UserController.java
17.9 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package com.bsth.controller.sys;
import com.bsth.common.Constants;
import com.bsth.common.ResponseCode;
import com.bsth.controller.BaseController;
import com.bsth.controller.sys.dto.CompanyData;
import com.bsth.controller.sys.util.RSAUtils;
import com.bsth.entity.sys.CompanyAuthority;
import com.bsth.entity.sys.Role;
import com.bsth.entity.sys.SysUser;
import com.bsth.security.SsoConfig;
import com.bsth.security.util.SecurityUtils;
import com.bsth.service.sys.CompanyAuthorityService;
import com.bsth.service.sys.SysUserService;
import com.bsth.util.HttpClientUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ArrayListMultimap;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@RestController
@RequestMapping("user")
public class UserController extends BaseController<SysUser, Integer> {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
SysUserService sysUserService;
@Autowired
CompanyAuthorityService companyAuthorityService;
private ObjectMapper mapper = new ObjectMapper();
@Autowired
private SsoConfig ssoConfig;
private Pattern pattern = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*?[#?!@$%^&*-.]).{8,16}$");
@RequestMapping(value = "/login/jCryptionKey")
public Map<String, Object> jCryptionKey(HttpServletRequest request) {
//公匙返回页面
Map<String, Object> rs = new HashMap<>();
rs.put("publickey", RSAUtils.generateBase64PublicKey());
return rs;
}
@RequestMapping(value = "/getCurrentUser")
public SysUser getCurrentUser() {
SysUser user = SecurityUtils.getCurrentUser();
return user;
}
//需要验证码的账号
public static Map<String, Integer> USER_ERRTIMES = new HashMap<>();
public static Map<String, Long> USER_LOCKTIME = new HashMap<>();
@RequestMapping(value = "/login/token")
public void login(@RequestParam String token, @RequestParam String account, @RequestParam Long time, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.addHeader("Content-Type", "text/html;charset=UTF-8");
if (!ssoConfig.isSsoEnabled()) {
response.getWriter().write("系统未开启统一登录配置,请联系管理员");
return;
}
if (token == null || account == null || time == null) {
throw new IllegalArgumentException("请检查参数");
}
Map<String, Object> param = new HashMap<>(), user = new HashMap<>();
param.put("token", token);
param.put("systemCode", ssoConfig.getSystemCode());
StringBuilder sb = HttpClientUtils.post(ssoConfig.getSsoAuthUrl(), mapper.writeValueAsString(param));
Assert.notNull(sb, "统一登录平台验证数据不为空");
logger.info(String.format("统一登录平台:%s", sb.toString()));
param = mapper.readValue(mapper.writeValueAsString(mapper.readValue(sb.toString(), Map.class).get("data")), Map.class);
String jobCode = (String) param.get("account"), realName = (String) param.get("userName");
if (!account.equals(jobCode)) {
response.getWriter().write("token与用户不匹配");
return;
}
if (jobCode == null || realName == null) {
response.getWriter().write("token数据异常");
return;
}
user.put("jobCode_eq", jobCode);
user.put("realName_eq", realName);
user.put("enabled", true);
Iterator<SysUser> userIterator = sysUserService.list(user).iterator();
SysUser sysUser = null;
while (userIterator.hasNext()) {
sysUser = userIterator.next();
break;
}
if (sysUser != null) {
HttpSession session = request.getSession();
// 登录
SecurityUtils.login(sysUser, request);
sysUserService.recordLoginDate(sysUser.getUserName());
//session里写入用户名,webSocket连接时标识身份用
session.setAttribute(Constants.SSO_TOKEN, token);
session.setAttribute(Constants.SESSION_USERNAME, sysUser.getUserName());
session.setAttribute(Constants.RESOURCE_AUTHORITYS, sysUser.getLinks());
//获取公司权限数据
List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(sysUser);
session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
USER_ERRTIMES.remove(sysUser.getUserName());
logger.error(String.format("用户: %s登录, token: %s",sysUser.getUserName(), token));
response.sendRedirect("/pages/home.html");
} else {
response.getWriter().write("未找到有效的用户,请联系管理员");
}
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public Map<String, Object> login(HttpServletRequest request, @RequestParam String userName,
@RequestParam String password, String captcha) {
Map<String, Object> rs = new HashMap<>();
rs.put("status", ResponseCode.ERROR);
try {
HttpSession session = request.getSession();
rs.put("captcha", session.getAttribute("captcha"));
//解密RSA
try {
userName = RSAUtils.decryptBase64(userName);
password = RSAUtils.decryptBase64(password);
} catch (RuntimeException e) {
return put(rs, "msg", "decrypt RSA fail!可能页面已过期,尝试刷新页面。");
}
SysUser user = sysUserService.findByUserName(userName);
if (null == user) {
userOrPasswordInvalid(rs, userName);
return rs;
}
// 校验用户状态
if (!user.isEnabled()) {
return put(rs, "msg", "该用户已被锁定,请联系管理员");
}
// 校验临时状态
if (USER_LOCKTIME.get(userName) != null && USER_LOCKTIME.get(userName) >= System.currentTimeMillis()) {
return put(rs, "msg", "您的账户因密码错误次数过多,处于锁定状态中");
}
// 校验验证码
if (USER_ERRTIMES.get(userName) != null && USER_ERRTIMES.get(userName) > 1) {
String verCode = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
if (StringUtils.isBlank(captcha)) {
return put(rs, "msg", "请输入验证码");
}
if (!verCode.equals(captcha)) {
return put(rs, "msg", "验证码有误,请刷新后重新输入");
}
}
// 校验密码
boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
if (!matchStatus) {
userOrPasswordInvalid(rs, userName);
return rs;
}
// 弱密码检查
Matcher matcher = pattern.matcher(password);
if (!matcher.matches()) {
session.setAttribute(Constants.WEAK_CIPHER, 1);
}
// 登录
SecurityUtils.login(user, request);
sysUserService.recordLoginDate(userName);
//session里写入用户名,webSocket连接时标识身份用
session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
session.setAttribute(Constants.RESOURCE_AUTHORITYS, user.getLinks());
//获取公司权限数据
List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
USER_ERRTIMES.remove(userName);
rs.put("status", ResponseCode.SUCCESS);
logger.error("用户:" + user.getUserName() + "登录");
} catch (Exception e) {
logger.error("", e);
rs.put("msg", "服务器出现异常,请联系管理员");
}
return rs;
}
private void userOrPasswordInvalid(Map<String, Object> rs, String userName) {
rs.put("msg", "密码有误");
Integer errTimes = USER_ERRTIMES.get(userName);
if (null == errTimes) {
errTimes = 0;
}
USER_ERRTIMES.put(userName, ++errTimes);
if (errTimes > 3) {
USER_LOCKTIME.put(userName, System.currentTimeMillis() + 600000);
USER_ERRTIMES.put(userName, 0);
put(rs, "msg", "密码错误4次,账户将被锁定10分钟");
}
}
@RequestMapping(value = "/change_user", method = RequestMethod.POST)
public Map<String, Object> changeUser(HttpServletRequest request, @RequestParam String userName,
@RequestParam String password) {
Map<String, Object> rs = new HashMap<>();
rs.put("status", ResponseCode.ERROR);
try {
HttpSession session = request.getSession();
SysUser user = sysUserService.findByUserName(userName);
if (null == user)
return put(rs, "msg", "不存在的用户");
if (!user.isEnabled())
return put(rs, "msg", "该用户已被锁定,请联系管理员");
// 校验密码
boolean matchStatus = new BCryptPasswordEncoder(4).matches(password, user.getPassword());
if (!matchStatus)
return put(rs, "msg", "密码有误");
// 登录
SecurityUtils.login(user, request);
//session里写入用户名,webSocket连接时标识身份用
session.setAttribute(Constants.SESSION_USERNAME, user.getUserName());
session.setAttribute(Constants.RESOURCE_AUTHORITYS, user.getLinks());
//获取公司权限数据
List<CompanyAuthority> cmyAuths = companyAuthorityService.findByUser(user);
session.setAttribute(Constants.COMPANY_AUTHORITYS, cmyAuths);
rs.put("status", ResponseCode.SUCCESS);
} catch (Exception e) {
logger.error("", e);
rs.put("msg", "服务器出现异常,请联系管理员");
}
return rs;
}
/**
* 返回当前用户的公司权限数据,用于构建页面级联下拉框
*
* @return
*/
@RequestMapping("companyData")
public List<CompanyData> companyData(HttpServletRequest request) {
List<CompanyData> rs = new ArrayList<>();
CompanyData companyData;
ArrayListMultimap<String, CompanyAuthority> map = ArrayListMultimap.create();
List<CompanyAuthority> cmyAuths = (List<CompanyAuthority>) request.getSession().getAttribute(Constants.COMPANY_AUTHORITYS);
for (CompanyAuthority cAuth : cmyAuths) {
map.put(cAuth.getCompanyCode() + "_" + cAuth.getCompanyName(), cAuth);
}
Set<String> keys = map.keySet();
String[] temps;
for (String k : keys) {
temps = k.split("_");
companyData = new CompanyData();
companyData.setCompanyCode(temps[0]);
companyData.setCompanyName(temps[1]);
companyData.setChildren(new ArrayList<CompanyData.ChildrenCompany>());
cmyAuths = map.get(k);
for (CompanyAuthority c : cmyAuths) {
companyData.getChildren().add(new CompanyData.ChildrenCompany(c.getSubCompanyCode(), c.getSubCompanyName()));
}
rs.add(companyData);
}
return rs;
}
@RequestMapping(value = "/login/captchaStatus")
public int captchaStatus(String userName) {
Integer size = USER_ERRTIMES.get(userName);
return size == null ? 0 : size;
}
public Map<String, Object> put(Map<String, Object> rs, String key, Object val) {
rs.put(key, val);
return rs;
}
/**
* @Title: loginFailure @Description: TODO(查询登录失败的详细信息) @param @param
* request @return String 返回类型 @throws
*/
@RequestMapping("/loginFailure")
public String loginFailure(HttpServletRequest request) {
String msg = "";
HttpSession session = request.getSession();
Object obj = session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
if (obj instanceof BadCredentialsException)
msg = "登录失败,用户名或密码错误.";
else if (obj instanceof SessionAuthenticationException)
msg = "登录失败,当前策略不允许重复登录.";
session.removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
return msg;
}
@RequestMapping("/currentUser")
public SysUser currentUser() {
return SecurityUtils.getCurrentUser();
}
/**
* @param id 用户ID
* @param enabled 状态
* @return
* @Title changeEnabled
* @Description: TODO(改变用户状态)
*/
@RequestMapping("/changeEnabled")
public int changeEnabled(@RequestParam int id, @RequestParam int enabled) {
return sysUserService.changeEnabled(id, enabled);
}
/**
* @param oldPWD 原始密码
* @param newPWD 新密码
* @param cnewPWD 确认新密码
* @return
* @Title changePWD
* @Description: TODO(修改密码)
*/
@RequestMapping(value = "/changePWD", method = RequestMethod.POST)
public String changePWD(@RequestParam String oldPWD, @RequestParam String newPWD, @RequestParam String cnewPWD, HttpServletRequest request) {
SysUser sysUser = SecurityUtils.getCurrentUser();
String msg = "";
//解密RSA
try{
oldPWD = (RSAUtils.decryptBase64(oldPWD));
newPWD = (RSAUtils.decryptBase64(newPWD));
cnewPWD = (RSAUtils.decryptBase64(cnewPWD));
}catch (RuntimeException e) {
return "网络延迟,解密失败,请重新添加!";
}
if (new BCryptPasswordEncoder(4).matches(oldPWD, sysUser.getPassword())) {
if (oldPWD.equals(newPWD)) {
msg = "新密码不能跟原始密码一样!";
} else {
if (newPWD.equals(cnewPWD)) {
sysUserService.changePWD(sysUser.getId(), newPWD);
request.getSession().setAttribute(Constants.WEAK_CIPHER, 0);
msg = "修改成功!";
} else {
msg = "新密码两次输入不一致!";
}
}
} else {
msg = "原始密码错误!";
}
return msg;
}
@RequestMapping(value = "/validPWDExpired", method = RequestMethod.GET)
public String validPWDExpired() {
try {
SysUser sysUser = SecurityUtils.getCurrentUser();
this.sysUserService.validPWDExpired(sysUser.getUserName());
return "ok";
} catch (Exception exp) {
exp.printStackTrace();
return exp.getMessage();
}
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public Map<String, Object> register(SysUser u) {
return sysUserService.register(u);
}
// 查询用户下所有下级角色
@RequestMapping(value = "/all_distinct")
public List<SysUser> findAll_distinct() {
return sysUserService.findAll_distinct();
}
// 重置密码
@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
public Map<String, Object> resetPassword(@RequestParam Integer id, @RequestParam Integer pwdValidPeriod) {
return sysUserService.resetPassword(id, pwdValidPeriod);
}
/**
* 解除临时锁定
* @param userName
* @return
*/
@RequestMapping(value = "/unlock", method = RequestMethod.POST)
public Map<String, Object> unlock(@RequestParam String userName) {
Map<String, Object> result = new HashMap<>();
// 获取当前用户
SysUser user = SecurityUtils.getCurrentUser();
Iterator<Role> itRole = user.getRoles().iterator();
Role ro = new Role();
boolean isSuper = false;
while (itRole.hasNext()) {//判断是否有下一个
ro = itRole.next();
if (ro.getLevel() == 1) {
isSuper = true;
}
}
if (isSuper) {
USER_LOCKTIME.remove(userName);
USER_ERRTIMES.remove(userName);
result.put("status", ResponseCode.SUCCESS);
result.put("msg", "用户解锁成功!");
} else {
result.put("status", ResponseCode.ERROR);
result.put("msg", "您不是管理员无用户解锁权限");
}
return result;
}
/**
* 弱密码
* @param request
* @return
*/
@RequestMapping(value = "/isWeakCipher", method = RequestMethod.POST)
public Map<String, Object> isWeakCipher(HttpServletRequest request) {
Map<String, Object> result = new HashMap<>();
result.put("status", ResponseCode.SUCCESS);
result.put("data", request.getSession().getAttribute(Constants.WEAK_CIPHER));
return result;
}
}