43 lines
2.1 KiB
Kotlin
43 lines
2.1 KiB
Kotlin
package net.halfbinary.scavengerhuntapi.controller
|
|
|
|
import jakarta.validation.Valid
|
|
import net.halfbinary.scavengerhuntapi.config.JwtUtil
|
|
import net.halfbinary.scavengerhuntapi.model.converter.toDomain
|
|
import net.halfbinary.scavengerhuntapi.model.converter.toRefreshResponse
|
|
import net.halfbinary.scavengerhuntapi.model.request.LoginRequest
|
|
import net.halfbinary.scavengerhuntapi.model.request.LogoutRequest
|
|
import net.halfbinary.scavengerhuntapi.model.request.RefreshRequest
|
|
import net.halfbinary.scavengerhuntapi.model.response.LoginResponse
|
|
import net.halfbinary.scavengerhuntapi.model.response.RefreshResponse
|
|
import net.halfbinary.scavengerhuntapi.service.LoginService
|
|
import net.halfbinary.scavengerhuntapi.service.RefreshTokenService
|
|
import org.springframework.http.ResponseEntity
|
|
import org.springframework.web.bind.annotation.PostMapping
|
|
import org.springframework.web.bind.annotation.RequestBody
|
|
import org.springframework.web.bind.annotation.RequestMapping
|
|
import org.springframework.web.bind.annotation.RestController
|
|
|
|
|
|
@RestController
|
|
@RequestMapping("/auth")
|
|
class AuthController(private val loginService: LoginService, private val jwtUtils: JwtUtil, private val refreshTokenService: RefreshTokenService) {
|
|
@PostMapping("/login")
|
|
fun login(@Valid @RequestBody body: LoginRequest): ResponseEntity<LoginResponse> {
|
|
val result = loginService.login(body.toDomain())
|
|
val accessToken = jwtUtils.generateToken(result.email)
|
|
val refreshToken = refreshTokenService.generateRefreshToken(result.email)
|
|
val loginResponse = LoginResponse(accessToken, refreshToken)
|
|
return ResponseEntity.ok(loginResponse)
|
|
}
|
|
|
|
@PostMapping("/refresh")
|
|
fun refresh(@RequestBody body: RefreshRequest): ResponseEntity<RefreshResponse> {
|
|
return ResponseEntity.ok(refreshTokenService.getAccessToken(body.refreshToken).toRefreshResponse())
|
|
}
|
|
|
|
@PostMapping("/logout")
|
|
fun logout(@RequestBody body: LogoutRequest): ResponseEntity<String> {
|
|
refreshTokenService.removeToken(body.refreshToken)
|
|
return ResponseEntity.ok().build()
|
|
}
|
|
} |