-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11-AuthController.kt
54 lines (50 loc) · 1.99 KB
/
11-AuthController.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@Service
class AuthController(
private val beanValidator: BeanValidator,
private val tokenKeyPublic: PublicKey,
private val grantPasswordTokenUsecase: GrantPasswordTokenUsecase,
private val grantRefreshTokenUsecase: GrantRefreshTokenUsecase,
private val logoutUserUsecase: LogoutUserUsecase,
) {
suspend fun publicKey(req: ServerRequest): ServerResponse {
return ServerResponse.ok()
.headers { it.contentType = MediaType("application", "x-pem-file") }
.bodyValueAndAwait(tokenKeyPublic.toPemString())
}
suspend fun login(req: ServerRequest): ServerResponse {
val cmd = req.awaitBody<GrantPasswordTokenUsecase.Command>().apply {
ip = req.remoteAddressOrNull()?.address?.hostAddress
}
beanValidator.valid(cmd)
val tokens = grantPasswordTokenUsecase.execute(cmd)
return ServerResponse.ok()
.cookie(
ResponseCookie.from(REFRESH_TOKEN_COOKIE, tokens.refreshToken)
.httpOnly(true)
.path("/api/auth/refresh")
.build()
)
.bodyValueAndAwait(tokens)
}
suspend fun refresh(req: ServerRequest): ServerResponse {
val refreshToken = req.cookies().getFirst(REFRESH_TOKEN_COOKIE)!!.value
val tokens = grantRefreshTokenUsecase.execute(refreshToken)
return ServerResponse.ok().bodyValueAndAwait(tokens)
}
suspend fun logout(req: ServerRequest): ServerResponse {
val refreshToken = req.cookies().getFirst(REFRESH_TOKEN_COOKIE)!!.value
logoutUserUsecase.execute(refreshToken)
return ServerResponse.ok()
.cookie(
ResponseCookie.from(REFRESH_TOKEN_COOKIE, "")
.httpOnly(true)
.path("/api/auth/refresh")
.maxAge(0)
.build()
)
.buildAndAwait()
}
companion object {
const val REFRESH_TOKEN_COOKIE = "refreshToken"
}
}