From d8e2cd27eed45224faecb07ca45be69bf78611af Mon Sep 17 00:00:00 2001
From: whyclxw <810412026@qq.com>
Date: 星期三, 14 五月 2025 15:18:28 +0800
Subject: [PATCH] 用户登录rsa

---
 src/main/java/com/whyc/service/LoginService.java |  297 +++++++++++++++++++++++++++-------------------------------
 1 files changed, 138 insertions(+), 159 deletions(-)

diff --git a/src/main/java/com/whyc/service/LoginService.java b/src/main/java/com/whyc/service/LoginService.java
index 9d1e2aa..33c9e1a 100644
--- a/src/main/java/com/whyc/service/LoginService.java
+++ b/src/main/java/com/whyc/service/LoginService.java
@@ -2,19 +2,21 @@
 
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.whyc.constant.UserConstant;
 import com.whyc.constant.YamlProperties;
 import com.whyc.dto.Response;
 import com.whyc.dto.UserClient;
+import com.whyc.mapper.PageParamMapper;
 import com.whyc.mapper.UserMapper;
+import com.whyc.pojo.db_app_sys.PageParam;
+import com.whyc.pojo.db_user.PermitgroupUsr;
 import com.whyc.pojo.db_user.User;
-import com.whyc.util.CommonUtil;
-import com.whyc.util.DateUtil;
-import com.whyc.util.MessageUtils;
-import com.whyc.util.RSAUtil;
+import com.whyc.util.*;
 import org.apache.shiro.SecurityUtils;
 import org.apache.shiro.authc.AuthenticationException;
 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;
@@ -31,62 +33,16 @@
     private UserMapper userMapper;
 
     @Resource
+    private PageParamMapper pageParamMapper;
+
+    @Resource
     private UserService userService;
 
+    @Resource
+    private PermitGroupUserService permitGroupUserService;
 
-    public Response login(String name, String pwd, HttpServletRequest request) {
-        UsernamePasswordToken userToken = new UsernamePasswordToken(name, pwd);
-        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()){
-            //姣忎釜鐧诲綍鐨勭敤鎴烽兘鏈変竴涓叏灞�鍙橀噺,閲岄潰瀛樼潃瀵瑰簲鐨凷essionId;
-            //鍚屼竴涓处鍙�,鍚庨潰鐧诲綍鐨�,浼氭尋鎺変箣鍓嶇櫥褰曠殑SessionId,杩欎釜todo,鍋氶檺鍒惰处鍙峰悓鏃剁櫥闄嗕汉鏁颁负1
-            request.getServletContext().setAttribute(name,request.getSession().getId());
-            //Session瀛樺偍褰撳墠鐢ㄦ埛
-            request.getSession().setAttribute("user",subject.getPrincipal());
-            //request.getSession().setMaxInactiveInterval(600);
-            return new Response<>().setII(1,true,subject.getPrincipal(),"鐧诲綍鎴愬姛");
-        }
-        return new Response<>().set(1,false,"瀵嗙爜閿欒");
-    }
-    public Response login2(String userName, String pwd, HttpServletRequest request) throws UnsupportedEncodingException {
-        //String password = URLDecoder.decode(pwd, "utf-8");
-        String password = pwd;
-
-        String[] dataArr = RSAUtil.decryptFront(password, RSAUtil.fontSeparator);
-        //楠岀md5
-        if(!dataArr[1].equals(CommonUtil.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()){
-            //姣忎釜鐧诲綍鐨勭敤鎴烽兘鏈変竴涓叏灞�鍙橀噺,閲岄潰瀛樼潃瀵瑰簲鐨凷essionId;
-            //鍚屼竴涓处鍙�,鍚庨潰鐧诲綍鐨�,浼氭尋鎺変箣鍓嶇櫥褰曠殑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,"瀵嗙爜閿欒");
-    }
+    @Autowired
+    private BaojigroupService bjService;
 
     public Response loginByRSA(String userName, String pwd, String deliveredCode, HttpServletRequest request, Integer validCode) {
         Response<Object> response = new Response<>();
@@ -96,7 +52,7 @@
         deliveredCode = deliveredCode.toUpperCase(Locale.ENGLISH);
         if(validCode ==null ) { //灞炴�т笉瀛樺湪,鍒欒繘琛岄獙璇佺爜鏍¢獙;灞炴�у瓨鍦�,鍒欎笉杩涜楠岃瘉鐮佹牎楠�
             if (YamlProperties.fontDynamicCodeSwitch.toLowerCase(Locale.ENGLISH).equals("true")) {
-                String fontDynamicCode = (String) CommonUtil.getSession().getAttribute("fontDynamicCode");
+                String fontDynamicCode = (String) ActionUtil.getSession().getAttribute("fontDynamicCode");
                 if (fontDynamicCode == null || "".equals(fontDynamicCode)) {
                     return response.set(1, false, MessageUtils.getMessage("RefreshVerification"));
                 }
@@ -106,7 +62,7 @@
             }
         }
         //楠岃瘉姝g‘,娓呴櫎楠岃瘉鐮�
-        CommonUtil.getSession().removeAttribute("fontDynamicCode");
+        ActionUtil.getSession().removeAttribute("fontDynamicCode");
         /*String password = "";
         try {
             password = URLDecoder.decode(pwd, "utf-8");
@@ -115,7 +71,7 @@
         }*/
         String[] dataArr = RSAUtil.decryptFront(pwd, RSAUtil.fontSeparator);
         //楠岀md5
-        if (!dataArr[1].equals(CommonUtil.EncryptionMD5(org.apache.commons.lang3.StringUtils.trim(dataArr[0])).toString())) {
+        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]);
@@ -125,14 +81,96 @@
         Enumeration<String> attributeNames = servletContext.getAttributeNames();
 
         QueryWrapper<User> queryWrapper = Wrappers.query();
-        queryWrapper.select("uId", "status", "visit_ip", "visit_time", "password_update_time", "last_login_time").eq("uName", userName);
-        User user = userMapper.selectOne(queryWrapper);
+        queryWrapper.select("id", "status", "visit_ip", "visit_time", "password_update_time", "last_login_time").eq("name", userName);
+        User userInf = userMapper.selectOne(queryWrapper);
         //姣忎釜鐧诲綍鐨勭敤鎴烽兘鏈変竴涓叏灞�鍙橀噺,閲岄潰瀛樼潃瀵瑰簲鐨凷essionId;
         //鍚屼竴涓处鍙�,鍚庨潰鐧诲綍鐨�,浼氭尋鎺変箣鍓嶇櫥褰曠殑SessionId,杩欎釜todo,鍋氶檺鍒惰处鍙峰悓鏃剁櫥闄嗕汉鏁颁负1
 
         //鏌ヨ璐﹀彿鐘舵��
-        if(user == null){
+        if(userInf == null){
             return response.set(1,false,MessageUtils.getMessage("AccountOrPasswordError"));
+        }
+        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) {
+            //鐧诲綍涔嬪墠,棣栧厛鏍¢獙鍏佽鏃堕棿鍜岀櫥褰昳p
+            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) { //瀵嗙爜淇敼鏃堕棿涓虹┖,灏氭湭淇敼鍒濆鍙d护
+                /*response.setCode(3);
+                response.setData(false);
+                response.setMsg(MessageUtils.getMessage("FirstLoginModify"));
+                return response;*/
+                response.setData3(2);
+            } else if (passwordUpdateTime.compareTo(now.getTime()) < 0) {
+                /*response.setCode(2);
+                response.setData(false);
+                response.setMsg(MessageUtils.getMessage("ThreeMonthModify"));
+                return response;*/
+                response.setData3(3);
+            }
         }
 
         try {
@@ -152,6 +190,16 @@
                     }
                 }
                 //鏌ヨ璐﹀彿瀵嗙爜閿欒闄愬埗娆℃暟
+                PageParam loginFailTimesLimit = pageParamMapper.findByCategoryId(9).get(0);
+                if ((++loginFailTimes) == loginFailTimesLimit.getStatus()) {
+                    //杈惧埌闄愬埗娆℃暟,閿佸畾璐﹀彿
+                    userService.lock(userInf.getId());
+                    //娓呴櫎鐧诲綍閿欒娆℃暟缁熻
+                    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("AccountOrPasswordError"));
             }else if(e instanceof AuthenticationException){
                 return response.set(1, false, "瀵嗙爜瑙f瀽澶辫触");
@@ -160,6 +208,11 @@
         }
 
         if (subject.isAuthenticated()) {
+            //楠岃瘉瀵嗙爜鏃舵晥鎬�
+            int flag=userService.checkPasswordValidity(userInf);
+            if(flag==-1){
+                return response.set(1, false, "瀵嗙爜闀挎湡鏈慨鏀瑰凡澶辨晥,璇蜂慨鏀瑰瘑鐮�");
+            }
             //鐧诲綍鎴愬姛
             servletContext.setAttribute(userName, request.getSession().getId());
             //鏃ョ櫥褰曠敤鎴风粺璁�
@@ -170,9 +223,12 @@
             }
             String dateStr = DateUtil.YYYY_MM_DD.format(new Date());
             loginMap.put(userName, dateStr);
+            /*//绱璁块棶浜烘
+            pageParam2Service.updateVisitCount();*/
             //Session瀛樺偍褰撳墠鐢ㄦ埛鍙婃潈闄愮粍鍒楄〃
             request.getSession().setAttribute("user", subject.getPrincipal());
-            //request.getSession().setMaxInactiveInterval(60*60*24);
+            request.getSession().setMaxInactiveInterval(60*60*24);
+            request.getSession().setAttribute("permits", ActionUtil.getGson().toJson(permitGroupUserService.getItemList(userInf.getId())));
             //娓呴櫎璐﹀彿鐧诲綍澶辫触璁板綍
             while (attributeNames.hasMoreElements()) {
                 String attributeName = attributeNames.nextElement();
@@ -181,91 +237,43 @@
                 }
             }
             //鍥炲啓鐧诲綍鏃堕棿鍒版暟鎹簱
+            userService.updateLoginTime(userInf.getId());
             //鏌ヨ鐢ㄦ埛瀵瑰簲鐨勬潈闄愮粍id骞惰繑鍥炵粰鍓嶇
             LinkedList<Object> dataList = new LinkedList<>();
             dataList.add(subject.getPrincipal());
-
+            PermitgroupUsr permitGroup = permitGroupUserService.getPermitGroup(userInf.getId());
+            if(permitGroup == null){
+                return response.set(1, false, MessageUtils.getMessage("userNoPermitGroup"));
+            }else {
+                int permitGroupId = permitGroup.getPermitGroupId();
+                dataList.add(permitGroupId);
+            }
+            //鏌ヨ鐢ㄦ埛瀵瑰簲鐨勭彮缁勬爣璇�
+            dataList.add(bjService.getGroupFlag(userInf.getId().intValue()));
+           // CommonUtil.record(((User) subject.getPrincipal()).getId(), UserOperation.TYPE_LOGIN.getType(), UserOperation.TYPE_LOGIN.getTypeName(), UserOperation.TYPE_LOGIN.getTypeNameEn());
             return response.setII(1, true, dataList, MessageUtils.getMessage("LoginSucceeded"));
         }
         return response.set(1, false, MessageUtils.getMessage("AuthenticationFailed"));
     }
 
-    // 灏嗘墍鏈夌櫥闄嗙殑鐢ㄦ埛鐨勪俊鎭瓨鍒癮pplication涓�
-    public void setApplication(User user) {
-        ServletContext application = CommonUtil.getApplication();
-        //鏌ョ湅鍏ㄥ眬涓瓨鍌ㄧ殑users鐨凪ap鐨刱ey-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.getName());
-            if (client != null) { //宸插瓨鍦�
-                map.remove(user.getName());
-            }
-        }
-        Long login_time = new Date().getTime();
-        CommonUtil.getSession().setAttribute("login_time", login_time);
-        map.put(user.getName(), new UserClient(CommonUtil.getRequest().getRemoteAddr(),user,login_time));
-        application.setAttribute("users", map);
-    }
 
 
-    /**
-     * 寮�濮嬫煡鐪媋pplication涓槸鍚︽湁鍙︿竴鐢ㄤ娇鐢ㄨ璐﹀彿鐧婚檰
-     *
-     * @return
-     */
-    public Response checkUser(){
-        Response model = new Response();
-        Map<String, UserClient> map = (Map) CommonUtil.getApplication().getAttribute("users");
-        // System.out.println(map);
-        if (map != null && map.size() > 0) {
-            HttpSession session = CommonUtil.getSession();
-            // System.out.println(session);
-            User user = (User) session.getAttribute("user");
-            Long login_time = (Long) session.getAttribute("login_time");
-            if (user != null && login_time != null) {
-                UserClient client = map.get(user.getName());
-                if (client != null) {
-                    if (!login_time.equals(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 {
             User user = (User) httpSession.getAttribute("user");
-            //System.out.println("webSocket:"+user);
             if(user!=null){
-                ServletContext servletContext = httpSession.getServletContext();
-                String sessionId = (String) servletContext.getAttribute(user.getName());
+                String sessionId = (String) httpSession.getServletContext().getAttribute(user.getName());
                 if(httpSession.getId().equals(sessionId)){
-                    //鐢ㄦ埛鍦ㄧ嚎鐘舵�佹牎楠屾垚鍔�,鏇存柊褰撳墠鐢ㄦ埛鐨勫湪绾挎椂闂�
-                    HashMap<String, Long> onlineMap = (HashMap<String, Long>) servletContext.getAttribute("online");
-                    if(onlineMap == null){
-                        onlineMap = new HashMap<>();
-                        servletContext.setAttribute("online", onlineMap);
-                    }
-                    onlineMap.put(user.getName(), System.currentTimeMillis());
                     model.set(1,user,null);
                 }else{
-                    model.set(1,false,"涓嶅悓涓绘満鐧诲綍");
+                    if(sessionId.equals("123456")){
+                        model.set(1,false,"韬唤鏉冮檺鍙樻洿,璇烽噸鏂扮櫥褰�");
+                    }else{
+                        model.set(1,false,"涓嶅悓涓绘満鐧诲綍");
+                    }
                     //鐢ㄦ埛鍦ㄥ叾浠栦富鏈虹櫥褰�,寮鸿揩鐢ㄦ埛鍦ㄦ湰鏈虹殑session澶辨晥
                     httpSession.invalidate();
                 }
@@ -273,7 +281,6 @@
             else {
                 model.set(1,false,"鐢ㄦ埛淇℃伅澶辨晥,璇烽噸鏂扮櫥褰�");
             }
-
         }catch (Exception e){
             model.set(1,false,"鐧诲綍淇℃伅澶辨晥,閲嶆柊鐧诲綍");
         }
@@ -285,32 +292,4 @@
         subject.logout();
     }
 
-    public Response loginNoPass(int uId, HttpServletRequest request) {
-        Response<Object> response = new Response<>();
-        //鏍规嵁uId鑾峰彇鐢ㄦ埛鐨勭敤鎴峰悕鍜屽瘑鐮�,杩涜绫荤櫥褰曟搷浣�
-        User user = userService.getUinfByUId(uId);
-
-        UsernamePasswordToken userToken = new UsernamePasswordToken(user.getName(),RSAUtil.decrypt(user.getPwd(),RSAUtil.getPrivateKey()));
-        Subject subject = SecurityUtils.getSubject();
-        subject.login(userToken);
-
-        if (subject.isAuthenticated()) {
-            //姣忎釜鐧诲綍鐨勭敤鎴烽兘鏈変竴涓叏灞�鍙橀噺,閲岄潰瀛樼潃瀵瑰簲鐨凷essionId;
-            //鍚屼竴涓处鍙�,鍚庨潰鐧诲綍鐨�,浼氭尋鎺変箣鍓嶇櫥褰曠殑SessionId,杩欎釜todo,鍋氶檺鍒惰处鍙峰悓鏃剁櫥闄嗕汉鏁颁负1
-
-            //鐧诲綍鎴愬姛
-            ServletContext servletContext = request.getServletContext();
-            servletContext.setAttribute(user.getName(), request.getSession().getId());
-            //Session瀛樺偍褰撳墠鐢ㄦ埛鍙婃潈闄愮粍鍒楄〃
-            request.getSession().setAttribute("user", subject.getPrincipal());
-            request.getSession().setMaxInactiveInterval(60 * 60 * 24);
-
-            //鍥炲啓鐧诲綍鏃堕棿鍒版暟鎹簱
-            //鏌ヨ鐢ㄦ埛瀵瑰簲鐨勬潈闄愮粍id骞惰繑鍥炵粰鍓嶇
-            LinkedList<Object> dataList = new LinkedList<>();
-            dataList.add(subject.getPrincipal());
-            return new Response<>().setII(1, true, dataList, "鐧诲綍鎴愬姛");
-        }
-        return new Response().set(1,false,"璁よ瘉鏈�氳繃");
-    }
 }

--
Gitblit v1.9.1