Browse Source

合并注册登录, 抽象 R 类, sql 唯一约束改为 is_deleted + user_name

zhenghao 5 tháng trước cách đây
mục cha
commit
ed10a06521

+ 3 - 2
sql/pg.sql

@@ -41,11 +41,12 @@ DROP TABLE IF EXISTS user_list;
 CREATE TABLE user_list (
     id bigserial primary key, -- 主键
     user_id text not null, -- 用户id
-    user_name text unique, -- 用户名
+    user_name text, -- 用户名
     user_password text NULL, -- 密码
     create_time timestamp(0) DEFAULT now() NULL, -- 创建时间
     update_time timestamp(0) DEFAULT now() NULL, -- 更新时间
-    is_deleted int2 default 0 NULL -- 是否删除
+    is_deleted int2 default 0, -- 是否删除
+    CONSTRAINT UNIQUE (user_name, is_deleted)
 );
 COMMENT ON TABLE user_list IS '用户列表';
 

+ 0 - 24
src/main/java/cn/jlsxwkj/common/R/ErrorHandler.java

@@ -1,24 +0,0 @@
-package cn.jlsxwkj.common.R;
-
-import lombok.Data;
-
-/**
- *  @author zh
- *  异常封装类
- */
-@Data
-public class ErrorHandler {
-    /**
-     * 异常的状态码
-     */
-    private Integer status;
-    /**
-     * 异常的消息
-     */
-    private String message;
-    /**
-     * 异常的名字
-     */
-    private String exception;
-
-}

+ 5 - 41
src/main/java/cn/jlsxwkj/common/R/Response.java

@@ -1,58 +1,22 @@
 package cn.jlsxwkj.common.R;
 
-
-import io.netty.handler.codec.http.HttpResponseStatus;
 import lombok.Data;
 
 /**
- * @Author zh
+ * @author zh
  */
 @Data
-public class Response {
+public abstract class Response {
     /**
      * 标识返回状态
      */
-    private Integer code;
+    Integer code;
     /**
      * 标识返回内容
      */
-    private Object data;
+    Object data;
     /**
      * 标识返回消息
      */
-    private String message;
-    /**
-     * 标识返回异常
-     */
-    private String exception;
-
-    /**
-     * 禁止构造对象
-     */
-    private Response () {}
-
-    /**
-     * 成功返回
-     *
-     */
-    public static Response data(Object data){
-        Response r = new Response();
-        r.setCode(HttpResponseStatus.OK.code());
-        r.setMessage(HttpResponseStatus.OK.reasonPhrase());
-        r.setData(data);
-        return r;
-    }
-
-    /**
-     * 失败返回
-     *
-     */
-    public static Response error(Integer code, String message, String exception){
-        Response r = new Response();
-        r.setCode(code);
-        r.setMessage(message);
-        r.setException(exception);
-        return r;
-    }
+    String message;
 }
-

+ 26 - 0
src/main/java/cn/jlsxwkj/common/R/ResponseError.java

@@ -0,0 +1,26 @@
+package cn.jlsxwkj.common.R;
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ *  @author zh
+ *  异常封装类
+ */
+@EqualsAndHashCode(callSuper = true)
+@Data
+public class ResponseError extends Response {
+
+    /**
+     * 标识返回异常
+     */
+    private String exception;
+
+    public static ResponseError data(String exception){
+        ResponseError r = new ResponseError();
+        r.setCode(500);
+        r.setMessage("服务器异常");
+        r.setException(exception);
+        return r;
+    }
+}

+ 22 - 0
src/main/java/cn/jlsxwkj/common/R/ResponseSucceed.java

@@ -0,0 +1,22 @@
+package cn.jlsxwkj.common.R;
+
+
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+/**
+ * @Author zh
+ */
+@EqualsAndHashCode(callSuper = true)
+@Data
+public class ResponseSucceed extends Response {
+
+    public static ResponseSucceed data(Object data){
+        ResponseSucceed r = new ResponseSucceed();
+        r.setCode(200);
+        r.setMessage("完成");
+        r.setData(data);
+        return r;
+    }
+}
+

+ 11 - 10
src/main/java/cn/jlsxwkj/common/R/GlobalRestExceptionHandler.java → src/main/java/cn/jlsxwkj/common/handler/GlobalRestExceptionHandler.java

@@ -1,10 +1,10 @@
-package cn.jlsxwkj.common.R;
+package cn.jlsxwkj.common.handler;
 
 import cn.dev33.satoken.exception.SaTokenException;
+import cn.jlsxwkj.common.R.ResponseError;
 import cn.jlsxwkj.common.utils.Log;
 import cn.jlsxwkj.moudles.logerror.LogError;
 import cn.jlsxwkj.moudles.logerror.LogErrorService;
-import io.netty.handler.codec.http.HttpResponseStatus;
 import jakarta.annotation.Resource;
 import org.springframework.web.ErrorResponse;
 import org.springframework.web.bind.annotation.ExceptionHandler;
@@ -28,30 +28,31 @@ public class GlobalRestExceptionHandler {
      * @return 封装异常对象
      */
     @ExceptionHandler(Throwable.class)
-    public ErrorHandler exception(Exception e) {
-        ErrorHandler errorHandler = new ErrorHandler();
-        errorHandler.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
-        errorHandler.setMessage("未知异常");
-        errorHandler.setException(e.getClass().getName());
+    public ResponseError exception(Exception e) {
+        ResponseError errorHandler = ResponseError.data(e.getClass().getName());
+
         if (e instanceof LoginException) {
             errorHandler.setMessage(e.getMessage());
         }
         if (e instanceof ErrorResponse) {
-            errorHandler.setStatus(((ErrorResponse)e).getStatusCode().value());
+            errorHandler.setCode(((ErrorResponse)e).getStatusCode().value());
             errorHandler.setMessage(e.getMessage());
         }
         if (e instanceof SaTokenException) {
-            errorHandler.setStatus(((SaTokenException)e).getCode());
+            errorHandler.setCode(((SaTokenException)e).getCode());
             errorHandler.setMessage("账户未登录");
         }
+
         LogError errorHandlerToLogError = new LogError().castErrorHandlerToLogError(errorHandler);
         errorHandlerToLogError.setErrorInfo(e.getMessage());
         errorHandlerToLogError.setErrorStackTrace(Arrays.toString(e.getStackTrace()));
         logErrorService.insertOne(errorHandlerToLogError);
-        Log.error(e.getClass(), "Code       ====> {}", errorHandler.getStatus());
+
+        Log.error(e.getClass(), "Code       ====> {}", errorHandler.getCode());
         Log.error(e.getClass(), "Exception  ====> {}", errorHandler.getException());
         Log.error(e.getClass(), "Message    ====> {}", errorHandler.getMessage());
         Log.error(e.getClass(), "ErrInfo    ====> {}", e.getMessage());
+
         return errorHandler;
     }
 }

+ 12 - 7
src/main/java/cn/jlsxwkj/common/R/ResultResponseHandler.java → src/main/java/cn/jlsxwkj/common/handler/ResultResponseHandler.java

@@ -1,6 +1,8 @@
-package cn.jlsxwkj.common.R;
+package cn.jlsxwkj.common.handler;
 
 
+import cn.jlsxwkj.common.R.ResponseError;
+import cn.jlsxwkj.common.R.ResponseSucceed;
 import cn.jlsxwkj.common.utils.Log;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import org.springframework.core.MethodParameter;
@@ -36,22 +38,25 @@ public class ResultResponseHandler implements ResponseBodyAdvice<Object> {
                                   @Nullable ServerHttpRequest serverHttpRequest,
                                   @Nullable ServerHttpResponse serverHttpResponse) {
         // 对请求的结果在这里统一返回和处理
-        if (o instanceof ErrorHandler) {
+        if (o instanceof ResponseError) {
             // 1、如果返回的结果是一个异常的结果,就把异常返回的结构数据倒腾到R.fail里面即可
-            ErrorHandler errorHandler = (ErrorHandler) o;
-            return Response.error(errorHandler.getStatus(), errorHandler.getMessage(), errorHandler.getException());
+            ResponseError errorHandler = (ResponseError) o;
+            return ResponseSucceed.data(errorHandler);
         }
         if (o instanceof String) {
             try {
                 // 2、因为springmvc数据转换器对String是有特殊处理 StringHttpMessageConverter
                 ObjectMapper objectMapper = new ObjectMapper();
-                Response r = Response.data(o);
-                return objectMapper.writeValueAsString(r);
+                ResponseSucceed data = ResponseSucceed.data(o);
+                return objectMapper.writeValueAsString(data);
             } catch (Exception e) {
                 Log.error(e.getClass(), Arrays.toString(e.getStackTrace()));
             }
         }
-        return Response.data(o);
+        if (null == o) {
+            return null;
+        }
+        return ResponseSucceed.data(o);
     }
 }
 

+ 6 - 12
src/main/java/cn/jlsxwkj/moudles/chat/ChatService.java

@@ -134,6 +134,7 @@ public class ChatService {
 	 * @return 			回答内容
 	 */
 	public Flux<String> chatStream(String message) {
+		String userId = SaManager.getStpLogic("").getLoginIdAsString();
 		chatMessage = new StringBuffer();
 		//查询获取文档信息
 		String content = search(message);
@@ -145,12 +146,12 @@ public class ChatService {
 					System.out.print(str);
 					chatMessage.append(str);
 					return str.replace(" ", "  ");
-				})
-				.concatWithValues("<{完成}>").onErrorStop()
+				}).concatWithValues("<{完成}>")
+				.onErrorStop()
 				.doOnComplete(() -> {
 					System.out.println();
 					LIST_MESSAGE.add(new AssistantMessage(chatMessage.toString()));
-					saveDialog(message, chatMessage.toString());
+					chatHistoryService.insert(userId, message, chatMessage.toString());
 				});
 
 	}
@@ -162,6 +163,7 @@ public class ChatService {
 	 * @return 			回答内容
 	 */
 	public String chat(String message) {
+		String userId = SaManager.getStpLogic("").getLoginIdAsString();
 		chatMessage = new StringBuffer();
 		//查询获取文档信息
 		String content = search(message);
@@ -171,7 +173,7 @@ public class ChatService {
 		chatMessage.append(result);
 		Log.info(this.getClass(),"{} message : {}", "chat", result);
 		LIST_MESSAGE.add(new AssistantMessage(chatMessage.toString()));
-		saveDialog(message, chatMessage.toString());
+		chatHistoryService.insert(userId, message, chatMessage.toString());
 		return result;
 	}
 
@@ -189,12 +191,4 @@ public class ChatService {
 		LIST_MESSAGE.add(new UserMessage(message));
 		return prompt;
 	}
-
-	/**
-	 * 保存会话
-	 */
-	private void saveDialog(String userQ, String chatA) {
-		String userId = SaManager.getStpLogic("").getLoginIdAsString();
-		chatHistoryService.insert(userId, userQ, chatA);
-	}
 }

+ 2 - 2
src/main/java/cn/jlsxwkj/moudles/chathistory/ChatHistoryController.java

@@ -2,7 +2,7 @@ package cn.jlsxwkj.moudles.chathistory;
 
 import io.swagger.v3.oas.annotations.Operation;
 import jakarta.annotation.Resource;
-import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
@@ -19,7 +19,7 @@ public class ChatHistoryController {
     private ChatHistoryService chatHistoryService;
 
     @Operation(summary = "获取历史对话")
-    @PostMapping("/getHistory")
+    @GetMapping("/getHistory")
     public List<ChatHistory> selectHistory() {
         return chatHistoryService.selectHistoryByUserId();
     }

+ 2 - 2
src/main/java/cn/jlsxwkj/moudles/logerror/LogError.java

@@ -1,6 +1,6 @@
 package cn.jlsxwkj.moudles.logerror;
 
-import cn.jlsxwkj.common.R.ErrorHandler;
+import cn.jlsxwkj.common.R.ResponseError;
 import lombok.Data;
 
 /**
@@ -16,7 +16,7 @@ public class LogError {
     private String errorStackTrace;
     private java.sql.Timestamp createTime;
 
-    public LogError castErrorHandlerToLogError(ErrorHandler errorHandler) {
+    public LogError castErrorHandlerToLogError(ResponseError errorHandler) {
         this.setMessage(errorHandler.getMessage());
         this.setException(errorHandler.getException());
         return this;

+ 2 - 9
src/main/java/cn/jlsxwkj/moudles/userlist/UserListController.java

@@ -19,16 +19,9 @@ public class UserListController {
 
     @Operation(summary = "登录")
     @PostMapping("/login")
-    public String login(@RequestParam String userName,
+    public UserVO login(@RequestParam String userName,
                           @RequestParam String userPassword) throws LoginException {
-        return userListService.checkUser(userName, userPassword);
-    }
-
-    @Operation(summary = "注册")
-    @PostMapping("/auth")
-    public String auth(@RequestParam String userName,
-                        @RequestParam String userPassword) throws LoginException {
-        return userListService.authUser(userName, userPassword);
+        return userListService.checkOrAddUser(userName, userPassword);
     }
 
     @Operation(summary = "登出")

+ 24 - 20
src/main/java/cn/jlsxwkj/moudles/userlist/UserListService.java

@@ -20,34 +20,38 @@ public class UserListService {
     private UserListMapper userListMapper;
     private final Snowflake snowflake = new Snowflake();
 
-    public String authUser(String userName, String userPassword) throws AccountException {
-        if (userListMapper.checkUser(userName) != null) {
-            throw new AccountException("用户已注册, 请勿重复注册");
-        }
-        UserList userList = new UserList();
-        userList.setUserId(snowflake.nextIdStr());
-        userList.setUserName(userName);
-        userList.setUserPassword(SaSecureUtil.sha512(userPassword));
-        Integer rows = userListMapper.authUser(userList);
-        if (rows > 0) {
-            return "注册成功";
-        }
-        throw new AccountException("注册失败");
-    }
-
-    public String checkUser(String userName, String userPassword) throws LoginException {
+    public UserVO checkOrAddUser(String userName, String userPassword) throws LoginException {
+        String sha512pwd = SaSecureUtil.sha512(userPassword);
         UserList userList = userListMapper.checkUser(userName);
+        UserVO userVO = new UserVO();
         if (userList != null) {
-            if (!userList.getUserPassword().contains(SaSecureUtil.sha512(userPassword))) {
+            if (!userList.getUserPassword().contains(sha512pwd)) {
                 throw new FailedLoginException("密码错误");
             }
             if (!StpUtil.isLogin()) {
                 String userId = userList.getUserId();
-                StpUtil.login(userId);
-                return "登录成功";
+                StpUtil.login(userId, false);
+                userVO.setUserId(userId);
+                userVO.setUserName(userList.getUserName());
+                userVO.setMessage("登录成功");
+                return userVO;
             }
             throw new LoginException("请勿重复登录");
         }
-        throw new FailedLoginException("用户未注册");
+        userList = new UserList();
+        userList.setUserId(snowflake.nextIdStr());
+        userList.setUserName(userName);
+        userList.setUserPassword(sha512pwd);
+        Integer rows = userListMapper.authUser(userList);
+        if (rows > 0) {
+            String userId = userList.getUserId();
+            StpUtil.login(userId, false);
+            userVO.setUserId(userId);
+            userVO.setUserName(userList.getUserName());
+            userVO.setMessage("注册成功");
+            return userVO;
+
+        }
+        throw new AccountException("注册失败");
     }
 }

+ 13 - 0
src/main/java/cn/jlsxwkj/moudles/userlist/UserVO.java

@@ -0,0 +1,13 @@
+package cn.jlsxwkj.moudles.userlist;
+
+import lombok.Data;
+
+/**
+ * @author zh
+ */
+@Data
+public class UserVO {
+    private String userId;
+    private String userName;
+    private String message;
+}