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