From 1acf9a48021d0af1d81fdf3ed8fcf8dffd020f6b Mon Sep 17 00:00:00 2001 From: hongjli <3117313295@qq.com> Date: 星期二, 15 四月 2025 14:20:51 +0800 Subject: [PATCH] 登录,注册,获取用户信息---接口 --- src/main/java/com/weiwojc/controller/UserController.java | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 54 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/weiwojc/controller/UserController.java b/src/main/java/com/weiwojc/controller/UserController.java new file mode 100644 index 0000000..40cb2fb --- /dev/null +++ b/src/main/java/com/weiwojc/controller/UserController.java @@ -0,0 +1,54 @@ +package com.weiwojc.controller; + +import com.weiwojc.model.common.Result; +import com.weiwojc.model.dto.UserLoginDTO; +import com.weiwojc.model.dto.UserRegisterDTO; +import com.weiwojc.model.entity.User; +import com.weiwojc.service.UserService; +import com.weiwojc.utils.JwtUtils; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/api/users") +@RequiredArgsConstructor +public class UserController { + + private final UserService userService; + private final JwtUtils jwtUtils; + + @PostMapping("/register") + public Result<User> register(@Valid @RequestBody UserRegisterDTO registerDTO) { + User user = userService.register(registerDTO); + return Result.success("娉ㄥ唽鎴愬姛", user); + } + + @PostMapping("/login") + public Result<String> login(@Valid @RequestBody UserLoginDTO loginDTO) { + String token = userService.login(loginDTO); + return Result.success("鐧诲綍鎴愬姛", token); + } + + @GetMapping("/info") + public Result<User> getUserInfo(HttpServletRequest request) { + String token = request.getHeader("token"); + // 楠岃瘉token鏄惁瀛樺湪 + if (token == null || token.isEmpty()) { + return Result.unauthorized("鏈櫥褰曟垨token鏃犳晥"); + } + + Long userId = jwtUtils.getUserIdFromToken(token); + if (userId == null) { + return Result.unauthorized("token鏃犳晥鎴栧凡杩囨湡"); + } + + User user = userService.getUserInfo(userId); + if (user == null) { + return Result.error("鐢ㄦ埛涓嶅瓨鍦�"); + } + + return Result.success(user); + } +} \ No newline at end of file -- Gitblit v1.9.3