增加登入端点

This commit is contained in:
05412 2024-07-25 18:15:07 +08:00
parent 8ec29a69f8
commit b0313feff9

View File

@ -1,9 +1,13 @@
package dev.surl.surl.controller 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.dto.UserDto
import dev.surl.surl.service.UserService import dev.surl.surl.service.UserService
import dev.surl.surl.util.JwtTokenUtil
import dev.surl.surl.util.redis.RedisUtil
import jakarta.validation.Valid import jakarta.validation.Valid
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestMethod
@ -13,12 +17,28 @@ import org.springframework.web.bind.annotation.RestController
* 用户操作控制器 * 用户操作控制器
*/ */
@RestController @RestController
class UserController { class UserController(
private val jwtTokenUtil: JwtTokenUtil, private val redisUtil: RedisUtil, private val userService: UserService
) {
/** /**
* 用户注册 * 用户注册
*/ */
@RequestMapping(method = [RequestMethod.POST], path = ["/reg"]) @RequestMapping(method = [RequestMethod.POST], path = ["/reg"])
fun reg( fun reg(
@Autowired service: UserService, @Valid @RequestBody(required = true) user: UserDto @Valid @RequestBody(required = true) user: UserDto
) = service.addUser(user.username!!, user.password!!) // 新增用户 ) = userService.addUser(user.username!!, user.password!!) // 新增用户
/**
* 用户登录
*/
@RequestMapping(method = [RequestMethod.POST], path = ["/login"])
fun login(@Valid @RequestBody(required = true) user: UserDto): Msg<Map<String, Any>> {
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))
}
} }