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

πŸ„ :: (Meogo-3) user #4

Merged
merged 4 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
29 changes: 29 additions & 0 deletions src/main/kotlin/org/meogo/domain/user/domain/User.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package org.meogo.domain.user.domain

import org.meogo.global.base.BaseUUIDEntity
import java.util.UUID
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.EnumType
import javax.persistence.Enumerated

@Entity
class User(
id: UUID? = null,

@Column(nullable = false, length = 4)
val name: String,

@Column(name = "account_id", nullable = false, length = 15, unique = true)
val accountId: String,

val password: String,

@Column(name = "enrolled_school", nullable = true)
val enrolledSchool: Int? = 0,

val profile: String? = null,

@Enumerated(EnumType.STRING)
val role: UserRole
) : BaseUUIDEntity(id)
7 changes: 7 additions & 0 deletions src/main/kotlin/org/meogo/domain/user/domain/UserRole.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.meogo.domain.user.domain

enum class UserRole {
MANAGER,
USER,
ADMIN
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.meogo.domain.user.exception

import org.meogo.global.error.exception.ErrorCode
import org.meogo.global.error.exception.MeogoException

object UserNotFoundException : MeogoException(
ErrorCode.USER_NOT_FOUND
)
21 changes: 21 additions & 0 deletions src/main/kotlin/org/meogo/domain/user/facade/UserFacade.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package org.meogo.domain.user.facade

import org.meogo.domain.user.domain.User
import org.meogo.domain.user.exception.UserNotFoundException
import org.meogo.domain.user.repository.UserRepository
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Component

@Component
class UserFacade(
private val userRepository: UserRepository
) {

fun currentUser(): User {
val accountId = SecurityContextHolder.getContext().authentication.name
return getUserByAccountId(accountId)
}
meltapplee marked this conversation as resolved.
Show resolved Hide resolved

fun getUserByAccountId(accountId: String): User =
userRepository.findByAccountId(accountId) ?: throw UserNotFoundException
}
13 changes: 13 additions & 0 deletions src/main/kotlin/org/meogo/domain/user/repository/UserRepository.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.meogo.domain.user.repository

import org.meogo.domain.user.domain.User
import org.springframework.data.repository.Repository
import java.util.UUID

interface UserRepository : Repository<User, UUID> {
fun save(entity: User): User

fun findByAccountId(accountId: String): User?

fun existsByAccountId(accountId: String): Boolean
}
2 changes: 2 additions & 0 deletions src/main/kotlin/org/meogo/global/error/exception/ErrorCode.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ enum class ErrorCode(
INVALID_TOKEN(401, "Invalid Token"),
EXPIRED_TOKEN(401, "Expired Token"),

USER_NOT_FOUND(404, "User not found"),

// Internal Server Error
INTERNAL_SERVER_ERROR(500, "Internal Server Error")
}
41 changes: 19 additions & 22 deletions src/main/kotlin/org/meogo/global/jwt/JwtTokenProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import org.meogo.global.jwt.entity.repository.RefreshTokenRepository
import org.meogo.global.jwt.exception.ExpiredTokenException
import org.meogo.global.jwt.exception.InvalidJwtException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import java.util.Date
import javax.servlet.http.HttpServletRequest
Expand All @@ -29,16 +28,17 @@ class JwtTokenProvider(
}

fun getToken(name: String): TokenResponse {
val accessToken: String = generateAccessToken(name, ACCESS_KEY, jwtProperties.accessExp)
val refreshToken: String = generateRefreshToken(REFRESH_KEY, jwtProperties.refreshExp)
val accessToken = generateAccessToken(name, ACCESS_KEY, jwtProperties.accessExp)
val refreshToken = generateRefreshToken(REFRESH_KEY, jwtProperties.refreshExp)
refreshTokenRepository.save(
RefreshToken(name, refreshToken, jwtProperties.refreshExp)
)
return TokenResponse(accessToken = accessToken, refreshToken = refreshToken)
return TokenResponse(accessToken, refreshToken)
}

private fun generateAccessToken(name: String, type: String, expiration: Long): String {
return Jwts.builder().signWith(SignatureAlgorithm.HS256, jwtProperties.secretKey)
return Jwts.builder()
.signWith(SignatureAlgorithm.HS256, jwtProperties.secretKey)
.setSubject(name)
.setHeaderParam("type", type)
.setIssuedAt(Date())
Expand All @@ -47,48 +47,45 @@ class JwtTokenProvider(
}

private fun generateRefreshToken(type: String, ttl: Long): String {
return Jwts.builder().signWith(SignatureAlgorithm.HS256, jwtProperties.secretKey)
return Jwts.builder()
.signWith(SignatureAlgorithm.HS256, jwtProperties.secretKey)
.setHeaderParam("type", type)
.setIssuedAt(Date())
.setExpiration(Date(System.currentTimeMillis() + ttl * 1000))
.compact()
}

fun resolveToken(request: HttpServletRequest): String? {
val bearer: String? = request.getHeader("Authorization")

val bearer = request.getHeader("Authorization")
return parseToken(bearer)
}

fun parseToken(bearerToken: String?): String? {
return if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
return bearerToken.replace("Bearer ", "")
bearerToken.removePrefix("Bearer ")
} else {
null
}
}

fun authorization(token: String): UsernamePasswordAuthenticationToken {
return token.let {
val userDetails: UserDetails = authDetailsService.loadUserByUsername(getTokenSubject(token))
return UsernamePasswordAuthenticationToken(userDetails, "", userDetails.authorities)
}
val userDetails = authDetailsService.loadUserByUsername(getTokenSubject(token))
return UsernamePasswordAuthenticationToken(userDetails, "", userDetails.authorities)
}

private fun getTokenSubject(subject: String): String {
return getTokenBody(subject).subject
private fun getTokenSubject(token: String): String {
return getTokenBody(token).subject
}

private fun getTokenBody(token: String?): Claims {
return try {
Jwts.parser().setSigningKey(jwtProperties.secretKey)
.parseClaimsJws(token).body
Jwts.parser().setSigningKey(jwtProperties.secretKey).parseClaimsJws(token).body
} catch (e: ExpiredJwtException) {
throw ExpiredTokenException
} catch (e: InvalidClaimException) {
throw InvalidJwtException
} catch (e: Exception) {
when (e) {
is ExpiredJwtException -> throw ExpiredTokenException
is InvalidClaimException -> throw InvalidJwtException
else -> throw InvalidJwtException
}
throw InvalidJwtException
meltapplee marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Loading