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

[refactor] RedisService 생성 #135

Merged
merged 2 commits into from
Aug 19, 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.psr.psr.global.config

import com.psr.psr.global.jwt.JwtFilter
import com.psr.psr.global.jwt.utils.JwtUtils
import com.psr.psr.user.service.RedisService
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.security.config.annotation.SecurityConfigurerAdapter
Expand All @@ -10,12 +11,12 @@ import org.springframework.security.web.DefaultSecurityFilterChain
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

@Configuration
class JwtSecurityConfig (private val jwtUtils: JwtUtils, private val redisTemplate: RedisTemplate<String, String>): SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> () {
class JwtSecurityConfig (private val jwtUtils: JwtUtils, private val redisService: RedisService): SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> () {
/**
* jwtFilter를 SecurityFilter 앞에 추가
*/
override fun configure(builder: HttpSecurity?) {
val jwtFilter = JwtFilter(jwtUtils, redisTemplate)
val jwtFilter = JwtFilter(jwtUtils, redisService)
builder!!.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter::class.java)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.psr.psr.global.config
import com.psr.psr.global.jwt.exception.JwtAccessDeniedHandler
import com.psr.psr.global.jwt.exception.JwtAuthenticationEntryPoint
import com.psr.psr.global.jwt.utils.JwtUtils
import com.psr.psr.user.service.RedisService
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.core.RedisTemplate
Expand All @@ -18,7 +19,7 @@ import org.springframework.security.web.util.matcher.AntPathRequestMatcher
@EnableWebSecurity
class WebSecurityConfig(
private val jwtUtils: JwtUtils,
private val redisTemplate: RedisTemplate<String, String>,
private val redisService: RedisService,
private val jwtAuthenticationEntryPoint: JwtAuthenticationEntryPoint,
private val jwtAccessDeniedHandler: JwtAccessDeniedHandler
) {
Expand Down Expand Up @@ -54,7 +55,7 @@ class WebSecurityConfig(
c.requestMatchers("/users/password").permitAll()
c.anyRequest().authenticated()
}
.apply(JwtSecurityConfig(jwtUtils, redisTemplate))
.apply(JwtSecurityConfig(jwtUtils, redisService))

return http.build()
}
Expand Down
5 changes: 3 additions & 2 deletions src/main/kotlin/com/psr/psr/global/jwt/JwtFilter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import com.psr.psr.global.dto.BaseResponse
import com.psr.psr.global.exception.BaseException
import com.psr.psr.global.exception.BaseResponseCode
import com.psr.psr.global.jwt.utils.JwtUtils
import com.psr.psr.user.service.RedisService
import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
Expand All @@ -15,7 +16,7 @@ import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils
import org.springframework.web.filter.OncePerRequestFilter

class JwtFilter(private val jwtUtils: JwtUtils, private val redisTemplate: RedisTemplate<String, String>) : OncePerRequestFilter() {
class JwtFilter(private val jwtUtils: JwtUtils, private val redisService: RedisService) : OncePerRequestFilter() {

override fun doFilterInternal(
request: HttpServletRequest,
Expand All @@ -28,7 +29,7 @@ class JwtFilter(private val jwtUtils: JwtUtils, private val redisTemplate: Redis
// 유효한 token 인지 확인
if(StringUtils.hasText(token) && jwtUtils.validateToken(token)){
// 이미 blacklist 가 된 토큰인지 아닌지 확인
if(!ObjectUtils.isEmpty(redisTemplate.opsForValue().get(token!!))){
if(!ObjectUtils.isEmpty(redisService.getValue(token!!))){
throw BaseException(BaseResponseCode.BLACKLIST_TOKEN)
}
val authentication = jwtUtils.getAuthentication(token)
Expand Down
35 changes: 6 additions & 29 deletions src/main/kotlin/com/psr/psr/global/jwt/utils/JwtUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,18 @@ import com.psr.psr.global.exception.BaseResponseCode
import com.psr.psr.global.jwt.UserDetailsServiceImpl
import com.psr.psr.global.jwt.dto.TokenDto
import com.psr.psr.user.entity.Type
import com.psr.psr.user.service.RedisService
import io.jsonwebtoken.*
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.security.Keys
import io.jsonwebtoken.security.SecurityException
import mu.KotlinLogging
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import org.springframework.util.ObjectUtils
import java.security.Key
import java.time.Duration
import java.util.*
Expand All @@ -31,14 +30,13 @@ import java.util.stream.Collectors
class JwtUtils(
private val userDetailsService: UserDetailsServiceImpl,
@Value("\${jwt.secret}") private val secret: String,
private val redisTemplate: RedisTemplate<String, String>
private val redisService: RedisService
) {
val logger = KotlinLogging.logger {}

// private final val ACCESS_TOKEN_EXPIRE_TIME: Long = 1000L * 60 * 30 // 30 분
private final val ACCESS_TOKEN_EXPIRE_TIME: Long = 1000L * 60 * 60 * 24 * 14 // 2주일 (임시)
private final val REFRESH_TOKEN_EXPIRE_TIME: Long = 1000L * 60 * 60 * 24 * 7 // 일주일
private final val SMS_KEY_EXPIRE_TIME: Long = 1000L * 60 * 6 // 2분

private val keyBytes = Decoders.BASE64.decode(secret)
val key: Key = Keys.hmacShaKeyFor(keyBytes)
Expand All @@ -63,8 +61,8 @@ class JwtUtils(
.setExpiration(Date(now + REFRESH_TOKEN_EXPIRE_TIME))
.signWith(key, SignatureAlgorithm.HS512)
.compact()
redisTemplate.opsForValue().set(authentication.name, refreshToken, Duration.ofMillis(REFRESH_TOKEN_EXPIRE_TIME))

redisService.setValue(authentication.name, refreshToken, Duration.ofMillis(REFRESH_TOKEN_EXPIRE_TIME))
return TokenDto(BEARER_PREFIX + accessToken, BEARER_PREFIX + refreshToken, type.value)
}

Expand Down Expand Up @@ -116,8 +114,7 @@ class JwtUtils(
fun expireToken(token: String, status: String){
val accessToken = token.replace(BEARER_PREFIX, "")
val expiration = getExpiration(accessToken)
redisTemplate.opsForValue().set(accessToken, status, expiration, TimeUnit.MILLISECONDS)

redisService.setValue(accessToken, status, expiration, TimeUnit.MILLISECONDS)
}

/**
Expand All @@ -133,34 +130,14 @@ class JwtUtils(
* refresh token 삭제
*/
fun deleteRefreshToken(userId: Long) {
if(redisTemplate.opsForValue().get(userId.toString()) != null) redisTemplate.delete(userId.toString())
if(redisService.getValue(userId.toString()) != null) redisService.deleteValue(userId.toString())
}

/**
* check Token in Redis DB
*/
fun validateRefreshToken(userId: Long, refreshToken: String) {
val redisToken = redisTemplate.opsForValue().get(userId.toString())
val redisToken = redisService.getValue(userId.toString())
if(redisToken == null || redisToken != refreshToken) throw BaseException(BaseResponseCode.INVALID_TOKEN)
}

/**
* 휴대폰 smsKey 만료시간
*/
fun createSmsKey(phone: String, smsKey: String){
// 재발급을 받은 경우 기존 인증코드 삭제
if (redisTemplate.opsForValue().get(phone) != null) redisTemplate.delete(phone)
// 인증코드 생성
redisTemplate.opsForValue().set(phone, smsKey, Duration.ofMillis(SMS_KEY_EXPIRE_TIME))
}

/**
* 휴대폰 인증코드 정보 불러오기
*/
fun getSmsKey(phone: String) : String {
val key = redisTemplate.opsForValue().get(phone)
// sms key 가 없거나 만료된 경우 예외처리
if(ObjectUtils.isEmpty(key) || key == null) throw BaseException(BaseResponseCode.BLACKLIST_PHONE)
return key
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class UserAssembler {
* toDto
*/
fun toMyPageInfoRes(user: User) : MyPageInfoRes {
return MyPageInfoRes(user.email, user.imgUrl, user.type.value, user.phone)
return MyPageInfoRes(user.email, user.imgUrl, user.type.value, user.phone, user.nickname)
}

fun toProfileRes(user: User) : ProfileRes {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ data class MyPageInfoRes(
val imgUrl: String ?= null,
val type: String,
val phone: String,
val nickname: String,
)
32 changes: 32 additions & 0 deletions src/main/kotlin/com/psr/psr/user/service/RedisService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.psr.psr.user.service

import io.netty.util.Timeout
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Duration
import java.util.concurrent.TimeUnit

@Service
@Transactional(readOnly = true)
class RedisService (
private val redisTemplate: RedisTemplate<String, String>
){

fun setValue(key: String, value: String, time: Duration){
redisTemplate.opsForValue().set(key, value, time)
}

fun setValue(key: String, value: String, exp: Long, time: TimeUnit){
redisTemplate.opsForValue().set(key, value, exp, time)
}

fun getValue(key : String) : String? {
return redisTemplate.opsForValue().get(key)
}

@Transactional
fun deleteValue(key : String) {
redisTemplate.delete(key)
}
}
9 changes: 7 additions & 2 deletions src/main/kotlin/com/psr/psr/user/service/UserService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import com.psr.psr.global.Constant.UserPhone.UserPhone.TIMESTAMP_HEADER
import com.psr.psr.global.Constant.UserPhone.UserPhone.UTF_8
import com.psr.psr.global.Constant.UserStatus.UserStatus.ACTIVE_STATUS
import com.psr.psr.global.exception.BaseException
import com.psr.psr.global.exception.BaseResponseCode
import com.psr.psr.global.exception.BaseResponseCode.*
import com.psr.psr.global.jwt.dto.TokenDto
import com.psr.psr.global.jwt.utils.JwtUtils
Expand All @@ -33,6 +34,7 @@ import com.psr.psr.user.entity.User
import com.psr.psr.user.repository.BusinessInfoRepository
import com.psr.psr.user.repository.UserInterestRepository
import com.psr.psr.user.repository.UserRepository
import com.psr.psr.user.utils.SmsUtils
import jakarta.servlet.http.HttpServletRequest
import org.apache.tomcat.util.codec.binary.Base64
import org.springframework.beans.factory.annotation.Value
Expand All @@ -43,8 +45,10 @@ import org.springframework.security.config.annotation.authentication.builders.Au
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.ObjectUtils
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.util.DefaultUriBuilderFactory
import java.time.Duration
import java.util.stream.Collectors
import javax.crypto.Mac

Expand All @@ -58,6 +62,7 @@ class UserService(
private val businessInfoRepository: BusinessInfoRepository,
private val authenticationManagerBuilder: AuthenticationManagerBuilder,
private val jwtUtils: JwtUtils,
private val smsUtils: SmsUtils,
private val passwordEncoder: PasswordEncoder,
@Value("\${eid.key}")
private val serviceKey: String,
Expand Down Expand Up @@ -290,12 +295,12 @@ class UserService(
}
.bodyToMono(String::class.java)
.block()
jwtUtils.createSmsKey(validPhoneReq.phone, smsKey)
smsUtils.createSmsKey(validPhoneReq.phone, smsKey)
}

// 휴대폰 인증번호 조회
fun checkValidSmsKey(phone: String, smsKey: String) {
val sms = jwtUtils.getSmsKey(phone)
val sms = smsUtils.getSmsKey(phone)
// 인증코드가 같지 않은 경우 예외처리 발생
if(sms != smsKey) throw BaseException(INVALID_SMS_KEY)
}
Expand Down
35 changes: 35 additions & 0 deletions src/main/kotlin/com/psr/psr/user/utils/SmsUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.psr.psr.user.utils

import com.psr.psr.global.exception.BaseException
import com.psr.psr.global.exception.BaseResponseCode
import com.psr.psr.user.service.RedisService
import org.springframework.stereotype.Component
import org.springframework.util.ObjectUtils
import java.time.Duration

@Component
class SmsUtils (
private val redisService: RedisService
){
private final val SMS_KEY_EXPIRE_TIME: Long = 1000L * 60 * 5 // 5분

/**
* 휴대폰 smsKey 만료시간
*/
fun createSmsKey(phone: String, smsKey: String){
// 재발급을 받은 경우 기존 인증코드 삭제
if (redisService.getValue(phone) != null) redisService.deleteValue(phone)
// 인증코드 생성
redisService.setValue(phone, smsKey, Duration.ofMillis(SMS_KEY_EXPIRE_TIME))
}

/**
* 휴대폰 인증코드 정보 불러오기
*/
fun getSmsKey(phone: String) : String {
val key = redisService.getValue(phone)
// sms key 가 없거나 만료된 경우 예외처리
if(ObjectUtils.isEmpty(key) || key == null) throw BaseException(BaseResponseCode.BLACKLIST_PHONE)
return key
}
}
Loading