LoginController.java
12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package com.glsx.usedcar.web.api;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.util.PhoneUtil;
import com.glsx.usedcar.module.account.domain.AccountInfo;
import com.glsx.usedcar.module.account.entity.Account;
import com.glsx.usedcar.module.account.service.AccountService;
import com.glsx.usedcar.module.security.domain.MaLoginRequest;
import com.glsx.usedcar.util.NameUtil;
import com.glsx.usedcar.web.AccountJwtProvider;
import com.glsx.usedcar.web.dto.LoginRequest;
import jakarta.annotation.Resource;
import jakarta.security.auth.message.AuthException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSession;
import me.chanjar.weixin.common.session.WxSessionManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.summerframework.core.exception.FieldException;
import org.summerframework.log.OplogType;
import org.summerframework.log.entity.Oplog;
import org.summerframework.log.service.OplogService;
import org.summerframework.security.Authenticity;
import org.summerframework.web.util.IpUtils;
import java.util.Objects;
import static com.glsx.usedcar.web.WebConstants.LOGIN_ACCOUNT;
@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController extends LoginCommonController {
@Resource
private AccountService accountService;
@Resource
private OplogService oplogService;
@Resource
private AccountJwtProvider jwtProvider;
@Resource
private WxSessionManager wxSessionManager;
@Resource
private WxMaService wxMaService;
@PostMapping("login")
public Authenticity doLogin(@ModelAttribute LoginRequest loginRequest, HttpServletRequest request) {
Account account;
Authenticity authenticity = new Authenticity(0, "");
try {
String userName = loginRequest.getUserName();
if (StringUtils.isNoneBlank(userName)) {
//账户密码登录
//手机号/邮箱登录密码登录
boolean mobile = PhoneUtil.isMobile(userName);
if (mobile) {
account = accountService.getAccountByMobile(userName);
} else if (userName.contains("@")) {
// customer = customerService.getCustomerByEmail(userName);
} else {
throw new AuthException("请输入正确的手机或者邮箱");
}
// if (Objects.isNull(account) || !new BCryptPasswordEncoder().matches(loginRequest.getPassword(), account.getPassword())) {
// throw new AuthException("手机或者邮箱或者密码错误");
// }
} else {
//手机验证码登录
account = accountService.getAccountByMobile(loginRequest.getMobile());
if (Objects.isNull(account)) {
throw new AuthException("手机号码尚未注册");
}
}
} catch (AuthException authException) {
log.info("登录失败:{}", authException.getMessage());
// authenticity.setSuccess(false);
// authenticity.setErrorText(authException.getMessage());
return authenticity;
}
// if (!account.isEnabled()) {
// authenticity.setErrorText("账户被锁定,请联系管理员");
// return authenticity;
// }
// oplogService.pushOplog(new Oplog(OplogType.LOGIN, "", "【客户端】登录成功", "", "", account.getAccountName(), IpUtils.getIpAddress(request)));
// authenticity.setSuccess(true);
// authenticity.setCustomer(account);
// authenticity.setToken(jwtProvider.generateAccount(account));
// request.getSession().setAttribute(LOGIN_ACCOUNT, account);
return authenticity;
}
/**
* <pre>
* 小程序手机号登录
* </pre>
*/
@PostMapping("/ma/{appid}/phoneLogin")
public AccountInfo phone(@PathVariable String appid, @RequestBody MaLoginRequest maLoginRequest, HttpSession httpSession, HttpServletRequest request) throws FieldException, WxErrorException {
if (!wxMaService.switchover(appid)) {
throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid));
}
String code = maLoginRequest.getCode();
String encryptedData = maLoginRequest.getEncryptedData();
String iv = maLoginRequest.getIv();
WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
String sessionKey = session.getSessionKey();
String openid = session.getOpenid();
// 解密
String phoneNumber;
try {
WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
phoneNumber = phoneNoInfo.getPhoneNumber();
} catch (Exception e) {
log.error("小程序登录失败:解密失败", e);
throw new WxErrorException("获得手机号码失败");
} finally {
WxMaConfigHolder.remove();//清理ThreadLocal
}
AccountInfo accountInfo = new AccountInfo();
Account account = accountService.getAccountByMobile(phoneNumber);
if (Objects.isNull(account)) {
// 创建新用户
account = new Account();
account.setOpenId(openid);
account.setAccountName(phoneNumber);
account.setMobile(phoneNumber);
account.setNickName(NameUtil.getName());
account.setEnabled(true);
account.setCertifiedState(Account.CertifiedState.UNCERTIFIED);
account.setAccountType(Account.AccountType.COMMON);
account = accountService.addAccount(account);
} else {
if (!account.isEnabled()) {
accountInfo.setStatus(403);
accountInfo.setMessage("账户被锁定,请联系管理员");
return accountInfo;
}
accountService.updateAccountLoginTime(account.getAccountId());
}
if (StringUtils.isNoneBlank(openid) && !openid.equals(account.getOpenId())) {
accountService.updateWxOpenId(account.getAccountId(), openid);
}
oplogService.pushOplog(new Oplog(OplogType.LOGIN, "", "【小程序】登录成功", "", "", account.getAccountName(), IpUtils.getIpAddress(request)));
accountInfo.setToken(jwtProvider.generateAccount(account));
accountInfo.setAccountInfo(account);
request.getSession().setAttribute(LOGIN_ACCOUNT, account);
return accountInfo;
}
// /**
// * 扫小程序码登录
// */
// @GetMapping("/maWxCode")
// public WxCodeResult maWxCode() {
// WxCodeResult wxCodeResult = new WxCodeResult();
// String random = RandomStringUtils.randomAlphanumeric(16);
// try {
// byte[] trials = wxMaService.getQrcodeService().createWxaCodeUnlimitBytes(random, null, false, "release", 320,
// true, null, true);
// String encode = "data:image/png;base64," + Base64.encode(trials);
// wxCodeResult.setSuccess(true);
// wxCodeResult.setScene(random);
// wxCodeResult.setWxCodeBase64(encode);
// } catch (Exception e) {
// e.printStackTrace();
// wxCodeResult.setSuccess(false);
// wxCodeResult.setMsg("小程序码获取失败,请刷新页面重试");
// }
// return wxCodeResult;
// }
// @GetMapping("/getMaWxCodeStatus")
// public ResponseResult getMaWxCodeStatus(@RequestParam String scene, HttpServletRequest request) {
// Account customer = redisService.getCodeLogin(scene);
// if (Objects.nonNull(customer)) {
// request.getSession().setAttribute(LOGIN_ACCOUNT, customer);
// oplogService.pushOplog(new Oplog(OplogType.LOGIN, "", "【web扫码】登录成功", "", "", customer.getAccountName(), IpUtils.getIpAddress(request)));
// Authenticity authenticity = new Authenticity(0, "");
//// authenticity.setCustomer(customer);
// authenticity.setToken(jwtProvider.generateAccount(customer));
// return new ResponseResult(ResponseResult.Result.SUCCESS, authenticity);
// } else {
// return new ResponseResult(ResponseResult.Result.FAILURE);
// }
// }
/**
* 个人账户中绑定微信号
*
* @param ticket
* @param login
* @return
* @throws FieldException
*/
@GetMapping("getQrCodeStatus")
public boolean getQrCodeStatus(@RequestParam("qid") String ticket, @RequestAttribute(LOGIN_ACCOUNT) Account login) throws FieldException {
WxSession session = wxSessionManager.getSession(ticket);
if (Objects.nonNull(session)) {
Object status = session.getAttribute("status");
Object openId = session.getAttribute("openId");
if ("ok".equals(status) && Objects.nonNull(openId)) {
// 扫码通过
String wxOpenId = openId.toString();
Account customer = accountService.getAccountByOpenId(wxOpenId);
if (Objects.isNull(customer)) {
accountService.updateWxOpenId(login.getAccountId(), wxOpenId);
} else {
throw new FieldException("wx", null, "该微信号已绑定账户");
}
session.removeAttribute("status");
return true;
}
}
return false;
}
/**
* 个人账户修改手机原号码校验
*
* @param loginRequest
* @param request
* @return
* @throws FieldException
*/
@PostMapping("checkSmsCode")
public String checkSmsCode(@RequestBody LoginRequest loginRequest, HttpServletRequest request) throws FieldException {
HttpSession httpSession = request.getSession();
String mobile = loginRequest.getMobile();
String smsCode = loginRequest.getSmsCode();
log.info("原号码校验:{},{}", mobile, smsCode);
String code;
try {
validateSmsCode(httpSession, mobile, smsCode);
// 提交新号码时带回用于新号码校验
code = new BCryptPasswordEncoder().encode(mobile);
// 5分钟内有效
httpSession.setAttribute(code, System.currentTimeMillis() + 60 * 5000);
} catch (AuthException e) {
log.info("原号码校验失败:{}", e.getMessage());
throw new FieldException("smsCode", null, e.getMessage());
}
return code;
}
/**
* 个人账户修改手机新号码校验
*
* @param loginRequest
* @param request
* @param customer
* @return
* @throws FieldException
*/
@PostMapping("checkSmsCodeByNewMobile")
public boolean checkSmsCodeByNewMobile(@RequestBody LoginRequest loginRequest, HttpServletRequest request, @RequestAttribute(LOGIN_ACCOUNT) Account customer) throws FieldException {
HttpSession httpSession = request.getSession();
String mobile = loginRequest.getMobile();
String smsCode = loginRequest.getSmsCode();
log.info("新号码校验:{},{}", mobile, smsCode);
try {
validateSmsCode(httpSession, mobile, smsCode);
Long val = (Long) httpSession.getAttribute(loginRequest.getCode());
customer = accountService.getAccountById(customer.getAccountId());
if (Objects.nonNull(customer.getMobile()) && Objects.nonNull(val) && System.currentTimeMillis() - val > 0L) {
throw new FieldException("smsCode", null, "原号码验证已过期,请重新修改");
}
customer.setMobile(mobile);
accountService.updateMobile(customer);
} catch (AuthException e) {
log.info("新号码校验失败:{}", e.getMessage());
throw new FieldException("smsCode", null, e.getMessage());
}
return true;
}
}