Browse Source

日志 和 返回结构修改

andy 1 year ago
parent
commit
f28d6f338e

+ 4 - 0
mainFactory/pom.xml

@@ -59,6 +59,10 @@
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-aop</artifactId>
+        </dependency>
 
         <dependency>
             <groupId>junit</groupId>

+ 2 - 0
mainFactory/src/main/java/org/bfkj/MainFactoryApplication.java

@@ -15,6 +15,7 @@ import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
 import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
 import org.springframework.core.env.Environment;
 import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.scheduling.annotation.Scheduled;
@@ -29,6 +30,7 @@ import java.util.logging.Level;
 
 @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
 @EnableScheduling
+@EnableAspectJAutoProxy
 public class MainFactoryApplication implements InitializingBean {
 
     private final static Logger logger = LoggerFactory.getLogger(MainFactoryApplication.class);

+ 17 - 0
mainFactory/src/main/java/org/bfkj/advice/GlobalExeceptionHandler.java

@@ -0,0 +1,17 @@
+package org.bfkj.advice;
+
+
+import org.bfkj.dtos.R;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+@RestControllerAdvice
+public class GlobalExeceptionHandler {
+    @ExceptionHandler(Exception.class)
+    public ResponseEntity<R<Object>> handleException(Exception exception) {
+        R<Object> fail = R.fail("-1", exception.getMessage());
+        return ResponseEntity.ok(fail);
+
+    }
+}

+ 12 - 10
mainFactory/src/main/java/org/bfkj/api/AuthManageApi.java

@@ -3,6 +3,8 @@ package org.bfkj.api;
 
 import jakarta.servlet.http.HttpServletRequest;
 import org.bfkj.application.AuthApplicationImpl;
+import org.bfkj.dtos.R;
+import org.bfkj.dtos.ServiceDto;
 import org.bfkj.services.SecurityService;
 import org.bfkj.utils.HttpRequestUtil;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -27,10 +29,10 @@ public class AuthManageApi {
             Map<String, Object> bodyMap = new HashMap<>(body);
             Map<String, Object> requestData = HttpRequestUtil.combineData(null, bodyMap, httpServletRequest);
 
-            Map<String, Object> result = securityService.getToken(requestData);
-            if ("0".equals(result.get("code"))) {
+            ServiceDto<Map<String, Object>,Object> result = securityService.getToken(requestData);
+            if (result.isSuccess()) {
                 Map<String, Object> temp = new HashMap<>();
-                Map<String, Object> returnData = (Map<String, Object>) result.get("returnData");
+                Map<String, Object> returnData = result.getReturnData().getReturnData();
 
                 temp.put("app_effective", returnData.get("expirestime"));
                 temp.put("app_token", returnData.get("token"));
@@ -39,7 +41,7 @@ public class AuthManageApi {
                 temp.put("background", returnData.get("background"));
                 temp.put("app_log", returnData.get("logo"));
                 temp.put("app_small_log", returnData.get("smalllogo"));
-                result.put("returnData", temp);
+                result.setReturnData(R.success("0",temp));
             }
             return result;
         } catch (Exception e) {
@@ -55,9 +57,9 @@ public class AuthManageApi {
             Map<String, Object> bodyMap = new HashMap<>(body);
             Map<String, Object> requestData = HttpRequestUtil.combineData(null, bodyMap, httpServletRequest);
 
-            Map<String, Object> result = securityService.getToken(requestData);
-            if ("0".equals(result.get("code"))) {
-                Map<String, Object> returnData = (Map<String, Object>) result.get("returnData");
+            ServiceDto<Map<String, Object>,Object> result = securityService.getToken(requestData);
+            if (result.isSuccess()) {
+                Map<String, Object> returnData = result.getReturnData().getReturnData();
 
                 Object appToken = returnData.get("token");
                 Object expirestime = returnData.get("expirestime");
@@ -95,9 +97,9 @@ public class AuthManageApi {
             Map<String, Object> bodyMap = new HashMap<>(body);
             Map<String, Object> requestData = HttpRequestUtil.combineData(headers, bodyMap, httpServletRequest);
 
-            Map<String, Object> result = securityService.refreshToken(requestData);
-            if ("0".equals(result.get("code"))) {
-                Map<String, Object> returnData = (Map<String, Object>) result.get("returnData");
+            ServiceDto<Map<String, Object>,Object> result = securityService.refreshToken(requestData);
+            if (result.isSuccess()) {
+                Map<String, Object> returnData = result.getReturnData().getReturnData();
                 Object appToken = returnData.get("token");
                 Object expirestime = returnData.get("expirestime");
                 if(httpServletRequest.getRequestURI().endsWith("refreshToken")) {

+ 34 - 30
mainFactory/src/main/java/org/bfkj/api/SecurityApi.java

@@ -3,10 +3,14 @@ package org.bfkj.api;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
 import jakarta.servlet.http.HttpServletRequest;
+import org.bfkj.domain.Permissions;
+import org.bfkj.dtos.R;
+import org.bfkj.dtos.ServiceDto;
 import org.bfkj.services.SecurityService;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
 
+import java.util.List;
 import java.util.Map;
 
 import static org.bfkj.utils.HttpRequestUtil.combineData;
@@ -30,10 +34,10 @@ public class SecurityApi {
      * @return
      */
     @PostMapping("user/getToken")
-    public ResponseEntity getToken(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) throws JsonProcessingException {
+    public ResponseEntity<R<Map<String,Object>>> getToken(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) throws JsonProcessingException {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.getToken(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String, Object>,Object> result = securityService.getToken(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -43,10 +47,10 @@ public class SecurityApi {
      * @return
      */
     @PostMapping("user/refreshToken")
-    public ResponseEntity refreshToken(@RequestHeader Map<String, Object> headers, HttpServletRequest httpRequest) throws JsonProcessingException {
+    public ResponseEntity refreshToken(@RequestHeader Map<String, Object> headers, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, null, httpRequest);
-        Map<String, Object> result = securityService.refreshToken(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String, Object>,Object> result = securityService.refreshToken(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -56,12 +60,12 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/testToken","foxlibc/testToken"})
+    @PostMapping({"user/testToken", "foxlibc/testToken"})
     public ResponseEntity testToken(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
 
-        Map<String, Object> result = securityService.verifyToken(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String, Object>,Object> result = securityService.verifyToken(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -71,11 +75,11 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/verifyCode","foxlibc/verification-code"})
+    @PostMapping({"user/verifyCode", "foxlibc/verification-code"})
     public ResponseEntity getCode(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.verifyCode(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String, Object>,Object> result = securityService.verifyCode(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -85,11 +89,11 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/forceLogin","foxlibc/force_sign"})
+    @PostMapping({"user/forceLogin", "foxlibc/force_sign"})
     public ResponseEntity forceLogin(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.forceLogin(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String, Object>,Object> result = securityService.forceLogin(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -99,11 +103,11 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/login","foxlibc/sign-in"})
+    @PostMapping({"user/login", "foxlibc/sign-in"})
     public ResponseEntity login(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.login(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String, Object>,Object> result = securityService.login(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -113,11 +117,11 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/permissions","foxlibc/permissions"})
+    @PostMapping({"user/permissions", "foxlibc/permissions"})
     public ResponseEntity getPermissions(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.permission(requestData,0);
-        return ResponseEntity.ok(result);
+        ServiceDto<List<Permissions>,Object> result = securityService.permission(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
 
@@ -128,11 +132,11 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/changePassword","foxlibc/reset-passwd"})
+    @PostMapping({"user/changePassword", "foxlibc/reset-passwd"})
     public ResponseEntity changePwd(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.changePassword(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String,Object>,Object> result = securityService.changePassword(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -142,11 +146,11 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/logOut","foxlibc/sign-out}"})
+    @PostMapping({"user/logOut", "foxlibc/sign-out"})
     public ResponseEntity logOut(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.logOut(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<Map<String, Object>,Object> result = securityService.logOut(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 
     /**
@@ -156,10 +160,10 @@ public class SecurityApi {
      * @param body
      * @return
      */
-    @PostMapping({"user/health","foxlibc/health"})
+    @PostMapping({"user/health", "foxlibc/health"})
     public ResponseEntity health(@RequestHeader Map<String, Object> headers, @RequestBody Map<String, Object> body, HttpServletRequest httpRequest) {
         Map<String, Object> requestData = combineData(headers, body, httpRequest);
-        Map<String, Object> result = securityService.userHeartbeat(requestData);
-        return ResponseEntity.ok(result);
+        ServiceDto<List<Permissions>,Object> result = securityService.userHeartbeat(requestData);
+        return ResponseEntity.ok(result.getReturnData());
     }
 }

+ 16 - 0
mainFactory/src/main/java/org/bfkj/apos/Log.java

@@ -0,0 +1,16 @@
+package org.bfkj.apos;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * @author l7871
+ */
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Log {
+    LogType value();
+
+    enum LogType {
+        SERVICE, SYSTEM, USER, APP
+    }
+}

+ 105 - 0
mainFactory/src/main/java/org/bfkj/apos/LogAop.java

@@ -0,0 +1,105 @@
+package org.bfkj.apos;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.annotation.AfterReturning;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.bfkj.dtos.ServiceDto;
+import org.bfkj.utils.MyDbHelper;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+@Aspect
+@Component
+public class LogAop {
+
+    private ObjectMapper objectMapper = new ObjectMapper();
+
+    private List<Object> userlogs = new ArrayList<>();
+    private List<Object> applogs = new ArrayList<>();
+    private List<Object> systemerrlogs = new ArrayList<>();
+    private List<Object> serviceerrlogs = new ArrayList<>();
+    private List<Object> servicelogs = new ArrayList<>();
+
+    private final MyDbHelper myDbHelper;
+    private final ScheduledExecutorService service;
+
+    public LogAop(@Qualifier("logDataBaseConnectionStr") String logDataBaseConnectionStr) {
+
+        this.myDbHelper = new MyDbHelper(logDataBaseConnectionStr);
+        this.service = Executors.newScheduledThreadPool(64);
+
+//        定时
+        service.scheduleWithFixedDelay(() -> {
+            List<Object> temp;
+            if (!applogs.isEmpty()) {
+                temp = applogs;
+                applogs = new ArrayList<>();
+                String sql = "insert into  applog(logtime, appid, apiname, requestip, sessionid, inputdata, outputdata) values(?,?,?,?,?,?,?)";
+                myDbHelper.JDBCBatch(sql, temp, null);
+                temp.clear();
+            }
+            if (!userlogs.isEmpty()) {
+                temp = userlogs;
+                userlogs = new ArrayList<>();
+                String sql = "insert into userlog (logtime, userid, username, requestip, sessionid, pagename, pagecode, inputdata, outputdata) VALUES (?,?,?,?,?,?,?,?,?)";
+                myDbHelper.JDBCBatch(sql, temp, null);
+                temp.clear();
+            }
+            if (!systemerrlogs.isEmpty()) {
+                temp = systemerrlogs;
+                systemerrlogs = new ArrayList<>();
+                String sql = "insert into systemerrlog (logtime, errordata) VALUES (?,?)";
+                myDbHelper.JDBCBatch(sql, temp, null);
+                temp.clear();
+            }
+
+
+            if (!servicelogs.isEmpty()) {
+                temp = servicelogs;
+                servicelogs = new ArrayList<>();
+                String sql = "insert into servicelog (logtime, serviceid, servicename, outputdata, inputdata, libraryid) VALUES (?,?,?,?,?,?)";
+                myDbHelper.JDBCBatch(sql, temp, null);
+                temp.clear();
+            }
+
+            if (!serviceerrlogs.isEmpty()) {
+                temp = serviceerrlogs;
+                serviceerrlogs = new ArrayList<>();
+                String sql = "insert into serviceerrlog (logtime, serviceid, servicename, outputdata, inputdata, libraryid) VALUES (?,?,?,?,?,?)";
+                myDbHelper.JDBCBatch(sql, temp, null);
+                temp.clear();
+            }
+
+        }, 1, 1, TimeUnit.SECONDS);
+    }
+
+    @AfterReturning(value = "@annotation(org.bfkj.apos.Log)", returning = "serviceDto")
+    public void doAfter(JoinPoint point, ServiceDto serviceDto) {
+        MethodSignature signature = (MethodSignature) point.getSignature();
+        Method method = signature.getMethod();
+        Log annotation = method.getAnnotation(Log.class);
+        Log.LogType value = annotation.value();
+        switch (value) {
+            case SERVICE -> {
+                if (serviceDto.isSuccess()) {
+                    servicelogs.add(serviceDto.getLogData());
+                } else {
+                    serviceerrlogs.add(serviceDto.getLogData());
+                }
+            }
+            case SYSTEM -> systemerrlogs.add(serviceDto.getLogData());
+            case USER -> userlogs.add(serviceDto.getLogData());
+            case APP -> applogs.add(serviceDto.getLogData());
+        }
+
+    }
+}

+ 13 - 0
mainFactory/src/main/java/org/bfkj/config/DatabaseConfig.java

@@ -1,5 +1,9 @@
 package org.bfkj.config;
 
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.openjdk.nashorn.internal.runtime.regexp.joni.ast.StringNode;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.jdbc.DataSourceBuilder;
 import org.springframework.context.annotation.Bean;
@@ -47,4 +51,13 @@ public class DatabaseConfig {
         DataSource dataSource = DataSourceBuilder.create().driverClassName(logDriverClassName).password(logPassword).username(logUsername).url(logUrl).build();
         return new JdbcTemplate(dataSource);
     }
+    @Bean("logDataBaseConnectionStr")
+    public String logDataBaseConnectionStr() {
+        ObjectNode node=new ObjectNode(JsonNodeFactory.instance);
+        node.put("url", logUrl);
+        node.put("username", logUsername);
+        node.put("password", logPassword);
+        node.put("driver-class-name", logDriverClassName);
+        return node.toString();
+    }
 }

+ 6 - 6
mainFactory/src/main/java/org/bfkj/domain/Userinfo.java

@@ -13,12 +13,12 @@ public class Userinfo implements Serializable {
     */
     
     
-    private Integer userid;
+    private Long userid;
     /**
     * 
     */
     
-    private Integer usergroupid;
+    private Long usergroupid;
     /**
     * 用户名
     */
@@ -63,14 +63,14 @@ public class Userinfo implements Serializable {
     /**
     * 自增长主键用户编号
     */
-    public void setUserid(Integer userid){
+    public void setUserid(Long userid){
     this.userid = userid;
     }
 
     /**
     * 
     */
-    public void setUsergroupid(Integer usergroupid){
+    public void setUsergroupid(Long usergroupid){
     this.usergroupid = usergroupid;
     }
 
@@ -120,14 +120,14 @@ public class Userinfo implements Serializable {
     /**
     * 自增长主键用户编号
     */
-    public Integer getUserid(){
+    public Long getUserid(){
     return this.userid;
     }
 
     /**
     * 
     */
-    public Integer getUsergroupid(){
+    public Long getUsergroupid(){
     return this.usergroupid;
     }
 

+ 6 - 6
mainFactory/src/main/java/org/bfkj/domain/Userloginlog.java

@@ -14,12 +14,12 @@ public class Userloginlog implements Serializable {
     */
     
     
-    private Integer loginid;
+    private Long loginid;
     /**
     * 
     */
     
-    private Integer userid;
+    private Long userid;
     private String appid;
 
     public String getAppid() {
@@ -98,14 +98,14 @@ public class Userloginlog implements Serializable {
     /**
     * 自增长主键登录编号
     */
-    public void setLoginid(Integer loginid){
+    public void setLoginid(Long loginid){
     this.loginid = loginid;
     }
 
     /**
     * 
     */
-    public void setUserid(Integer userid){
+    public void setUserid(Long userid){
     this.userid = userid;
     }
 
@@ -162,14 +162,14 @@ public class Userloginlog implements Serializable {
     /**
     * 自增长主键登录编号
     */
-    public Integer getLoginid(){
+    public Long getLoginid(){
     return this.loginid;
     }
 
     /**
     * 
     */
-    public Integer getUserid(){
+    public Long getUserid(){
     return this.userid;
     }
 

+ 57 - 0
mainFactory/src/main/java/org/bfkj/dtos/R.java

@@ -0,0 +1,57 @@
+package org.bfkj.dtos;
+
+import com.fasterxml.jackson.annotation.JsonAlias;
+
+/**
+ * @author l7871
+ */
+public class R<T> {
+    private String code;
+    private String message;
+    @JsonAlias({"returnData","data"})
+    private T returnData;
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public void setMessage(String message) {
+        this.message = message;
+    }
+
+    public T getReturnData() {
+        return returnData;
+    }
+
+    public void setReturnData(T returnData) {
+        this.returnData = returnData;
+    }
+
+    public static <T> R<T> fail(String code, String message){
+        R<T> objectR = new R<>();
+        objectR.setCode(code);
+        objectR.setMessage(message);
+        return objectR;
+    }
+    public static <T> R<T> success(String code, T data){
+        R<T> objectR = new R<>();
+        objectR.setCode(code);
+        objectR.setReturnData(data);
+        return objectR;
+    }
+    public static <T> R<T> success(String code,String message, T data){
+        R<T> objectR = new R<>();
+        objectR.setCode(code);
+        objectR.setMessage(message);
+        objectR.setReturnData(data);
+        return objectR;
+    }
+}

+ 38 - 0
mainFactory/src/main/java/org/bfkj/dtos/ServiceDto.java

@@ -0,0 +1,38 @@
+package org.bfkj.dtos;
+
+import java.util.List;
+
+/**
+ * @author l7871
+ */
+public class ServiceDto<T,L> {
+    private R<T> returnData;
+
+    private boolean success;
+
+    public boolean isSuccess() {
+        return success;
+    }
+
+    public void setSuccess(boolean success) {
+        this.success = success;
+    }
+
+    public R<T> getReturnData() {
+        return returnData;
+    }
+
+    public void setReturnData(R<T> returnData) {
+        this.returnData = returnData;
+    }
+
+    public List<L> getLogData() {
+        return logData;
+    }
+
+    public void setLogData(List<L> logData) {
+        this.logData = logData;
+    }
+
+    private List<L> logData;
+}

+ 4 - 3
mainFactory/src/main/java/org/bfkj/services/ApplicationconnectlogService.java

@@ -30,9 +30,9 @@ public class ApplicationconnectlogService {
 
     }
 
-    public void updateApplicationLogTokenExpiresTime(String appId, String token, LocalDateTime expiresTime) {
-        securityJdbcTemplate.update("update appconnectlog set expiretime=? where apptoken =? and appid=?",
-                expiresTime, token, appId);
+    public boolean updateApplicationLogTokenExpiresTime(String appId, String token,String requestid, LocalDateTime expiresTime) {
+        return securityJdbcTemplate.update("update appconnectlog set expiretime=? where apptoken =? and requestip =? and appid=?",
+                expiresTime, token, requestid, appId) != 0;
     }
 
 
@@ -44,4 +44,5 @@ public class ApplicationconnectlogService {
     public void removeExpiresData() {
         securityJdbcTemplate.update("delete from appconnectlog where expiretime < NOW() and 1 = ?", 1);
     }
+
 }

+ 1 - 1
mainFactory/src/main/java/org/bfkj/services/PermissionsService.java

@@ -78,7 +78,7 @@ public class PermissionsService {
 
     }
 
-    public void removePermissions(Integer userId) {
+    public void removePermissions(Long userId) {
 
     }
 }

+ 312 - 239
mainFactory/src/main/java/org/bfkj/services/SecurityService.java

@@ -1,9 +1,13 @@
 package org.bfkj.services;
 
 
+import com.fasterxml.jackson.annotation.JsonInclude;
 import com.fasterxml.jackson.core.JsonProcessingException;
-import jakarta.annotation.Nullable;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.bfkj.apos.Log;
 import org.bfkj.domain.*;
+import org.bfkj.dtos.R;
+import org.bfkj.dtos.ServiceDto;
 import org.bfkj.services.cache.CodeCacheService;
 import org.bfkj.utils.CommonUtil;
 import org.bfkj.utils.RandomGraphic;
@@ -21,14 +25,19 @@ public class SecurityService {
 
     private final static Map<String, List<String>> alias = new HashMap<>();
 
+    private ObjectMapper objectMapper = new ObjectMapper() {{
+        setSerializationInclusion(JsonInclude.Include.NON_NULL);
+    }};
+
     static {
         alias.put("appid", List.of("appid", "app_id", "appId", "APPID"));
         alias.put("appsecret", List.of("appSecret", "app_secret", "APP_SECRET", "appsecret", "APPSECRET"));
-        alias.put("sessionid", List.of("sessionId", "sessionid"));
-        alias.put("requestip", List.of("requestIp", "requestip"));
-        alias.put("username", List.of("username"));
-        alias.put("password", List.of("password"));
-        alias.put("version", List.of("version"));
+        alias.put("sessionid", List.of("sessionId", "sessionid", "SESSIONID", "SESSION_ID", "session_id"));
+        alias.put("requestip", List.of("requestIp", "requestip", "request_ip", "REQUEST_IP", "request_ip", "REQUESTIP", "ip"));
+        alias.put("username", List.of("username", "userName", "user_name", "USER_NAME", "USERNAME"));
+        alias.put("password", List.of("password", "pwd", "PWD", "PASSWORD"));
+        alias.put("version", List.of("version", "Version", "VERSION"));
+        alias.put("verifycode", List.of("verifycode", "verifyCode", "code"));
     }
 
     private final ApplicationService applicationService;
@@ -47,364 +56,429 @@ public class SecurityService {
         this.codeCacheService = codeCacheService;
     }
 
-
     //安全类服务
     //连接认证--获取连接令牌
-    public Map<String, Object> getToken(Map<String, Object> requestData) throws JsonProcessingException {
+    @Log(Log.LogType.APP)
+    public ServiceDto<Map<String, Object>,Object> getToken(Map<String, Object> requestData) throws JsonProcessingException {
         Optional<String> appid = getValue("appid", requestData);
         Optional<String> appSecret = getValue("appsecret", requestData);
         Optional<String> requestIp = getValue("requestip", requestData);
         Optional<String> sessionId = getValue("sessionid", requestData);
-
-        Map<String, Object> result = new HashMap<>();
+        ServiceDto<Map<String, Object>,Object> serviceDto = new ServiceDto<>();
+        Application application = null;
         if (appid.isPresent() && appSecret.isPresent()) {
 //            无条件删除过期的数据
             applicationconnectlogService.removeExpiresData();
-            result.putAll(getAppToken(appid.get(), appSecret.get(), requestIp.get(), sessionId.get()));
-        } else {
-            result.put("code", "-1");
-            result.put("message", "appid 或者 appSecret 错误");
-        }
-        return result;
-    }
 
-    private Map<String, Object> getAppToken(String appid, String appSecret, String requestIp, String sessionId) throws JsonProcessingException {
-        Application application = applicationService.findByAppId(appid);
-        Map<String, Object> result = new HashMap<>();
-        if (appSecret.equals(application.getAppsecret())) {
+            application = applicationService.findByAppId(appid.get());
+            if (appSecret.get().equals(application.getAppsecret())) {
 //            令牌
-            String md5Token = CommonUtil.toMD5("%s:%s".formatted(LocalDateTime.now(), sessionId));
+                String md5Token = CommonUtil.toMD5("%s:%s".formatted(LocalDateTime.now(), sessionId));
 //            有效期时长
-            Long apptokeneffective = application.getApptokeneffective();
+                Long apptokeneffective = application.getApptokeneffective();
 //            过期时间
-            LocalDateTime expiresTime = LocalDateTime.now().plusSeconds(apptokeneffective);
+                LocalDateTime expiresTime = LocalDateTime.now().plusSeconds(apptokeneffective);
 //            新增记录
-            Appconnectlog applicationconnectlog = new Appconnectlog();
-
-            applicationconnectlog.setAppid(appid);
-            applicationconnectlog.setExpiretime(expiresTime);
-            applicationconnectlog.setApptoken(md5Token);
-            applicationconnectlog.setRequestip(requestIp);
-            applicationconnectlog.setRequesttime(LocalDateTime.now());
-            applicationconnectlog.setLasttime(LocalDateTime.now());
-            applicationconnectlogService.save(applicationconnectlog);
-            Map<String, Object> data = new HashMap<>();
-            data.put("token", md5Token);
-            data.put("expirestime", expiresTime.format(dateTimeFormatter));
-            data.put("appname", application.getAppname());
-            data.put("appenname", application.getAppengname());
-            data.put("logo", application.getApplogo());
-            data.put("smalllogo", application.getSmalllogo());
-            data.put("background", application.getBackgroundimage());
-            data.put("securitycoderule", application.getSecuritycoderule());
-            result.put("returnData", data);
-            result.put("code", "0");
-            result.put("message", null);
+                Appconnectlog applicationconnectlog = new Appconnectlog();
+
+                applicationconnectlog.setAppid(appid.get());
+                applicationconnectlog.setExpiretime(expiresTime);
+                applicationconnectlog.setApptoken(md5Token);
+                applicationconnectlog.setRequestip(requestIp.get());
+                applicationconnectlog.setRequesttime(LocalDateTime.now());
+                applicationconnectlog.setLasttime(LocalDateTime.now());
+                applicationconnectlogService.save(applicationconnectlog);
+                Map<String, Object> data = new HashMap<>();
+                data.put("token", md5Token);
+                data.put("expirestime", expiresTime.format(dateTimeFormatter));
+                data.put("appname", application.getAppname());
+                data.put("appenname", application.getAppengname());
+                data.put("logo", application.getApplogo());
+                data.put("smalllogo", application.getSmalllogo());
+                data.put("background", application.getBackgroundimage());
+                data.put("securitycoderule", application.getSecuritycoderule());
+                serviceDto.setReturnData(R.success("0", data));
+                serviceDto.setSuccess(true);
+
+            } else {
+                serviceDto.setSuccess(false);
+                serviceDto.setReturnData(R.fail("-1", "用户或密码错误"));
+            }
         } else {
-            result.put("message", "用户或密码错误");
-            result.put("code", "-1");
+            serviceDto.setSuccess(false);
+            serviceDto.setReturnData(R.fail("-1", "appid 或者 appSecret 错误"));
         }
-        return result;
+//        logtime, appid, apiname, requestip, sessionid, inputdata, outputdata;
+        List<Object> logData = new ArrayList<>();
+        logData.add(LocalDateTime.now());
+        logData.add(appid.get());
+        logData.add((Objects.nonNull(application) ? application.getAppname() : null));
+        logData.add(requestIp.get());
+        logData.add(sessionId.get());
+        logData.add(objectMapper.writeValueAsString(requestData));
+        logData.add(objectMapper.writeValueAsString(serviceDto.getReturnData()));
+        serviceDto.setLogData(logData);
+        return serviceDto;
     }
 
-
-
     //校验连接令牌
-    public Map<String, Object> verifyToken(Map<String, Object> requestData) {
+    public ServiceDto<Map<String, Object>,Object> verifyToken(Map<String, Object> requestData) {
         Optional<String> token = getValue("token", requestData);
 
         Optional<String> requestIp = getValue("requestip", requestData);
 
-        Map<String, Object> result = new HashMap<>();
+        ServiceDto<Map<String, Object>,Object> serviceDto = new ServiceDto<>();
         if (token.isEmpty()) {
-            result.put("code", "-1");
-            result.put("message", "token错误");
+            serviceDto.setSuccess(false);
+            serviceDto.setReturnData(R.fail("-1", "token错误"));
         } else {
             Appconnectlog applicationLog = applicationconnectlogService.findByTokenAndRequestIp(token.get(), requestIp.get());
             if (LocalDateTime.now().isAfter(applicationLog.getExpiretime())) {
-                result.put("code", "-1");
-                result.put("message", "token已过期");
+                serviceDto.setSuccess(false);
+                serviceDto.setReturnData(R.fail("-1", "token已过期"));
             } else {
-                result.put("code", "0");
-                result.put("message", "token校验通过");
+                serviceDto.setSuccess(true);
 
                 Map<String, Object> data = new HashMap<>();
                 data.put("validstatus", true);
-                result.put("returnData", data);
+                data.put("appid", applicationLog.getAppid());
+                serviceDto.setReturnData(R.success("0", "token校验通过", data));
             }
         }
-        return result;
+        return serviceDto;
     }
 
     //刷新连接令牌
-    public Map<String, Object> refreshToken(Map<String, Object> requestData) {
-        Map<String, Object> resultData = new HashMap<>();
-        Map<String, Object> map = verifyToken(requestData);
-        Optional<String> version = getValue("version", requestData);
-
-        if (map.get("code").equals("0")) {
-            Optional<String> requestIp = getValue("requestIp", requestData);
-            Optional<String> token = getValue("token", requestData);
-
-            Appconnectlog applicationconnectlog = applicationconnectlogService.findByTokenAndRequestIp(token.get(), requestIp.get());
-            Application application = applicationService.findByAppId(applicationconnectlog.getAppid());
-            LocalDateTime expiresTime = LocalDateTime.now().plusSeconds(application.getApptokeneffective());
-            applicationconnectlogService.updateApplicationLogTokenExpiresTime(applicationconnectlog.getAppid(), token.get(), expiresTime);
-            resultData.put("code", "0");
+    public ServiceDto<Map<String, Object>,Object> refreshToken(Map<String, Object> requestData) {
+        ServiceDto<Map<String, Object>,Object> verified = verifyToken(requestData);
+
+        if (!verified.isSuccess()) {
+            return verified;
+        }
+        ServiceDto<Map<String, Object>,Object> resultData = new ServiceDto<>();
+        Optional<String> requestIp = getValue("requestIp", requestData);
+        Optional<String> token = getValue("token", requestData);
+        String appid = (String) verified.getReturnData().getReturnData().get("appid");
+        Application application = applicationService.findByAppId(appid);
+        LocalDateTime expiresTime = LocalDateTime.now().plusSeconds(application.getApptokeneffective());
+        if (applicationconnectlogService.updateApplicationLogTokenExpiresTime(appid, token.get(), requestIp.get(), expiresTime)) {
             Map<String, Object> data = new HashMap<>();
             data.put("expirestime", expiresTime.format(dateTimeFormatter));
             data.put("token", token.get());
-            if ("1".equals(version.orElse("1"))) {
-                resultData.put("returnData", data);
-            } else {
-                resultData.put("data", data);
-            }
+            resultData.setSuccess(true);
+            resultData.setReturnData(R.success("0", data));
+
         } else {
-            resultData.putAll(map);
+            resultData.setReturnData(R.fail("-1", "刷新令牌失败"));
+            resultData.setSuccess(false);
         }
+
+
         return resultData;
     }
 
     //获取登录验证码
-    public Map<String, Object> verifyCode(Map<String, Object> requestData) {
-        Map<String, Object> resultData = new HashMap<>();
-        Optional<String> token = getValue("token", requestData);
-        Optional<String> ip = getValue("requestip", requestData);
+    public ServiceDto<Map<String, Object>,Object> verifyCode(Map<String, Object> requestData) {
+        ServiceDto<Map<String, Object>,Object> resultData = new ServiceDto<>();
+        ServiceDto<Map<String, Object>,Object> verified = verifyToken(requestData);
+        if (!verified.isSuccess()) {
+            return verified;
+        }
+        String appid = (String) verified.getReturnData().getReturnData().get("appid");
         Optional<String> sessionId = getValue("sessionid", requestData);
-        Map<String, Object> testToken = verifyToken(requestData);
-        if ("0".equals(testToken.get("code"))) {
-            Appconnectlog applicationLog = applicationconnectlogService.findByTokenAndRequestIp(token.get(), ip.get());
-            String appid = applicationLog.getAppid();
-            Application application = applicationService.findByAppId(appid);
-            String securitycoderule = application.getSecuritycoderule();
-            Long securitycodeeffective = application.getSecuritycodeeffective();
-            Integer securitycoderulelength = application.getSecuritycoderulelength();
-            Map<String, Object> codeMap = RandomGraphic.generateVerifyCode(securitycoderulelength, securitycoderule);
-
-            String code = codeMap.get("verifyCode").toString();
-            String verifyCodeImage = codeMap.get("verifyCodeImage").toString();
-            codeCacheService.addCode(code, sessionId.get(), securitycodeeffective);
-            resultData.put("code", "0");
+        Optional<String> requestIp = getValue("requestip", requestData);
+        Application application = applicationService.findByAppId(appid);
+        String securitycoderule = application.getSecuritycoderule();
+        Long securitycodeeffective = application.getSecuritycodeeffective();
+        Integer securitycoderulelength = application.getSecuritycoderulelength();
+        Map<String, Object> codeMap = RandomGraphic.generateVerifyCode(securitycoderulelength, securitycoderule);
+
+        String code = codeMap.get("verifyCode").toString();
+        String verifyCodeImage = codeMap.get("verifyCodeImage").toString();
+        codeCacheService.addCode(code, sessionId.get(), appid, securitycodeeffective, requestIp.get());
 //            编译后的验证码
+        Map<String, Object> data = new HashMap<>();
+        data.put("verifyCodeImage", verifyCodeImage);
+        resultData.setReturnData(R.success("0", data));
+        resultData.setSuccess(true);
 
-            Map<String, Object> data = new HashMap<>();
-            data.put("verifyCodeImage", verifyCodeImage);
-            resultData.put("returnData", data);
-        } else {
-            resultData.put("code", "-1");
-            resultData.put("message", "token已经过期");
-        }
         return resultData;
     }
 
 
     //用户登录
-    public Map<String, Object> login(Map<String, Object> requestData) {
-        Map<String, Object> testToken = verifyToken(requestData);
-        Map<String, Object> resultData = new HashMap<>();
-        if (testToken.get("code").equals("0")) {
-            //用户登录日志单独记录--方便控制用户在线状态、用户登录时长、用户心跳等
-            Optional<String> username = getValue("username", requestData);
-            Optional<String> password = getValue("password", requestData);
-            Optional<String> code = getValue("verifycode", requestData);
-            Optional<String> sessionId = getValue("sessionid", requestData);
-            Optional<String> requestIp = getValue("requestip", requestData);
-            Optional<String> token = getValue("token", requestData);
-            resultData.putAll(getUserToken(token.get(), username.get(), password.get(), code.get(), requestIp.get(), sessionId.get(), true));
-        } else {
-            resultData.put("code", "-1");
-            resultData.put("message", "token已经过期");
+    public ServiceDto<Map<String, Object>,Object> login(Map<String, Object> requestData) {
+//        首先,通过verifyToken方法验证app的令牌(token)是否有效(返回是否有效、appid)。
+        ServiceDto<Map<String, Object>,Object> resultData = new ServiceDto<>();
+        ServiceDto<Map<String, Object>,Object> verified = verifyToken(requestData);
+        if (!verified.isSuccess()) {
+            return verified;
         }
-        return resultData;
-    }
 
-    private Map<String, Object> getUserToken(@Nullable String appToken, @Nullable String userName, @Nullable String password, @Nullable String code, @Nullable String requestIp, String sessionId, Boolean checkCode) {
-        Map<String, Object> result = new HashMap<>();
-        Appconnectlog applicationconnectlog = applicationconnectlogService.findByTokenAndRequestIp(appToken, requestIp);
-        if (Objects.isNull(applicationconnectlog)) {
-            result.put("code", "-1");
-            result.put("message", "apptoken 错误");
-            return result;
+        String appid = verified.getReturnData().getReturnData().get("appid").toString();
+        Optional<String> requestip = getValue("requestip", requestData);
+        Optional<String> sessionid = getValue("sessionid", requestData);
+        Optional<String> username = getValue("username", requestData);
+        Optional<String> password = getValue("password", requestData);
+        Optional<String> verifycode = getValue("verifycode", requestData);
+        Application application = applicationService.findByAppId(appid);
+        String securitycoderule = application.getSecuritycoderule();
+        if (Objects.nonNull(securitycoderule) && !codeCacheService.check(verifycode.get(), sessionid.get(), appid, requestip.get())) {
+            resultData.setSuccess(false);
+            resultData.setReturnData(R.fail("-1", "验证码错误"));
+            return resultData;
         }
-        Application application = applicationService.findByAppId(applicationconnectlog.getAppid());
 
-        if (checkCode && Objects.nonNull(application.getSecuritycoderule()) && !codeCacheService.check(code, sessionId)) {
-            result.put("code", "-1");
-            result.put("message", "验证码错误");
-        } else {
-            Integer multilogin = application.getMultilogin();
-            Userinfo user = userinfoService.findByUsername(userName);
-            List<Userloginlog> userloginlogs = userloginlogService.findByUserId(user.getUserid());
-            if (!userloginlogs.isEmpty()) {
-                result.put("code", "0");
-                if (multilogin == 1) {
-                    userloginlogService.expiresByUserid(user.getUserid());
-                }
-                userloginlogService.insertUserLoginLog(requestIp, sessionId, user.getUserid(), null, appToken, application.getAppid());
-                result.put("returnData", new HashMap<>() {{
-                    put("userstatus", 1);
-                }});
-                return result;
-            } else {
-                result.put("code", "0");
-                result.put("returnData", new HashMap<>() {{
-                    put("userstatus", 0);
-                }});
-            }
-            userloginlogService.insertUserLoginLog(requestIp, sessionId, user.getUserid(), null, appToken, application.getAppid());
+        Userinfo userinfo = userinfoService.findByUsernameAndPassword(username.get(), password.get());
+        if (Objects.isNull(userinfo)) {
+            resultData.setSuccess(false);
+            resultData.setReturnData(R.fail("-1", "用户名或密码错误"));
+            return resultData;
+        }
+
+        Userloginlog userloginlog = userloginlogService.findByUserIdAndSessionId(userinfo.getUserid(), sessionid.get());
+
+        Map<String, Object> data = new HashMap<>();
+        if (Objects.nonNull(userloginlog)) {
 
+            data.put("userstatus", "2");
+            resultData.setSuccess(true);
+            resultData.setReturnData(R.fail("0", "data"));
+            return resultData;
         }
-        return result;
+        Integer multilogin = application.getMultilogin();
+        Appconnectlog appconnectlog = new Appconnectlog();
+        if (1 == multilogin) {
+            applicationconnectlogService.save(appconnectlog);
+
+            data.put("userstatus", "0");
+            resultData.setSuccess(true);
+            resultData.setReturnData(R.fail("0", "data"));
+            return resultData;
+        }
+
+
+        List<Userloginlog> userloginlogs = userloginlogService.findByUserId(userinfo.getUserid());
+//            没有登录
+        if (userloginlogs.isEmpty()) {
+            data.put("userstatus", "0");
+            resultData.setSuccess(true);
+            resultData.setReturnData(R.fail("0", "data"));
+        } else {
+            data.put("userstatus", "1");
+            resultData.setSuccess(true);
+            resultData.setReturnData(R.fail("0", "data"));
+        }
+        appconnectlog.setApptoken(appconnectlog.getApptoken());
+        appconnectlog.setAppid(appid);
+        appconnectlog.setLasttime(LocalDateTime.now());
+        appconnectlog.setRequesttime(LocalDateTime.now());
+        appconnectlog.setRequestip(requestip.get());
+        appconnectlog.setExpiretime(LocalDateTime.now().plusSeconds(application.getApptokeneffective()));
+        applicationconnectlogService.save(appconnectlog);
+
+        codeCacheService.remove(verifycode.get(), sessionid.get(), appid, requestip.get());
+        return resultData;
+
+
+//
+//        如果令牌有效,继续执行以下步骤:
+//        从requestData中获取sessionid、requestip、用户名、密码、验证码(md5)。
+//        通过appid字段查找对应的application表记录
+//                判断记录中验证码规则
+//        如需验证验证码
+//                根据appid,ip,sessionid,和验证码查询数据库
+//        如不通过 返回错误
+//        验证用户名密码(根据用户名、密码到数据库查询即可,同时还可获取到userid)
+//        如不通过 返回错误
+//        通过userid、sessionid在userloginlog中查找
+//        如找到  用户状态设置为2
+//        如未找到
+//        获取application记录中的multilogin字段。
+//        如果 multilogin 等于1 则
+//        在userloginlog表中插入一条新的登录记录(userid、sessionid、ip、apptoken)。
+//        将用户状态设置为0
+//        如果 multilogin 不等于1 则
+//        通过用户ID在userloginlog表中查找对应的登录记录。
+//        如果登录记录不为空,
+//        将用户状态设置为1。
+//        如果登录记录为空,
+//        将用户状态设置为0。
+//        在userloginlog表中插入一条新的登录记录。
+//        将用户状态添加到result中。
+//        返回result作为用户令牌的结果。
+//        否则
+//                返回错误
     }
 
+
     //强制登录
-    public Map<String, Object> forceLogin(Map<String, Object> requestData) {
+    public ServiceDto<Map<String, Object>,Object> forceLogin(Map<String, Object> requestData) {
 
-        Map<String, Object> verifyTokenResult = verifyToken(requestData);
-        if (!verifyTokenResult.get("code").equals("0")) {
-            return verifyTokenResult;
+        ServiceDto<Map<String, Object>,Object> verified = verifyToken(requestData);
+        if (!verified.isSuccess()) {
+            return verified;
         }
-        Optional<String> token = getValue("token", requestData);
-        Optional<String> sessionId = getValue("sessionid", requestData);
-        Optional<String> requestIp = getValue("requestip", requestData);
-        Userloginlog userloginlog = userloginlogService.findByAppToken(token.get(), sessionId.get());
-        Map<String, Object> result = new HashMap<>();
+        Optional<String> requestip = getValue("requestip", requestData);
+        Optional<String> sessionid = getValue("sessionid", requestData);
+        Optional<String> apptoken = getValue("token", requestData);
+        String appid = verified.getReturnData().getReturnData().get("appid").toString();
+        Application application = applicationService.findByAppId(appid);
+        ServiceDto<Map<String, Object>,Object> result = new ServiceDto<>();
+        result.setSuccess(false);
+        if (Objects.isNull(application)) {
+            result.setReturnData(R.fail("-1", "没有找到应用配置"));
+            return result;
+        }
+        Userloginlog userloginlog = userloginlogService.findByAppTokenAndSessionIdAndRequestIp(apptoken.get(), sessionid.get(), requestip.get());
         if (Objects.isNull(userloginlog)) {
-            result.put("code", "-1");
-            result.put("message", "登录失败");
+            result.setReturnData(R.fail("-1", "登录失败"));
+            return result;
+        }
+        Long securitycodeeffective = application.getSecuritycodeeffective();
+        LocalDateTime expiresTime = LocalDateTime.now().plusSeconds(securitycodeeffective);
+        String userToken = CommonUtil.toMD5("%s:%s".formatted(LocalDateTime.now(), sessionid.get()));
+        userloginlogService.updateUserToken(userloginlog.getLoginid(), userToken);
+        result.setSuccess(true);
+        HashMap<String, Object> data = new HashMap<>();
+        data.put("expirestime", expiresTime);
+        data.put("usertoken", userToken);
+        result.setReturnData(R.success("0", data));
+        Integer multilogin = application.getMultilogin();
+        if (multilogin == 1) {
+            userloginlogService.removeByLogIdAndUserIdAndAppId(userloginlog.getLoginid(), userloginlog.getUserid(), userloginlog.getAppid());
         } else {
-            Map<String, Object> data = new HashMap<>();
-            Appconnectlog appconnectlog = applicationconnectlogService.findByTokenAndRequestIp(token.get(), requestIp.get());
-            if (Objects.nonNull(appconnectlog)) {
-                String appid = appconnectlog.getAppid();
-                Application application = applicationService.findByAppId(appid);
-                if (Objects.nonNull(application)) {
-                    result.put("code", "0");
-                    data.put("userid", userloginlog.getUserid());
-                    Long apptokeneffective = application.getApptokeneffective();
-                    data.put("expirestime", LocalDateTime.now().plusSeconds(apptokeneffective).format(dateTimeFormatter));
-                    String userToken = CommonUtil.toMD5("%s:%s".formatted(sessionId.get(), LocalDateTime.now()));
-                    data.put("usertoken", userToken);
-                    userloginlogService.removeUserLoginAppToken(sessionId.get(), userloginlog.getUserid(), userToken);
-                } else {
-                    result.put("code", "-1");
-                    result.put("message", "应用配置没有找到");
-                }
-            } else {
-                result.put("code", "-1");
-                result.put("message", "应用token没有找到");
-            }
+            userloginlogService.removeExpires();
         }
         return result;
+//        获取请求数据中的apptoken、sessionid和requestip。
+//        首先,通过verifyToken方法验证app的令牌(token)是否有效(返回是否有效、appid)。
+//        根据appid查询application对象。
+//        如果application为空
+//        code设置为-1,message设置为"应用配置没有找到"。
+//        根据apptoken、sessionid、requestip查询userloginlog对象。
+//        如果userloginlog为空,
+//        表示登录失败,code设置为-1,message设置为"登录失败"。
+//        如果userloginlog不为空(包含userid,logid),
+//        继续执行以下步骤:
+//        code设置为0。
+//        生成token过期时间:当前时间加上apptokeneffective秒后的时间。
+//        使用sessionId和当前时间生成一个用户令牌userToken。
+//        根据logid更新userToken,token过期时间,清空appToken
+//                判断application中的multilogin
+//        如果不等于1(不允许账号多点登录)
+//        删除userloginlog表中userid相同但是主键不等于当前logid的其他记录
+//        返回usertoken和过期时间。
+
     }
 
-    private Map<String, Object> checkUserToken(Map<String, Object> requestData) {
+    private ServiceDto<Map<String, Object>,Object> checkUserToken(Map<String, Object> requestData) {
         Optional<String> userToken = getValue("usertoken", requestData);
         Optional<String> sessionId = getValue("sessionid", requestData);
         Userloginlog userloginlog = userloginlogService.findByUserToken(userToken.get(), sessionId.get());
 
         String appid = userloginlog.getAppid();
         Application application = applicationService.findByAppId(appid);
+        ServiceDto<Map<String, Object>,Object> result = new ServiceDto<>();
         if (userloginlog.getLastheartbeat().plusSeconds(application.getApptokeneffective()).isBefore(LocalDateTime.now())) {
-            return new HashMap<>() {{
-                put("code", "1");
-                put("message", "用户token已过期");
-            }};
+            result.setSuccess(false);
+            result.setReturnData(R.fail("-1", "用户token已过期"));
+            return result;
         } else {
-            return new HashMap<>() {{
-                put("code", "0");
-            }};
+            result.setSuccess(true);
+            return result;
         }
 
     }
 
     //用户登出
-    public Map<String, Object> logOut(Map<String, Object> requestData) {
-        Map<String, Object> resultData = checkUserToken(requestData);
-        if (!"0".equals(resultData.get("code"))) {
+    public ServiceDto<Map<String, Object>,Object> logOut(Map<String, Object> requestData) {
+        ServiceDto<Map<String, Object>,Object> resultData = checkUserToken(requestData);
+        if (!resultData.isSuccess()) {
             return resultData;
         } else {
-            resultData = new HashMap<>();
 
             Optional<String> userToken = getValue("usertoken", requestData);
             Optional<String> sessionId = getValue("sessionid", requestData);
             Userloginlog userloginlog = userloginlogService.findByUserToken(userToken.get(), sessionId.get());
-
             userloginlogService.removeUserLoginLogByUserId(userloginlog.getUserid());
             permissionsService.removePermissions(userloginlog.getUserid());
-            resultData.put("code", "0");
-            resultData.put("message", "成功");
+            resultData.setReturnData(R.success("0", "成功", null));
             return resultData;
         }
     }
 
 
     //获取用户权限
-    public Map<String, Object> permission(Map<String, Object> requestData, Integer version) {
+    public ServiceDto<List<Permissions>,Object> permission(Map<String, Object> requestData) {
 
-        Map<String, Object> resultData = checkUserToken(requestData);
-        if (!"0".equals(resultData.get("code"))) {
+        ServiceDto<Map<String, Object>,Object> checked = checkUserToken(requestData);
+        ServiceDto<List<Permissions>,Object> resultData = new ServiceDto<>();
+        if (!checked.isSuccess()) {
+            resultData.setSuccess(false);
+            resultData.setReturnData(R.fail("-1", checked.getReturnData().getMessage()));
             return resultData;
         } else {
             Optional<String> userToken = getValue("usertoken", requestData);
             Optional<String> sessionId = getValue("sessionid", requestData);
             Userloginlog userloginlog = userloginlogService.findByUserToken(userToken.get(), sessionId.get());
-            if ("0".equals(version)) {
-                List<Permissions> ps = permissionsService.getPermissions(userloginlog.getUserid().toString());
-                resultData = new HashMap<>();
-                resultData.put("code", "0");
-                resultData.put("returnData", ps);
-            } else {
-                List<Map<String, Object>> ps = permissionsService.getPermissionsOld(userloginlog.getUserid().toString());
-                resultData = new HashMap<>();
-                resultData.put("code", "0");
-                resultData.put("returnData", ps);
-            }
+
+            List<Permissions> ps = permissionsService.getPermissions(userloginlog.getUserid().toString());
+            resultData.setReturnData(R.success("0", ps));
+
         }
         return resultData;
     }
 
     //应用API及数据权限
-    public Map<String, Object> changePassword(Map<String, Object> requestData) {
+    public ServiceDto<Map<String,Object>,Object> changePassword(Map<String, Object> requestData) {
 
-        Map<String, Object> resultData = checkUserToken(requestData);
-        if (!"0".equals(resultData.get("code"))) {
+        ServiceDto<Map<String, Object>,Object> checked = checkUserToken(requestData);
+        ServiceDto<Map<String,Object>,Object> resultData = new ServiceDto<>();
+        if (!checked.isSuccess()) {
+            resultData.setSuccess(false);
+            resultData.setReturnData(R.fail("-1", checked.getReturnData().getMessage()));
             return resultData;
         } else {
-            Optional<String> usertoken = getValue("usertoken", requestData);
             Optional<String> oldPassword = getValue("oldpassword", requestData);
             Optional<String> password = getValue("password", requestData);
 
             Optional<String> userToken = getValue("usertoken", requestData);
             Optional<String> sessionId = getValue("sessionid", requestData);
             Userloginlog userloginlog = userloginlogService.findByUserToken(userToken.get(), sessionId.get());
-            Integer userId = userloginlog.getUserid();
+            Long userId = userloginlog.getUserid();
             Userinfo userinfo = userinfoService.findByUserId(userId);
             if (Objects.nonNull(userinfo)) {
                 String userpassword = userinfo.getUserpassword();
                 if (!userpassword.equals(oldPassword.get())) {
-                    resultData.put("message", "密码错误");
-                    resultData.put("code", "-1");
+                    resultData.setSuccess(false);
+                    resultData.setReturnData(R.fail("-1", "密码错误"));
                     return resultData;
                 } else {
                     userinfoService.updateUserPassword(userId, password.get());
                 }
-                resultData = new HashMap<>();
-                resultData.put("code", "0");
-                resultData.put("message", "修改成功");
+                resultData.setSuccess(true);
+                resultData.setReturnData(R.success("-1", "成功", null));
+                return resultData;
+            } else {
+
+                resultData.setSuccess(false);
+                resultData.setReturnData(R.fail("-1", "用户没有找到"));
+                return resultData;
             }
 
         }
-        return resultData;
     }
 
     //用户心跳
-    public Map<String, Object> userHeartbeat(Map<String, Object> requestData) {
-        Map<String, Object> resultData = checkUserToken(requestData);
-        if (!"0".equals(resultData.get("code"))) {
+    public ServiceDto<List<Permissions>,Object> userHeartbeat(Map<String, Object> requestData) {
+        ServiceDto<Map<String, Object>,Object> checked = checkUserToken(requestData);
+        ServiceDto<List<Permissions>,Object> resultData = new ServiceDto<>();
+        if (!checked.isSuccess()) {
+            resultData.setSuccess(false);
+            resultData.setReturnData(R.fail("-1", checked.getReturnData().getMessage()));
             return resultData;
         } else {
-            resultData = new HashMap<>();
             Optional<String> userToken = getValue("usertoken", requestData);
             Optional<String> sessionId = getValue("sessionid", requestData);
             Userloginlog userloginlog1 = userloginlogService.findByUserToken(userToken.get(), sessionId.get());
@@ -415,19 +489,18 @@ public class SecurityService {
                     for (Userloginlog userloginlog : userloginlogs) {
 
                         userloginlogService.updateLoginLogUserLastTimeById(userloginlog.getLoginid(), sessionId.get());
-
-                        resultData.put("code", "0");
-                        resultData.put("message", "用户在线");
+                        resultData.setReturnData(R.success("0", "用户在线", null));
+                        resultData.setSuccess(true);
 
                     }
-                    if (resultData.isEmpty()) {
-                        resultData.put("code", "-1");
-                        resultData.put("message", "查询失败");
+                    if (!resultData.isSuccess()) {
+                        resultData.setReturnData(R.success("-1", "查询失败", null));
+                        resultData.setSuccess(false);
                     }
 
                 } else {
-                    resultData.put("code", "-1");
-                    resultData.put("message", "查询失败");
+                    resultData.setReturnData(R.success("-1", "查询失败", null));
+                    resultData.setSuccess(false);
                 }
             }
         }

+ 19 - 2
mainFactory/src/main/java/org/bfkj/services/UserinfoService.java

@@ -24,13 +24,13 @@ public class UserinfoService {
         this.securityJdbcTemplate = securityJdbcTemplate;
     }
 
-    public Userinfo findByUserId(Integer userId) {
+    public Userinfo findByUserId(Long userId) {
 
         return (Userinfo) securityJdbcTemplate.queryForObject("select * from userinfo where userid=?", new BeanPropertyRowMapper(Userinfo.class) , userId);
 
     }
 
-    public void updateUserPassword(Integer userId, String password) {
+    public void updateUserPassword(Long userId, String password) {
         securityJdbcTemplate.update("update userinfo set userpassword=? where userid=?", password, userId);
     }
 
@@ -48,4 +48,21 @@ public class UserinfoService {
         }
 
     }
+    public Userinfo findByUsernameAndPassword(String username,String password) {
+        synchronized (userInfoCache) {
+            Userinfo userinfo = userInfoCache.get(username);
+            if (Objects.nonNull(userinfo)) {
+                return userinfo;
+            } else {
+                Object result = securityJdbcTemplate.queryForObject("select * from userinfo where  username =? and userpassword=? ", new BeanPropertyRowMapper(Userinfo.class), username, password);
+                if(Objects.isNull(result)){
+                    return null;
+                }
+                userinfo = (Userinfo) result;
+                userInfoCache.put(username, userinfo);
+                return userinfo;
+            }
+        }
+
+    }
 }

+ 40 - 14
mainFactory/src/main/java/org/bfkj/services/UserloginlogService.java

@@ -15,6 +15,7 @@ import org.springframework.stereotype.Service;
 import java.time.LocalDateTime;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
 
 @Service
 public class UserloginlogService {
@@ -36,7 +37,7 @@ public class UserloginlogService {
                 userid, requestIp, sessionId, LocalDateTime.now(), md5Token, LocalDateTime.now(), LocalDateTime.now(), appToken, appid);
     }
 
-    public List<Userloginlog> findByUserId(Integer userId) {
+    public List<Userloginlog> findByUserId(Long userId) {
 
         List<Map<String, Object>> maps = securityJdbcTemplate.queryForList("select * from userloginlog where userid=? and isexpires=0 ", userId);
         return maps.stream().map(it -> {
@@ -50,38 +51,63 @@ public class UserloginlogService {
 
     }
 
+    public Userloginlog findByUserIdAndSessionId(Long userId, String sessionId) {
+
+        Map<String, Object> result = securityJdbcTemplate.queryForMap("select * from userloginlog where userid=? and sessionid=? and isexpires=0 ", userId, sessionId);
+        if (Objects.isNull(result)) {
+            return null;
+        }
+        try {
+            return objectMapper.readValue(objectMapper.writeValueAsString(result), Userloginlog.class);
+        } catch (JsonProcessingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public Userloginlog findByAppTokenAndSessionIdAndRequestIp(String appToken, String sessionId, String requestIp) {
+
+        Map<String, Object> result = securityJdbcTemplate.queryForMap("select * from userloginlog where apptoken=? and sessionid=? and requestip=? and isexpires=0 ", appToken, sessionId, requestIp);
+        if (Objects.isNull(result)) {
+            return null;
+        }
+        try {
+            return objectMapper.readValue(objectMapper.writeValueAsString(result), Userloginlog.class);
+        } catch (JsonProcessingException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
     public void removeUserLoginLog(@Nullable String apptokeneffective) {
         securityJdbcTemplate.update("delete from userloginlog where DATE_ADD(lasttime,INTERVAL ? MICROSECOND ) < now()",
                 apptokeneffective);
     }
 
 
-    public void removeUserLoginLogByUserId(@Nullable Integer userId) {
+    public void removeUserLoginLogByUserId(@Nullable Long userId) {
 
         securityJdbcTemplate.update("update userloginlog set isexpires=1 where userid = ?", userId);
     }
 
-    public void updateLoginLogUserLastTimeById(@Nullable Integer id, @Nonnull String sessionId) {
+    public void updateLoginLogUserLastTimeById(@Nullable Long id, @Nonnull String sessionId) {
         securityJdbcTemplate.update("update userloginlog set lasttime=now() where loginid=? and sessionid=?", id, sessionId);
     }
 
-    public void expiresByUserid(Integer userid) {
-        securityJdbcTemplate.update("update userloginlog set isexpires=1  where userid=? and isexpires=0", userid);
-    }
-
-    public Userloginlog findByAppToken(String appToken, String sessionId) {
-
-        return (Userloginlog) securityJdbcTemplate.queryForObject("select * from userloginlog where isexpires=0 and apptoken=? and sessionid=?", new BeanPropertyRowMapper(Userloginlog.class), appToken, sessionId);
-    }
-
     public Userloginlog findByUserToken(String userToken, String sessionId) {
 
         return (Userloginlog) securityJdbcTemplate.queryForObject("select * from userloginlog where isexpires=0 and usertoken=? and sessionid=?", new BeanPropertyRowMapper(Userloginlog.class), userToken, sessionId);
     }
 
-    public void removeUserLoginAppToken(String sessionId, Integer userid, String userToken) {
 
-        securityJdbcTemplate.update("update userloginlog set apptoken=?,usertoken=? where isexpires=0 and userid=? and sessionid=?",null, userToken, userid, sessionId);
+    public void updateUserToken(Long loginid, String userToken) {
+        securityJdbcTemplate.update("update userloginlog set apptoken=?,usertoken=?,lasttime=? where isexpires=0 and loginid=?", null, userToken, LocalDateTime.now(), loginid);
+
+    }
+
+    public void removeByLogIdAndUserIdAndAppId(Long loginId, Long userid, String appid) {
+        securityJdbcTemplate.update("delete  from userloginlog where (userid=? and appid=? and loginid <> ?) or isexpires=1", userid, appid, loginId);
+    }
 
+    public void removeExpires() {
+        securityJdbcTemplate.update("delete  from userloginlog where  isexpires=1");
     }
 }

+ 24 - 25
mainFactory/src/main/java/org/bfkj/services/cache/CodeCacheService.java

@@ -1,40 +1,39 @@
 package org.bfkj.services.cache;
 
+import org.bfkj.domain.Tempsecuritycode;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.jdbc.core.BeanPropertyRowMapper;
+import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.stereotype.Service;
 
 import java.time.LocalDateTime;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Objects;
-import java.util.stream.Stream;
 
 @Service
 public class CodeCacheService {
-    private final static Map<String, LocalDateTime> codeCache = new HashMap<>();
-
-    public void addCode(String code, String sessionId, Long securitycodeeffective) {
-        synchronized (codeCache) {
-            codeCache.put(code + sessionId, LocalDateTime.now().plusMinutes(securitycodeeffective));
-//            清理过期的数据
-            LocalDateTime now = LocalDateTime.now();
-            Stream<String> keys = codeCache.entrySet().stream().filter(it -> now.isAfter(it.getValue())).map(Map.Entry::getKey);
-            keys.forEach(codeCache::remove);
-        }
+
+    private final JdbcTemplate securityJdbcTemplate;
+
+    public CodeCacheService(@Qualifier("securityJdbcTemplate")  JdbcTemplate securityJdbcTemplate) {
+        this.securityJdbcTemplate = securityJdbcTemplate;
+    }
+
+    public void addCode(String code, String sessionId, String appid, Long securitycodeeffective, String requestIp) {
+//      使用数据库
+        LocalDateTime localDateTime = LocalDateTime.now().plusSeconds(securitycodeeffective);
+        securityJdbcTemplate.update("insert into tempsecuritycode(appid,requestip,sessionid,securitycode,expiretime) values (?,?,?,?,?)",appid,requestIp,sessionId,code,localDateTime);
+        securityJdbcTemplate.update("delete from tempsecuritycode where expiretime < now()");
+    }
+
+    public boolean check(String code, String sessionId, String appid,String requestIp) {
+        Map<String, Object> map = securityJdbcTemplate.queryForMap("select * from tempsecuritycode where securitycode=? and sessionid=? and appid=? and requestip=?", code, sessionId, appid, requestIp);
+        return Objects.nonNull(map) && !map.isEmpty();
+
     }
+    public void remove(String code, String sessionId, String appid,String requestIp) {
+         securityJdbcTemplate.update("delete from tempsecuritycode where securitycode=? and sessionid=? and appid=? and requestip=?", code, sessionId, appid, requestIp);
 
-    public boolean check(String code, String sessionId) {
-        synchronized (codeCache) {
-            LocalDateTime localDateTime = codeCache.get(code + sessionId);
-return true;
-//            if (Objects.isNull(localDateTime)) {
-//                return false;
-//            } else if (LocalDateTime.now().isAfter(localDateTime)) {
-//                codeCache.remove(code + sessionId);
-//                return false;
-//            } else {
-//                codeCache.remove(code + sessionId);
-//                return true;
-//            }
-        }
     }
 }

+ 1 - 1
mainFactory/src/main/java/org/bfkj/utils/MyDbHelper.java

@@ -712,7 +712,7 @@ public class MyDbHelper {//目前只差主键的条件优化
                     sqlPS.clearBatch();
                 }
             }
-            sqlPS.executeBatch();
+            int[] ints = sqlPS.executeBatch();
             connection.commit(); // 统一提交
             sqlPS.clearBatch();
             return processSuccess(dbValue);

+ 1 - 1
mainFactory/src/main/resources/application.yml

@@ -40,7 +40,7 @@ db:
     cipher: 123@bigdata
     type: com.mysql.cj.jdbc.Driver
   log:
-    url: jdbc:mysql://120.26.64.82:3306/oversecuritycenter
+    url: jdbc:mysql://120.26.64.82:3306/overlogcenter
     title: root
     cipher: 123@bigdata
     type: com.mysql.cj.jdbc.Driver