diff --git a/src/main/java/dev/surl/surl/controller/UserController.kt b/src/main/java/dev/surl/surl/controller/UserController.kt index f4ff27f..c82b505 100644 --- a/src/main/java/dev/surl/surl/controller/UserController.kt +++ b/src/main/java/dev/surl/surl/controller/UserController.kt @@ -1,14 +1,17 @@ package dev.surl.surl.controller +import dev.surl.surl.cfg.BaseConfig import dev.surl.surl.common.Msg import dev.surl.surl.common.enums.RedisStorage -import dev.surl.surl.common.exception.UnauthorizedExcecption +import dev.surl.surl.common.exception.UnauthorizedException 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.http.HttpHeaders import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RestController @@ -18,7 +21,10 @@ import org.springframework.web.bind.annotation.RestController */ @RestController class UserController( - private val jwtTokenUtil: JwtTokenUtil, private val redisUtil: RedisUtil, private val userService: UserService + private val jwtTokenUtil: JwtTokenUtil, + private val redisUtil: RedisUtil, + private val userService: UserService, + private val cfg: BaseConfig ) { /** * 用户注册 @@ -33,12 +39,24 @@ class UserController( */ @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") + if (!userService.authUser(user)) { + throw UnauthorizedException("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)) } + + @RequestMapping(method = [RequestMethod.GET], path = ["/loginCheck"]) + fun loginCheck(@RequestHeader header: HttpHeaders): Msg { + val token = header.getFirst("Authorization")?.substring(cfg.tokenHead.length) + ?: throw UnauthorizedException("token is empty") + val username = jwtTokenUtil.getUsernameFromToken(token) + val tokenInRedis = redisUtil.getString(username, RedisStorage.TOKEN) + if (tokenInRedis != token) { + throw UnauthorizedException("token is invalid") + } + return Msg() + } } \ No newline at end of file