Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement JwtAgent, Kakao Login #15

Merged
merged 3 commits into from
Dec 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion raisedragon-api/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ dependencies {

implementation("org.springframework.boot:spring-boot-starter-validation:3.0.4")
implementation("org.springframework.boot:spring-boot-starter-aop:3.0.4")

// Swagger
implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:$swaggerVersion")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.whatever.raisedragon.applicationservice

import com.whatever.raisedragon.domain.auth.AuthService
import com.whatever.raisedragon.domain.user.Nickname
import com.whatever.raisedragon.domain.user.User
import com.whatever.raisedragon.domain.user.UserService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
@Transactional
class AuthApplicationService(
private val authService: AuthService,
private val userService: UserService,
) {

fun kakoLogin(accessToken: String): User {
val kakaoId = authService.verifyKaKao(accessToken)
return userService.loadByOAuthPayload(kakaoId) ?: return userService.create(
User(
oauthTokenPayload = kakaoId,
fcmTokenPayload = null,
nickname = Nickname.generateRandomNickname()
)
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.whatever.raisedragon.controller.auth

import com.whatever.raisedragon.applicationservice.AuthApplicationService
import com.whatever.raisedragon.common.Response
import io.swagger.v3.oas.annotations.Operation
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("/v1/auth")
class AuthController(
private val authApplicationService: AuthApplicationService,
) {

@Operation(summary = "LoginAPI", description = "Kakao Login")
@PostMapping("/login")
fun login(@RequestBody loginRequest: LoginRequest): Response<LoginResponse> {
return Response.success(
LoginResponse(authApplicationService.kakoLogin(loginRequest.accessToken))
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.whatever.raisedragon.controller.auth

import com.whatever.raisedragon.domain.user.User
import io.swagger.v3.oas.annotations.media.Schema
import jakarta.validation.constraints.NotBlank

@Schema(description = "[Request] 카카오 로그인")
data class LoginRequest(
@NotBlank
@Schema(description = "카카오에서 발급받은 AccessToken")
val accessToken: String
)

@Schema(description = "[Request] 카카오 로그인 응답")
data class LoginResponse(
val user: User
)
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,13 @@ data class UserRetrieveResponse(

@Schema(description = "닉네임")
val nickname: Nickname,
)

@Schema(description = "[Response] 유저 로그인")
data class UserLoginResponse(
@Schema(description = "Access Token")
val accessToken: String,

@Schema(description = "Refresh Token")
val refreshToken: String,
)
5 changes: 5 additions & 0 deletions raisedragon-core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ dependencies {

// jasypt
api("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5")

// JWT
implementation("io.jsonwebtoken:jjwt-api:0.11.5")
implementation("io.jsonwebtoken:jjwt-impl:0.11.5")
implementation("io.jsonwebtoken:jjwt-jackson:0.11.5")
}

allOpen {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.whatever.raisedragon.common.config

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.client.RestTemplate


@Configuration
class RestTemplateConfig {
@Bean
fun restTemplate(): RestTemplate {
return RestTemplate()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ interface AuthService {
* @param userToken 사용자가 클라이언트에서 발급받은 토큰입니다.
* @return 사용자의 카카오 유저 아이디. 반환 값이 없거나 유효하지 않은 토큰인 경우 null을 반환합니다.
*/
fun verifyKakao(userToken: String): String?
fun verifyKaKao(userToken: String): String
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,4 @@ interface JwtAgent {
* @return JwtToken 을 반환합니다.
*/
fun provide(user: User): JwtToken

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.whatever.raisedragon.domain.auth.jwt

import com.whatever.raisedragon.domain.user.User
import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import org.springframework.stereotype.Component
import java.util.*

@Component
class JwtAgentImpl(
private val jwtGenerator: JwtGenerator
) : JwtAgent {

companion object {
private const val BEARER_PREFIX = "Bearer "
private const val ACCESS_TOKEN_EXPIRE_TIME = (1000 * 60 * 30).toLong()
private const val REFRESH_TOKEN_EXPIRE_TIME = (1000 * 60 * 60 * 24 * 7).toLong()
}

override fun provide(user: User): JwtToken {
val now = Date().time

return JwtToken(
accessToken = BEARER_PREFIX + jwtGenerator.generateAccessToken(
claims = buildClaims(user),
accessTokenExpiredAt = Date(now + ACCESS_TOKEN_EXPIRE_TIME)
),
refreshToken = BEARER_PREFIX + jwtGenerator.generateRefreshToken(
Date(now + REFRESH_TOKEN_EXPIRE_TIME)
)
)
}

private fun buildClaims(user: User): Claims {
val claims = Jwts.claims()
claims.setSubject(user.nickname.value)
claims["id"] = user.id
return claims
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.whatever.raisedragon.domain.auth.jwt

import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.security.Keys
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component
import java.security.Key
import java.util.*

@Component
class JwtGenerator {

@Value("\${jwt.secret-key}")
private var key: String? = null

internal fun generateAccessToken(
claims: Claims,
accessTokenExpiredAt: Date
): String {
return Jwts.builder()
.signWith(getSigningKey())
.setHeaderParam("type", "JWT")
.setClaims(claims)
.setExpiration(accessTokenExpiredAt)
.compact()
}

internal fun generateRefreshToken(
refreshTokenExpireIn: Date
): String {
return Jwts.builder()
.signWith(getSigningKey())
.setHeaderParam("type", "JWT")
.setExpiration(refreshTokenExpireIn)
.compact()
}

private fun getSigningKey(): Key {
val keyBytes = Decoders.BASE64.decode(key)
return Keys.hmacShaKeyFor(keyBytes)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.whatever.raisedragon.domain.auth.oauth.kakao

import com.fasterxml.jackson.annotation.JsonProperty
import java.time.LocalDateTime

data class KakaoLoginResponse(
@JsonProperty("id")
val id: String? = null,

@JsonProperty("connected_at")
val connectedAt: LocalDateTime? = null,
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.whatever.raisedragon.domain.auth.oauth.kakao

import com.whatever.raisedragon.domain.auth.AuthService
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate

@Service
class KakaoOAuthService(
private val restTemplate: RestTemplate,
) : AuthService {

private val KAKAO_USERINFO_REQUEST_URL = "https://kapi.kakao.com/v2/user/me"
override fun verifyKaKao(userToken: String): String {
val headers = HttpHeaders()
headers.contentType = MediaType.APPLICATION_FORM_URLENCODED
headers.setBearerAuth(userToken)

val request = HttpEntity(
null,
headers
)

val response = restTemplate.postForEntity(
KAKAO_USERINFO_REQUEST_URL,
request,
KakaoLoginResponse::class.java
)

return response.body?.id!!
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ package com.whatever.raisedragon.domain.user
import java.time.LocalDateTime

data class User(
val id: Long,
val id: Long? = 0L,
val oauthTokenPayload: String?,
val fcmTokenPayload: String?,
val nickname: Nickname,
var deletedAt: LocalDateTime?,
var createdAt: LocalDateTime?,
var updatedAt: LocalDateTime?
var deletedAt: LocalDateTime? = LocalDateTime.now(),
var createdAt: LocalDateTime? = LocalDateTime.now(),
var updatedAt: LocalDateTime? = LocalDateTime.now()
)

fun UserEntity.toDto(): User = User(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,21 @@ class UserEntity(

) : BaseEntity()

fun User.fromDto(): UserEntity = UserEntity(
oauthTokenPayload = oauthTokenPayload,
fcmTokenPayload = fcmTokenPayload,
nickname = nickname,
)

@Embeddable
data class Nickname(val nickname: String)
data class Nickname(
@Column(name = "nickname")
val value: String
) {
companion object {
fun generateRandomNickname(): Nickname {
return Nickname("random nickname")
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface UserRepository : JpaRepository<UserEntity, Long>
interface UserRepository : JpaRepository<UserEntity, Long> {
fun findByOauthTokenPayload(payload: String): UserEntity?
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,15 @@ import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

보통 여기서 readOnly = true 하고 밑에 실제 트랜잭션 동작이 있는곳에 @transactional 붙이지 않나요? readOnly의 default가 true인것 같아서요

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 defaultfalse로 알고있는데 이건 그냥 저희끼리만 통일화하면 될 것 같아요~

class UserService(
private val userRepository: UserRepository
)
private val userRepository: UserRepository,
) {

@Transactional(readOnly = true)
fun loadByOAuthPayload(payload: String): User? {
return userRepository.findByOauthTokenPayload(payload)?.toDto()
}

fun create(user: User): User {
return userRepository.save(user.fromDto()).toDto()
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
jwt:
secret-key: ENC(nFedRKX5zt00VoNk/11zZcZVAtdnl/AHTDJW74urxj103ameypl1NctWnJYl90thp8OS/DIP8B0oHXgvMVJ02TPFiMZes3Kf3/EPG9t/MnUKvjc4iz1HZ+F76oDcvxXheKiioRZkGt1b0g9iyh7PW4CKSo5T/rScgXsg2c+05bg=)

spring:
config:
activate:
Expand All @@ -6,7 +9,7 @@ spring:
driver-class-name: com.mysql.cj.jdbc.Driver
url: ENC(XipKlkEc8VLlKgM59OC01yV9WC2y7t7TISTVBYLuQG3CGPz/ph3dSwxtNMxjhJ548592hcelCVmuzEuRJJPP2dS6//yQrpBdBbujHL4m9c4=)
username: ENC(n1+fm+uUm/VLP6b0uTsVjeHAkMIobcWsdcfMqW+d8lvMUJKMH/jv9Se7C9hY6pG1)
password: ENC(wjhc+VfBjNy+DbgceiG+2/4CPBkLFiDaGqSjjyMRaThj/XtXkWNgPQSQuN4FO0Ge)
password: ENC(OdGW0TMCzvntfVve9NJ48/ZM40ab3jlIwZoRuA06GLrptSy/4aM6J8TW6nNhfxmz)
jpa:
hibernate:
ddl-auto: validate
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
jwt:
secret-key: ENC(nFedRKX5zt00VoNk/11zZcZVAtdnl/AHTDJW74urxj103ameypl1NctWnJYl90thp8OS/DIP8B0oHXgvMVJ02TPFiMZes3Kf3/EPG9t/MnUKvjc4iz1HZ+F76oDcvxXheKiioRZkGt1b0g9iyh7PW4CKSo5T/rScgXsg2c+05bg=)

spring:
config:
activate:
Expand Down