From b0313feff985c4834c899ed6bc685878d6591a88 Mon Sep 17 00:00:00 2001 From: 05412 <2738076308@qq.com> Date: Thu, 25 Jul 2024 18:15:07 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=99=BB=E5=85=A5=E7=AB=AF?= =?UTF-8?q?=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../surl/surl/controller/UserController.kt | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/main/java/dev/surl/surl/controller/UserController.kt b/src/main/java/dev/surl/surl/controller/UserController.kt index 54e0f6d..f4ff27f 100644 --- a/src/main/java/dev/surl/surl/controller/UserController.kt +++ b/src/main/java/dev/surl/surl/controller/UserController.kt @@ -1,9 +1,13 @@ package dev.surl.surl.controller +import dev.surl.surl.common.Msg +import dev.surl.surl.common.enums.RedisStorage +import dev.surl.surl.common.exception.UnauthorizedExcecption import dev.surl.surl.dto.UserDto import dev.surl.surl.service.UserService +import dev.surl.surl.util.JwtTokenUtil +import dev.surl.surl.util.redis.RedisUtil import jakarta.validation.Valid -import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod @@ -13,12 +17,28 @@ import org.springframework.web.bind.annotation.RestController * 用户操作控制器 */ @RestController -class UserController { +class UserController( + private val jwtTokenUtil: JwtTokenUtil, private val redisUtil: RedisUtil, private val userService: UserService +) { /** * 用户注册 */ @RequestMapping(method = [RequestMethod.POST], path = ["/reg"]) fun reg( - @Autowired service: UserService, @Valid @RequestBody(required = true) user: UserDto - ) = service.addUser(user.username!!, user.password!!) // 新增用户 + @Valid @RequestBody(required = true) user: UserDto + ) = userService.addUser(user.username!!, user.password!!) // 新增用户 + + /** + * 用户登录 + */ + @RequestMapping(method = [RequestMethod.POST], path = ["/login"]) + fun login(@Valid @RequestBody(required = true) user: UserDto): Msg> { + if(!userService.authUser(user)) { + throw UnauthorizedExcecption("invalid username or password") + } + val username = user.username!! + val (expireAt, token) = jwtTokenUtil.getToken(username, emptyList()) + redisUtil.setString(username, token, RedisStorage.TOKEN) + return Msg(code = 0, value = mapOf("expireAt" to expireAt, "token" to token)) + } } \ No newline at end of file