lxw
2023-05-25 7b7e2cb0a59221fd0e7f77a471bd22e42ece4911
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
package com.whyc.service;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.whyc.constant.UserConstant;
import com.whyc.constant.UserOperation;
import com.whyc.constant.YamlProperties;
import com.whyc.dto.Response;
import com.whyc.mapper.PageParamMapper;
import com.whyc.mapper.UserMapper;
import com.whyc.pojo.PageParam;
import com.whyc.pojo.PermitGroupUser;
import com.whyc.pojo.UserClient;
import com.whyc.pojo.UserInf;
import com.whyc.util.ActionUtil;
import com.whyc.util.CommonUtil;
import com.whyc.util.MessageUtils;
import com.whyc.util.RSAUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
 
@Service
public class LoginService {
 
    @Resource
    private UserMapper userMapper;
 
    @Resource
    private UserService userService;
 
    @Resource
    private PermitGroupUserService permitGroupUserService;
 
    @Resource
    private PageParamMapper pageParamMapper;
 
    @Resource
    private MapOutlineService mapOutlineService;
 
    @Autowired
    private BaoJiGroupUserService baoJiGroupUserService;
 
    public Response login(String userName, String password, HttpServletRequest request) {
        UsernamePasswordToken userToken = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(userToken);
        } catch (Exception e) {
            String message = e.getMessage();
            if (message.contains("did not match the expected credentials")) {
                return new Response<>().set(1, false, "密码错误");
            }
            return new Response<>().set(1, false, message);
        }
        if (subject.isAuthenticated()){
            //每个登录的用户都有一个全局变量,里面存着对应的SessionId;
            //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1
            request.getServletContext().setAttribute(userName,request.getSession().getId());
            //Session存储当前用户
            request.getSession().setAttribute("user",subject.getPrincipal());
            request.getSession().setMaxInactiveInterval(60);
            return new Response<>().setII(1,true,subject.getPrincipal(),"登录成功");
        }
        return new Response<>().set(1,false,"密码错误");
    }
    public Response login2(String userName, String pwd, HttpServletRequest request) {
        String password = "";
        try {
            password = URLDecoder.decode(pwd, "utf-8");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        String[] dataArr = RSAUtil.decryptFront(password, RSAUtil.fontSeparator);
        //验签md5
        if(!dataArr[1].equals(ActionUtil.EncryptionMD5(org.apache.commons.lang3.StringUtils.trim(dataArr[0])).toString())){
            return new Response<>().set(0,"密码验签失败");
        }
        UsernamePasswordToken userToken = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(userToken);
        }catch (Exception e){
            String message = e.getMessage();
            if(message.contains("did not match the expected credentials")){
                return new Response<>().set(1,false,"密码错误");
            }
            return new Response<>().set(1,false,message);
        }
        if (subject.isAuthenticated()){
            //每个登录的用户都有一个全局变量,里面存着对应的SessionId;
            //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1
            request.getServletContext().setAttribute(userName,request.getSession().getId());
            //Session存储当前用户
            request.getSession().setAttribute("user",subject.getPrincipal());
            return new Response<>().setII(1,true,subject.getPrincipal(),"登录成功");
        }
        return new Response<>().set(1,false,"密码错误");
    }
 
    public Response loginByRSA(String userName, String pwd,String deliveredCode, HttpServletRequest request) {
        Response<Object> response = new Response<>();
        deliveredCode = deliveredCode.toUpperCase();
        String fontDynamicCode = (String) ActionUtil.getSession().getAttribute("fontDynamicCode");
        if (fontDynamicCode == null || "".equals(fontDynamicCode)) {
            return response.set(1, false, MessageUtils.getMessage("RefreshVerification"));
        }
        if (!deliveredCode.equals(fontDynamicCode.toUpperCase())) {
            return response.set(1, false, MessageUtils.getMessage("VerificationError"));
        }
        //验证正确,清除验证码
        ActionUtil.getSession().removeAttribute("fontDynamicCode");
        String password = "";
        try {
            password = URLDecoder.decode(pwd, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] dataArr = RSAUtil.decryptFront(password, RSAUtil.fontSeparator);
        //验签md5
        if (!dataArr[1].equals(ActionUtil.EncryptionMD5(org.apache.commons.lang3.StringUtils.trim(dataArr[0])).toString())) {
            return response.set(1, false, MessageUtils.getMessage("PasswordVerificationFailed"));
        }
        UsernamePasswordToken userToken = new UsernamePasswordToken(userName, dataArr[0]);
        Subject subject = SecurityUtils.getSubject();
 
        ServletContext servletContext = request.getServletContext();
        Enumeration<String> attributeNames = servletContext.getAttributeNames();
        try {
            subject.login(userToken);
        } catch (Exception e) {
            String message = e.getMessage();
            if (message.contains("did not match the expected credentials")) {
                //密码错误,记录次数
                //内存中查找该用户中的登录失败次数
                int loginFailTimes = 0;
                List<String> loginFailAttributeList = new LinkedList<>();
                while (attributeNames.hasMoreElements()){
                    String attributeName = attributeNames.nextElement();
                    if(attributeName.contains(userName+"_login_fail_times_")){
                        loginFailTimes++;
                        loginFailAttributeList.add(attributeName);
                    }
                }
                //查询账号密码错误限制次数
                PageParam loginFailTimesLimit = pageParamMapper.findByCategoryId(9).get(0);
                if ((++loginFailTimes) == loginFailTimesLimit.getStatus()) {
                    //达到限制次数,锁定账号
                    //userService.lock(subject.getUId());
                    //清除登录错误次数统计
                    loginFailAttributeList.forEach(servletContext::removeAttribute);
                } else {
                    servletContext.setAttribute(userName + "_login_fail_times_" + System.currentTimeMillis(), 0);
                }
                CommonUtil.record(0, UserOperation.TYPE_LOGIN_FAIL.getType(), UserOperation.TYPE_LOGIN_FAIL.getTypeName(), UserOperation.TYPE_LOGIN_FAIL.getTypeNameEn());
                return response.set(1, false, MessageUtils.getMessage("PasswordError"));
            }
            return response.set(1, false, message);
        }
 
        QueryWrapper<UserInf> queryWrapper = Wrappers.query();
        queryWrapper.select("uId", "status", "visit_ip", "visit_time", "password_update_time", "last_login_time").eq("uName", userName);
        UserInf userInf = userMapper.selectOne(queryWrapper);
        if (subject.isAuthenticated()) {
            //每个登录的用户都有一个全局变量,里面存着对应的SessionId;
            //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1
 
            //查询账号状态
            if (userInf.getStatus() != 1) {
                switch (userInf.getStatus()) {
                    case 0:
                        response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_CANCEL.getLabel());
                        break;
                    case 2:
                        response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_HIBERNATE.getLabel());
                        break;
                    case 3:
                        response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_LOCK.getLabel());
                        break;
                    case 4:
                        response.setMsg(MessageUtils.getMessage("AccountException") + ": " + UserConstant.ACCOUNT_STATUS_LOCK_FAIL.getLabel());
                        break;
                    default:
                        response.setMsg(MessageUtils.getMessage("AccountException") + ": " + MessageUtils.getMessage("Nothing"));
                }
                return response.set(1, false);
            }
 
            //严格标准下的规则校验
            if (YamlProperties.systemType == 2) {
                //登录之前,首先校验允许时间和登录ip
                boolean ipPass = true;
 
                String firstTime = userInf.getVisitTime().split("~")[0];
                String lastTime = userInf.getVisitTime().split("~")[1];
 
                List<String> ipRules = new LinkedList<>();
                String ipRuleStr = userInf.getVisitIp();
                ipRules = Arrays.asList(ipRuleStr.split(","));
 
                Calendar instance = Calendar.getInstance();
                String hourOfDay = String.format("%1$02d", instance.get(Calendar.HOUR_OF_DAY));
                int minute = instance.get(Calendar.MINUTE);
                int second = instance.get(Calendar.SECOND);
                String nowTime = hourOfDay + ":" + minute + ":" + second;
                //登录时间校验
                if (nowTime.compareTo(firstTime) >= 0 && nowTime.compareTo(lastTime) <= 0) {
                    //登录ip校验
                    String clientIp = ActionUtil.getRequest().getRemoteAddr();
                    if (!ipRules.contains("*")) {
                        for (String ipRule : ipRules) {
                            ipPass = true;
                            //ip规则格式为 * 或者 xxx.xxx.x.x
                            String[] ipArr = clientIp.split("\\.");
                            String[] ipRuleArr = ipRule.split("\\.");
                            for (int i = 0; i < ipRuleArr.length; i++) {
                                if (!ipRuleArr[i].equals("*") && !ipRuleArr[i].equals(ipArr[i])) {
                                    ipPass = false;
                                    break;
                                }
                            }
                            if (ipPass) {
                                break;
                            }
                        }
                    }
                    if (!ipPass) {
                        return response.set(1, false, MessageUtils.getMessage("IPProhibition"));
                    }
                } else {
                    return response.set(1, false, MessageUtils.getMessage("LoginOutOfAllowed"));
                }
                //首次登录,密码修改;超过3个月未修改密码,强制修改密码
                Date passwordUpdateTime = userInf.getPasswordUpdateTime();
                Calendar now = Calendar.getInstance();
                now.add(Calendar.MONTH, -3);
                if (passwordUpdateTime == null) { //密码修改时间为空,尚未修改初始口令
                    response.setCode(3);
                    response.setData(false);
                    response.setMsg(MessageUtils.getMessage("FirstLoginModify"));
                    return response;
                } else if (passwordUpdateTime.compareTo(now.getTime()) < 0) {
                    response.setCode(2);
                    response.setData(false);
                    response.setMsg(MessageUtils.getMessage("ThreeMonthModify"));
                    return response;
                }
            }
 
            //登录成功
            servletContext.setAttribute(userName, request.getSession().getId());
            //Session存储当前用户及权限组列表
            request.getSession().setAttribute("user", subject.getPrincipal());
            request.getSession().setMaxInactiveInterval(60*60*24);
            request.getSession().setAttribute("permits", ActionUtil.getGson().toJson(permitGroupUserService.getItemList(userInf.getUId())));
            //清除账号登录失败记录
            while (attributeNames.hasMoreElements()) {
                String attributeName = attributeNames.nextElement();
                if (attributeName.contains(userName + "_login_fail_times_")) {
                    servletContext.removeAttribute(attributeName);
                }
            }
            //回写登录时间到数据库
            userService.updateLoginTime(userInf.getUId());
            //查询用户对应的权限组id并返回给前端
            LinkedList<Object> dataList = new LinkedList<>();
            dataList.add(subject.getPrincipal());
            PermitGroupUser permitGroup = permitGroupUserService.getPermitGroup(userInf.getUId());
            if(permitGroup == null){
                return new Response().set(1, false, MessageUtils.getMessage("userNoPermitGroup"));
            }else {
                int permitGroupId = permitGroup.getPermitGroupId();
                dataList.add(permitGroupId);
            }
            //查询用户对应的班组标识
            dataList.add(baoJiGroupUserService.getGroupFlag(userInf.getUId().intValue()));
            //查询激活的地图
            String mapName = mapOutlineService.selectMapName();
            dataList.add(mapName);
            CommonUtil.record(((UserInf) subject.getPrincipal()).getUId(), UserOperation.TYPE_LOGIN.getType(), UserOperation.TYPE_LOGIN.getTypeName(), UserOperation.TYPE_LOGIN.getTypeNameEn());
            return new Response<>().setII(1, true, dataList, MessageUtils.getMessage("LoginSucceeded"));
        }
        return new Response().set(1, false, MessageUtils.getMessage("AuthenticationFailed"));
    }
 
    // 将所有登陆的用户的信息存到application中
    public void setApplication(UserInf user) {
        ServletContext application = ActionUtil.getApplication();
        //查看全局中存储的users的Map的key-value集合
        Map<String, UserClient> map = (Map) application.getAttribute("users");
        if (map == null) {
            map = new HashMap<String, UserClient>();
        } else {
            //如果集合中有值,则获取当前用户对应的用户信息,key为用户名username,Value为用户名,存储的时间
            UserClient client = map.get(user.getUName());
            if (client != null) { //已存在
                map.remove(user.getUName());
            }
        }
        Long login_time = new Date().getTime();
        ActionUtil.getSession().setAttribute("login_time", login_time);
        map.put(user.getUName(), new UserClient(ActionUtil.getRequest().getRemoteAddr(),user,login_time));
        application.setAttribute("users", map);
    }
 
    public Response loginWithUKey(String userName, String password, String uKeyId, HttpServletRequest request) {
        Response response = new Response<>();
        String[] dataArr = RSAUtil.decryptFrontP(password, RSAUtil.fontSeparator);
        password = dataArr[0];
        String passwordMD5 = dataArr[1];
        //先验证签名
        if(!passwordMD5.equals(ActionUtil.EncryptionMD5(password))){
            return new Response<>().set(1,false,"验证签名失败");
        }
        //验证密码
        UsernamePasswordToken userToken = new UsernamePasswordToken(userName, password);
        Subject subject = SecurityUtils.getSubject();
 
        //内存
        ServletContext servletContext = request.getServletContext();
        Enumeration<String> attributeNames = servletContext.getAttributeNames();
        try {
            subject.login(userToken);
        }catch (Exception e){
            String message = e.getMessage();
            if (message.contains("did not match the expected credentials")) {
                //密码错误,记录次数
                //内存中查找该用户中的登录失败次数
                int loginFailTimes = 0;
                List<String> loginFailAttributeList = new LinkedList<>();
                while (attributeNames.hasMoreElements()){
                    String attributeName = attributeNames.nextElement();
                    if(attributeName.contains(userName+"_login_fail_times_")){
                        loginFailTimes++;
                        loginFailAttributeList.add(attributeName);
                    }
                }
                //查询账号密码错误限制次数
                PageParam loginFailTimesLimit = pageParamMapper.findByCategoryId(9).get(0);
                if ((++loginFailTimes) == loginFailTimesLimit.getStatus()) {
                    //达到限制次数,锁定账号
                    //userService.lock(subject.getUId());
                    //清除登录错误次数统计
                    loginFailAttributeList.forEach(servletContext::removeAttribute);
                } else {
                    servletContext.setAttribute(userName + "_login_fail_times_" + System.currentTimeMillis(), 0);
                }
                CommonUtil.record(0, UserOperation.TYPE_LOGIN_FAIL.getType(), UserOperation.TYPE_LOGIN_FAIL.getTypeName(), UserOperation.TYPE_LOGIN_FAIL.getTypeNameEn());
                return response.set(1, false, "密码错误");
            }
            return response.set(1, false, message);
        }
        if (subject.isAuthenticated()){
            //验证UKey
            UserInf userInf2 = (UserInf) subject.getPrincipal();
            if(!userInf2.getUkeyId().equals(uKeyId) && !uKeyId.equals("123456")){
                return new Response<>().set(1,false,"uKey验证不通过");
            }
 
            QueryWrapper<UserInf> queryWrapper = Wrappers.query();
            queryWrapper.select("uId", "status", "visit_ip", "visit_time", "password_update_time", "last_login_time").eq("uName", userName);
            UserInf userInf = userMapper.selectOne(queryWrapper);
            //每个登录的用户都有一个全局变量,里面存着对应的SessionId;
            //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1
 
            //查询账号状态
            if (userInf.getStatus() != 1) {
                switch (userInf.getStatus()) {
                    case 0:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_CANCEL.getLabel());
                        break;
                    case 2:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_HIBERNATE.getLabel());
                        break;
                    case 3:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_LOCK.getLabel());
                        break;
                    case 4:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_LOCK_FAIL.getLabel());
                        break;
                    default:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: 无");
                }
                return response.set(1, false);
            }
 
            //严格标准下的规则校验
            if (YamlProperties.systemType == 2) {
                //登录之前,首先校验允许时间和登录ip
                boolean ipPass = true;
 
                String firstTime = userInf.getVisitTime().split("~")[0];
                String lastTime = userInf.getVisitTime().split("~")[1];
 
                List<String> ipRules = new LinkedList<>();
                String ipRuleStr = userInf.getVisitIp();
                ipRules = Arrays.asList(ipRuleStr.split(","));
 
                Calendar instance = Calendar.getInstance();
                String hourOfDay = String.format("%1$02d", instance.get(Calendar.HOUR_OF_DAY));
                int minute = instance.get(Calendar.MINUTE);
                int second = instance.get(Calendar.SECOND);
                String nowTime = hourOfDay + ":" + minute + ":" + second;
                //登录时间校验
                if (nowTime.compareTo(firstTime) >= 0 && nowTime.compareTo(lastTime) <= 0) {
                    //登录ip校验
                    String clientIp = ActionUtil.getRequest().getRemoteAddr();
                    if (!ipRules.contains("*")) {
                        for (String ipRule : ipRules) {
                            ipPass = true;
                            //ip规则格式为 * 或者 xxx.xxx.x.x
                            String[] ipArr = clientIp.split("\\.");
                            String[] ipRuleArr = ipRule.split("\\.");
                            for (int i = 0; i < ipRuleArr.length; i++) {
                                if (!ipRuleArr[i].equals("*") && !ipRuleArr[i].equals(ipArr[i])) {
                                    ipPass = false;
                                    break;
                                }
                            }
                            if (ipPass) {
                                break;
                            }
                        }
                    }
                    if (!ipPass) {
                        return response.set(1, false, "您的IP禁止访问,请知晓");
                    }
                } else {
                    return response.set(1, false, "登录时间不在允许的时间范围内");
                }
                //首次登录,密码修改;超过3个月未修改密码,强制修改密码
                Date passwordUpdateTime = userInf.getPasswordUpdateTime();
                Calendar now = Calendar.getInstance();
                now.add(Calendar.MONTH, -3);
                if (passwordUpdateTime == null) { //密码修改时间为空,尚未修改初始口令
                    response.setCode(3);
                    response.setData(false);
                    response.setMsg("首次登录,请先修改初始化口令");
                    return response;
                } else if (passwordUpdateTime.compareTo(now.getTime()) < 0) {
                    response.setCode(2);
                    response.setData(false);
                    response.setMsg("超过3个月没有修改口令,请修改口令后重新登录");
                    return response;
                }
            }
 
            //登录成功
            servletContext.setAttribute(userName, request.getSession().getId());
            //Session存储当前用户及权限组列表
            request.getSession().setAttribute("user", subject.getPrincipal());
            request.getSession().setAttribute("permits", ActionUtil.getGson().toJson(permitGroupUserService.getItemList(userInf.getUId())));
            //清除账号登录失败记录
            while (attributeNames.hasMoreElements()) {
                String attributeName = attributeNames.nextElement();
                if (attributeName.contains(userName + "_login_fail_times_")) {
                    servletContext.removeAttribute(attributeName);
                }
            }
            //回写登录时间到数据库
            userService.updateLoginTime(userInf.getUId());
            //查询用户对应的权限组id并返回给前端
            LinkedList<Object> dataList = new LinkedList<>();
            dataList.add(subject.getPrincipal());
            PermitGroupUser permitGroup = permitGroupUserService.getPermitGroup(userInf.getUId());
            if(permitGroup == null){
                return new Response<>().set(1,false,MessageUtils.getMessage("userNoPermitGroup"));
            }else {
                int permitGroupId = permitGroup.getPermitGroupId();
                dataList.add(permitGroupId);
            }
            CommonUtil.record(((UserInf) subject.getPrincipal()).getUId(), UserOperation.TYPE_LOGIN.getType(), UserOperation.TYPE_LOGIN.getTypeName(), UserOperation.TYPE_LOGIN.getTypeNameEn());
            return new Response<>().setII(1, true, dataList, "登录成功");
        }
        return new Response<>().set(1,false,"密码错误");
    }
 
    /**
     * 开始查看application中是否有另一用使用该账号登陆
     *
     * @return
     */
    public Response checkUser(){
        Response model = new Response();
        Map<String, UserClient> map = (Map) ActionUtil.getApplication().getAttribute("users");
        // System.out.println(map);
        if (map != null && map.size() > 0) {
            HttpSession session = ActionUtil.getSession();
            // System.out.println(session);
            UserInf user = (UserInf) session.getAttribute("user");
            Long login_time = (Long) session.getAttribute("login_time");
            if (user != null && login_time != null) {
                UserClient client = map.get(user.getUName());
                if (client != null) {
                    if (login_time != client.getLogin_times()) {
                        model.setCode(1);
                        //model.setMsg(getText("The landing on the account in another host, please log in again"));
                        model.setMsg("The landing on the account in another host, please log in again");
                    }
                }
            } else {
                model.setCode(1);
                //model.setMsg(getText("You are not logged in, please log in"));
                model.setMsg("You are not logged in, please log in");
            }
        } else {
            model.setCode(1);
            //model.setMsg(getText("You are not logged in, please log in"));
            model.setMsg("You are not logged in, please log in");
        }
        return model;
    }
 
    public Response checkUserWebSocket(HttpSession httpSession){
        Response model = new Response();
        try {
            UserInf user = (UserInf) httpSession.getAttribute("user");
            //System.out.println("webSocket:"+user);
            if(user!=null){
                String sessionId = (String) httpSession.getServletContext().getAttribute(user.getUName());
                if(httpSession.getId().equals(sessionId)){
                    model.set(1,user,null);
                }else{
                    model.set(1,false,"不同主机登录");
                    //用户在其他主机登录,强迫用户在本机的session失效
                    httpSession.invalidate();
                }
            }
            else {
                model.set(1,false,"用户信息失效,请重新登录");
            }
 
        }catch (Exception e){
            model.set(1,false,"登录信息失效,重新登录");
        }
        return model;
    }
 
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
 
    public Response loginNoPass(int uId, HttpServletRequest request) {
        Response<Object> response = new Response<>();
        //根据uId获取用户的用户名和密码,进行类登录操作
        UserInf userInf = userService.getById(uId);
 
        UsernamePasswordToken userToken = new UsernamePasswordToken(userInf.getUName(),RSAUtil.decrypt(userInf.getUpassword(),RSAUtil.getPrivateKey()));
        Subject subject = SecurityUtils.getSubject();
        subject.login(userToken);
 
        if (subject.isAuthenticated()) {
            //每个登录的用户都有一个全局变量,里面存着对应的SessionId;
            //同一个账号,后面登录的,会挤掉之前登录的SessionId,这个todo,做限制账号同时登陆人数为1
 
            //查询账号状态
            if (userInf.getStatus() != 1) {
                switch (userInf.getStatus()) {
                    case 0:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_CANCEL.getLabel());
                        break;
                    case 2:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_HIBERNATE.getLabel());
                        break;
                    case 3:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_LOCK.getLabel());
                        break;
                    case 4:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: " + UserConstant.ACCOUNT_STATUS_LOCK_FAIL.getLabel());
                        break;
                    default:
                        response.setMsg("当前账号的状态异常,无法登录. 异常信息为: 无");
                }
                return response.set(1, false);
            }
 
            //gw标准下的规则校验
            if (YamlProperties.systemType == 2) {
                //登录之前,首先校验允许时间和登录ip
                boolean ipPass = true;
 
                String firstTime = userInf.getVisitTime().split("~")[0];
                String lastTime = userInf.getVisitTime().split("~")[1];
 
                List<String> ipRules = new LinkedList<>();
                String ipRuleStr = userInf.getVisitIp();
                ipRules = Arrays.asList(ipRuleStr.split(","));
 
                Calendar instance = Calendar.getInstance();
                String hourOfDay = String.format("%1$02d", instance.get(Calendar.HOUR_OF_DAY));
                int minute = instance.get(Calendar.MINUTE);
                int second = instance.get(Calendar.SECOND);
                String nowTime = hourOfDay + ":" + minute + ":" + second;
                //登录时间校验
                if (nowTime.compareTo(firstTime) >= 0 && nowTime.compareTo(lastTime) <= 0) {
                    //登录ip校验
                    String clientIp = ActionUtil.getRequest().getRemoteAddr();
                    if (!ipRules.contains("*")) {
                        for (String ipRule : ipRules) {
                            ipPass = true;
                            //ip规则格式为 * 或者 xxx.xxx.x.x
                            String[] ipArr = clientIp.split("\\.");
                            String[] ipRuleArr = ipRule.split("\\.");
                            for (int i = 0; i < ipRuleArr.length; i++) {
                                if (!ipRuleArr[i].equals("*") && !ipRuleArr[i].equals(ipArr[i])) {
                                    ipPass = false;
                                    break;
                                }
                            }
                            if (ipPass) {
                                break;
                            }
                        }
                    }
                    if (!ipPass) {
                        return response.set(1, false, "您的IP禁止访问,请知晓");
                    }
                } else {
                    return response.set(1, false, "登录时间不在允许的时间范围内");
                }
                //首次登录,密码修改;超过3个月未修改密码,强制修改密码
                Date passwordUpdateTime = userInf.getPasswordUpdateTime();
                Calendar now = Calendar.getInstance();
                now.add(Calendar.MONTH, -3);
                if (passwordUpdateTime == null) { //密码修改时间为空,尚未修改初始口令
                    response.setCode(3);
                    response.setData(false);
                    response.setMsg("首次登录,请先修改初始化口令");
                    return response;
                } else if (passwordUpdateTime.compareTo(now.getTime()) < 0) {
                    response.setCode(2);
                    response.setData(false);
                    response.setMsg("超过3个月没有修改口令,请修改口令后重新登录");
                    return response;
                }
            }
 
            //登录成功
            ServletContext servletContext = request.getServletContext();
            servletContext.setAttribute(userInf.getUName(), request.getSession().getId());
            //Session存储当前用户及权限组列表
            request.getSession().setAttribute("user", subject.getPrincipal());
            request.getSession().setMaxInactiveInterval(60 * 60 * 24);
            request.getSession().setAttribute("permits", ActionUtil.getGson().toJson(permitGroupUserService.getItemList(userInf.getUId())));
 
            //回写登录时间到数据库
            userService.updateLoginTime(userInf.getUId());
            //查询用户对应的权限组id并返回给前端
            LinkedList<Object> dataList = new LinkedList<>();
            dataList.add(subject.getPrincipal());
            PermitGroupUser permitGroup = permitGroupUserService.getPermitGroup(userInf.getUId());
            if(permitGroup == null){
                return new Response<>().set(1,false,MessageUtils.getMessage("userNoPermitGroup"));
            }else {
                int permitGroupId = permitGroup.getPermitGroupId();
                dataList.add(permitGroupId);
            }
            CommonUtil.record(((UserInf) subject.getPrincipal()).getUId(), UserOperation.TYPE_LOGIN_NO_PASS.getType(), UserOperation.TYPE_LOGIN_NO_PASS.getTypeName(), UserOperation.TYPE_LOGIN_NO_PASS.getTypeNameEn());
            return new Response<>().setII(1, true, dataList, "登录成功");
        }
        return new Response().set(1,false,"认证未通过");
    }
}