Skip to content

Commit

Permalink
refactor : 리팩터링 (#128)
Browse files Browse the repository at this point in the history
* refactor : auth class

* refactor : util class

* reafactor : id to non nullable

* refactor : etcs

* fix compile err

* fix : add suppress
  • Loading branch information
kshired authored Oct 15, 2023
1 parent 0115db9 commit e887d6d
Show file tree
Hide file tree
Showing 69 changed files with 160 additions and 197 deletions.
24 changes: 11 additions & 13 deletions src/main/kotlin/io/csbroker/apiserver/auth/AuthToken.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,17 @@ class AuthToken(
private val key: Key,
) {
constructor(email: String, expiry: Date, key: Key, role: String? = null) : this("", key) {
if (role != null) {
token = createAuthToken(email, expiry, role)
token = if (role != null) {
createAuthToken(email, expiry, role)
} else {
token = createAuthToken(email, expiry)
createAuthToken(email, expiry)
}
}

val tokenClaims: Claims?
get() {
try {
return Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.body
return parseJwt()
} catch (e: SecurityException) {
log.error("Invalid JWT signature.")
} catch (e: MalformedJwtException) {
Expand All @@ -52,11 +48,7 @@ class AuthToken(
val expiredTokenClaims: Claims?
get() {
try {
Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.body
parseJwt()
} catch (e: ExpiredJwtException) {
log.info("Expired JWT token.")
return e.claims
Expand All @@ -77,6 +69,12 @@ class AuthToken(
val isValid: Boolean
get() = tokenClaims != null

private fun parseJwt(): Claims? = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(token)
.body

private fun createAuthToken(email: String, expiry: Date): String {
return Jwts.builder()
.setSubject(email)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ class AuthTokenProvider(
.map(::SimpleGrantedAuthority)
.toList()
return UsernamePasswordAuthenticationToken(User(claims.subject, "", authorities), authToken, authorities)
} else {
throw UnAuthorizedException(ErrorCode.TOKEN_INVALID, "올바르지 않은 Token입니다.")
}

throw UnAuthorizedException(ErrorCode.TOKEN_INVALID, "올바르지 않은 Token입니다.")
}
}
24 changes: 6 additions & 18 deletions src/main/kotlin/io/csbroker/apiserver/auth/GithubOAuth2UserInfo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,9 @@ package io.csbroker.apiserver.auth

class GithubOAuth2UserInfo(
attributes: MutableMap<String, Any>,
) : OAuth2UserInfo(attributes) {

override fun getId(): String {
return (attributes["id"] as Int).toString()
}

override fun getName(): String {
return attributes["login"] as String
}

override fun getEmail(): String {
return attributes["email"] as String
}

override fun getImageUrl(): String {
return attributes["avatar_url"] as String
}
}
) : OAuth2UserInfo(
id = (attributes["id"] as Int).toString(),
name = attributes["login"] as String,
email = attributes["email"] as String,
imageUrl = attributes["avatar_url"] as String,
)
24 changes: 6 additions & 18 deletions src/main/kotlin/io/csbroker/apiserver/auth/GoogleOAuth2UserInfo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,9 @@ package io.csbroker.apiserver.auth

class GoogleOAuth2UserInfo(
attributes: MutableMap<String, Any>,
) : OAuth2UserInfo(attributes) {

override fun getId(): String {
return attributes["sub"] as String
}

override fun getName(): String {
return attributes["name"] as String
}

override fun getEmail(): String {
return attributes["email"] as String
}

override fun getImageUrl(): String {
return attributes["picture"] as String
}
}
) : OAuth2UserInfo(
id = attributes["sub"] as String,
name = attributes["name"] as String,
email = attributes["email"] as String,
imageUrl = attributes["picture"] as String,
)
15 changes: 5 additions & 10 deletions src/main/kotlin/io/csbroker/apiserver/auth/OAuth2UserInfo.kt
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
package io.csbroker.apiserver.auth

abstract class OAuth2UserInfo(
val attributes: MutableMap<String, Any>,
) {
abstract fun getId(): String

abstract fun getName(): String

abstract fun getEmail(): String

abstract fun getImageUrl(): String
}
val id: String,
val name: String,
val email: String,
val imageUrl: String,
)
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@ class OAuth2UserInfoFactory {
return when (providerType) {
ProviderType.GOOGLE -> GoogleOAuth2UserInfo(attributes)
ProviderType.GITHUB -> GithubOAuth2UserInfo(attributes)
else -> throw OAuthProviderMissMatchException(
"프로바이더 타입이 일치하지 않습니다. ${providerType.name}",
)
else -> throw OAuthProviderMissMatchException("프로바이더 타입이 일치하지 않습니다. ${providerType.name}")
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class TokenAuthenticationFilter(
response: HttpServletResponse,
filterChain: FilterChain,
) {
val tokenStr = getAccessToken(request)
val tokenStr = request.getAccessToken()

tokenStr ?: run {
filterChain.doFilter(request, response)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ class OAuth2AuthenticationSuccessHandler(
val user = authentication.principal as OidcUser
val userInfo = OAuth2UserInfoFactory.getOauth2UserInfo(providerType, user.attributes)

return userRepository.findByEmailOrProviderId(userInfo.getEmail(), userInfo.getId())
return userRepository.findByEmailOrProviderId(userInfo.email, userInfo.id)
?: throw EntityNotFoundException(
"유저를 찾을 수 없습니다. email = [${userInfo.getEmail()}], providerId = [${userInfo.getId()}] )",
"유저를 찾을 수 없습니다. email = [${userInfo.email}], providerId = [${userInfo.id}] )",
)
}

Expand Down
17 changes: 8 additions & 9 deletions src/main/kotlin/io/csbroker/apiserver/common/util/CookieUtil.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.csbroker.apiserver.common.util

import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest
import org.springframework.util.SerializationUtils
import java.util.Base64
import javax.servlet.http.Cookie
Expand All @@ -21,19 +22,17 @@ fun addCookie(response: HttpServletResponse, name: String, value: String, maxAge
}

fun deleteCookie(request: HttpServletRequest, response: HttpServletResponse, name: String) {
request.cookies?.let {
it.find { cookie -> cookie.name == name }?.let { cookie ->
cookie.value = ""
cookie.path = "/"
cookie.maxAge = 0
response.addCookie(cookie)
}
request.cookies?.find { cookie -> cookie.name == name }?.let { cookie ->
cookie.value = ""
cookie.path = "/"
cookie.maxAge = 0
response.addCookie(cookie)
}
}

fun serialize(obj: Any): String {
fun OAuth2AuthorizationRequest.serialize(): String {
return Base64.getUrlEncoder()
.encodeToString(SerializationUtils.serialize(obj))
.encodeToString(SerializationUtils.serialize(this))
}

fun <T> deserialize(cookie: Cookie, cls: Class<T>): T {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import javax.servlet.http.HttpServletRequest
const val HEADER_AUTHORIZATION = "Authorization"
const val TOKEN_PREFIX = "Bearer "

fun getAccessToken(request: HttpServletRequest): String? {
val headerValue = request.getHeader(HEADER_AUTHORIZATION)
fun HttpServletRequest.getAccessToken(): String? {
val headerValue = this.getHeader(HEADER_AUTHORIZATION)
return if (headerValue?.startsWith(TOKEN_PREFIX) == true) headerValue.substring(TOKEN_PREFIX.length) else null
}
8 changes: 3 additions & 5 deletions src/main/kotlin/io/csbroker/apiserver/common/util/UuidUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ package io.csbroker.apiserver.common.util
import java.nio.ByteBuffer
import java.util.UUID

fun uuidAsByte(uuid: UUID?): ByteArray? {
uuid ?: return null

fun UUID.asByte(): ByteArray? {
val byteBufferWrapper = ByteBuffer.wrap(ByteArray(16))
byteBufferWrapper.putLong(uuid.mostSignificantBits)
byteBufferWrapper.putLong(uuid.leastSignificantBits)
byteBufferWrapper.putLong(this.mostSignificantBits)
byteBufferWrapper.putLong(this.leastSignificantBits)
return byteBufferWrapper.array()
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ data class PostResponseDto(
val comments: List<CommentResponseDto>,
) {
constructor(post: Post, likeCount: Long, isLiked: Boolean, comments: List<CommentResponseDto>) : this(
id = post.id!!,
id = post.id,
content = post.content,
username = post.user.username,
likeCount = likeCount,
Expand All @@ -29,7 +29,7 @@ data class CommentResponseDto(
val createdAt: LocalDateTime,
) {
constructor(comment: Comment) : this(
id = comment.id!!,
id = comment.id,
content = comment.content,
username = comment.user.username,
createdAt = comment.createdAt!!,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,10 @@ class ProblemController(
@RequestParam("page") page: Int,
@RequestParam("size") size: Int,
): ApiResponse<ProblemPageResponseDto> {
var solvedBy: String? = null

if (isSolved != null) {
solvedBy = getEmailFromSecurityContextHolder()
val solvedBy = isSolved?.let {
getEmailFromSecurityContextHolder()
?: throw UnAuthorizedException(ErrorCode.FORBIDDEN, "사용자 권한이 없습니다.")
}

val searchDto = ProblemSearchDto(tags, solvedBy, isSolved, query, type, isGradable, page, size)
val foundProblems = commonProblemService.findProblems(searchDto)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package io.csbroker.apiserver.controller.v2.problem.response

class ShortProblemDetailResponseV2Dto(
data class ShortProblemDetailResponseV2Dto(
val id: Long,
val title: String,
val tags: List<String>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ data class KeywordGradingRequestDto(
companion object {
fun createKeywordGradingRequestDto(problem: LongProblem, answer: String): KeywordGradingRequestDto {
return KeywordGradingRequestDto(
problem.id!!,
problem.id,
answer,
problem.gradingStandards.filter {
it.type == GradingStandardType.KEYWORD
}.map {
GradingKeyword(
it.id!!,
it.id,
it.content,
)
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,21 @@ data class LongProblemGradingRequestToAiServerDto(
companion object {
fun createGradingRequestDto(problem: LongProblem, answer: String): LongProblemGradingRequestToAiServerDto {
return LongProblemGradingRequestToAiServerDto(
problem.id!!,
problem.id,
answer,
problem.gradingStandards.filter {
it.type == GradingStandardType.KEYWORD
}.map {
GradingKeyword(
it.id!!,
it.id,
it.content,
)
},
problem.gradingStandards.filter {
it.type == GradingStandardType.CONTENT
}.map {
GradingContent(
it.id!!,
it.id,
it.content,
)
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ data class LongProblemGradingHistoryDto(

return LongProblemGradingHistoryDto(
gradingHistoryId,
problem.id!!,
problem.id,
problem.title,
tags,
problem.description,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ data class MultipleChoiceProblemGradingHistoryDto(

val choices = problem.choicesList.map {
ChoiceResponseDto(
it.id!!,
it.id,
it.content,
)
}

return MultipleChoiceProblemGradingHistoryDto(
gradingHistoryId,
problem.id!!,
problem.id,
problem.title,
commonDetail.tags,
problem.description,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ data class ShortProblemGradingHistoryDto(

return ShortProblemGradingHistoryDto(
gradingHistoryId,
problem.id!!,
problem.id,
problem.title,
commonDetail.tags,
problem.description,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ data class GradingStandardResponseDto(
companion object {
fun fromGradingStandard(gradingStandard: GradingStandard): GradingStandardResponseDto {
return GradingStandardResponseDto(
id = gradingStandard.id!!,
id = gradingStandard.id,
content = gradingStandard.content,
score = gradingStandard.score,
type = gradingStandard.type,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@ data class UserAnswerResponseDto(
.map { GradingStandardResponseDto.fromGradingStandard(it) }

val selectedGradingStandards = userAnswer.userAnswerGradingStandards.map {
it.gradingStandard.id!!
it.gradingStandard.id
}

return UserAnswerResponseDto(
userAnswer.id!!,
userAnswer.problem.id!!,
userAnswer.id,
userAnswer.problem.id,
userAnswer.problem.title,
userAnswer.problem.description,
userAnswer.answer,
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/io/csbroker/apiserver/model/Challenge.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Challenge(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "challenge_id")
val id: Long? = null,
val id: Long = 0,

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "problem_id")
Expand Down
2 changes: 1 addition & 1 deletion src/main/kotlin/io/csbroker/apiserver/model/ChatResult.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ChatResult(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "chat_result_id")
val id: Long? = null,
val id: Long = 0,

// 연관관계로 엮을 수 있으나, 단순 데이터 저장용이기 때문에.. 굳이 엮지 않겠음.
@Column(name = "email")
Expand Down
Loading

0 comments on commit e887d6d

Please sign in to comment.