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

Feature/19 ๐Ÿš€ [feature] redis ์„ค์ • ๋ฐ ๋ฆฌํ”„๋ ˆ์‰ฌ ํ† ํฐ ๊ด€๋ฆฌ ์ถ”๊ฐ€ #35

Merged
merged 4 commits into from
Sep 26, 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
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-redis:2.3.1.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.springfox:springfox-swagger2:2.9.2'
Expand Down
255 changes: 0 additions & 255 deletions logs/info.log

Large diffs are not rendered by default.

6 changes: 5 additions & 1 deletion src/main/java/briefing/exception/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,12 @@ public enum ErrorCode {
FEIGN_METHOD_NOT_ALLOWED(BAD_REQUEST,"FEIGN_400_7" , "Feign server method not allowed"),
FEIGN_SERVER_ERROR(BAD_REQUEST,"FEIGN_500" , "Feign server error"),


// member ๊ด€๋ จ ์—๋Ÿฌ

MEMBER_NOT_FOUND(BAD_REQUEST, "MEMBER_400_1", "์‚ฌ์šฉ์ž๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค"),

// member ์—๋Ÿฌ
MEMBER_NOT_FOUND(NOT_FOUND, "MEMBER_001", "์กด์žฌํ•˜์ง€ ์•Š๋Š” ์‚ฌ์šฉ์ž์ž…๋‹ˆ๋‹ค."),


// scrap ์—๋Ÿฌ
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/briefing/exception/handler/MemberException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package briefing.exception.handler;

import briefing.exception.ErrorCode;
import briefing.exception.GeneralException;

public class MemberException extends GeneralException {
public MemberException(ErrorCode errorCode){
super(errorCode);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package briefing.exception.handler;

import briefing.exception.ErrorCode;
import briefing.exception.GeneralException;

public class RefreshTokenException extends GeneralException {
public RefreshTokenException(ErrorCode errorCode){
super(errorCode);
}
}
25 changes: 22 additions & 3 deletions src/main/java/briefing/member/api/MemberApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@
import briefing.member.application.dto.MemberResponse;
import briefing.member.domain.Member;
import briefing.member.domain.SocialType;
import briefing.redis.service.RedisService;
import briefing.security.provider.TokenProvider;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.UUID;

@Tag(name = "02-Member \uD83D\uDC64",description = "์‚ฌ์šฉ์ž ๊ด€๋ จ API")
@RestController
@RequestMapping("/members")
Expand All @@ -21,16 +27,29 @@ public class MemberApi {
private final MemberQueryService memberQueryService;
private final MemberCommandService memberCommandService;

private final TokenProvider tokenProvider;

private final RedisService redisService;

@Operation(summary = "02-01 Member\uD83D\uDC64 ์†Œ์…œ ๋กœ๊ทธ์ธ #FRAME", description = "๊ตฌ๊ธ€, ์• ํ”Œ ์†Œ์…œ๋กœ๊ทธ์ธ API์ž…๋‹ˆ๋‹ค.")
@PostMapping("/auth/{socialType}")
public CommonResponse<MemberResponse.LoginDTO> login(
@Parameter(description = "์†Œ์…œ๋กœ๊ทธ์ธ ์ข…๋ฅ˜", example = "google") @PathVariable final SocialType socialType,
@Parameter(description = "์†Œ์…œ๋กœ๊ทธ์ธ ์ข…๋ฅ˜", example = "google") @PathVariable final SocialType socialType,
@RequestBody final MemberRequest.LoginDTO request
) {
Member member = memberCommandService.login(socialType, request);
// TODO - TokenProvider์—์„œ ๋ฐœ๊ธ‰ํ•ด์ฃผ๋„๋ก ๋ณ€๊ฒฝ
String accessToken = "";
String refreshToken = "";
String accessToken = tokenProvider.createAccessToken(member.getId(),member.getSocialType().toString() ,member.getSocialId(), Arrays.asList(new SimpleGrantedAuthority("USER")));
String refreshToken = redisService.generateRefreshToken(member.getSocialId(),member.getSocialType());
return CommonResponse.onSuccess(MemberConverter.toLoginDTO(member, accessToken, refreshToken));
}

@Operation(summary = "ํ† ํฐ ์ž˜ ๋ฐœ๊ธ‰๋˜๋‚˜ ํ…Œ์ŠคํŠธ์šฉAPI", description = "ํ…Œ์ŠคํŠธ ํ›„ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค")
@GetMapping("/auth/test")
public CommonResponse<MemberResponse.LoginDTO> testGenerateToken(){
Member member = memberQueryService.findMember(1L);
String accessToken = tokenProvider.createAccessToken(member.getId(), member.getSocialType().toString() ,member.getSocialId(), Arrays.asList(new SimpleGrantedAuthority(member.getRole().name())));
String refreshToken = redisService.generateRefreshToken(member.getSocialId(), member.getSocialType());
return CommonResponse.onSuccess(MemberConverter.toLoginDTO(member,accessToken, refreshToken));
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package briefing.member.application;

import briefing.member.domain.Member;
import briefing.member.domain.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand All @@ -11,4 +12,7 @@
public class MemberQueryService {
private final MemberRepository memberRepository;

public Member findMember(Long memberId){
return memberRepository.findById(memberId).get();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,9 @@ public class MemberRequest {
public static class LoginDTO {
private String identityToken;
}

@Getter
public static class ReissueDTO{
private String refreshToken;
}
}
22 changes: 22 additions & 0 deletions src/main/java/briefing/redis/domain/RefreshToken.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package briefing.redis.domain;

import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;

import java.time.LocalDateTime;

@RedisHash(value = "refreshToken_Breifing", timeToLive = 1800000)
@Builder
@Getter
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class RefreshToken {

@Id
private Long memberId;

private String token;

private LocalDateTime expireTime;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package briefing.redis.repository;

import briefing.redis.domain.RefreshToken;
import org.springframework.data.repository.CrudRepository;

import java.util.Optional;

public interface RefreshTokenRepository extends CrudRepository<RefreshToken, Long> {

Optional<RefreshToken> findByToken(String token);
}
15 changes: 15 additions & 0 deletions src/main/java/briefing/redis/service/RedisService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package briefing.redis.service;

import briefing.member.application.dto.MemberRequest;
import briefing.member.domain.SocialType;
import briefing.redis.domain.RefreshToken;

public interface RedisService {

String generateRefreshToken(String socialId, SocialType socialType);

// accessToken ๋งŒ๋ฃŒ ์‹œ ๋ฐœ๊ธ‰ ํ˜น์€ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜
String reGenerateRefreshToken(MemberRequest.ReissueDTO request);

void deleteRefreshToken(String refreshToken);
}
91 changes: 91 additions & 0 deletions src/main/java/briefing/redis/service/RedisServiceImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package briefing.redis.service;

import briefing.exception.ErrorCode;
import briefing.exception.handler.MemberException;
import briefing.exception.handler.RefreshTokenException;
import briefing.member.application.dto.MemberRequest;
import briefing.member.domain.Member;
import briefing.member.domain.SocialType;
import briefing.member.domain.repository.MemberRepository;
import briefing.redis.domain.RefreshToken;
import briefing.redis.repository.RefreshTokenRepository;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class RedisServiceImpl implements RedisService{

Logger logger =LoggerFactory.getLogger(RedisServiceImpl.class);

private final MemberRepository memberRepository;

private final RefreshTokenRepository refreshTokenRepository;

@Override
@Transactional
public String generateRefreshToken(String socialId, SocialType socialType) {
Member member = memberRepository.findBySocialIdAndSocialType(socialId, socialType).orElseThrow(() -> new RefreshTokenException(ErrorCode.MEMBER_NOT_FOUND));

// ์ด ๋ถ€๋ถ„ ๊ดœ์ฐฎ์€์ง€ ๋ฆฌ๋ทฐ
String token = UUID.randomUUID().toString();

Long memberId = member.getId();

LocalDateTime currentTime =LocalDateTime.now();

LocalDateTime expireTime = currentTime.plus(1000, ChronoUnit.MINUTES);

return refreshTokenRepository.save(
RefreshToken.builder()
.memberId(memberId)
.token(token)
.expireTime(expireTime).build()
).getToken();
}

@Override
public String reGenerateRefreshToken(MemberRequest.ReissueDTO request) {
if(request.getRefreshToken() == null)
throw new MemberException(ErrorCode.INVALID_TOKEN_EXCEPTION);
RefreshToken findRefreshToken = refreshTokenRepository.findByToken(request.getRefreshToken()).orElseThrow(() -> new RefreshTokenException(ErrorCode.INVALID_TOKEN_EXCEPTION));
LocalDateTime expireTime = findRefreshToken.getExpireTime();
LocalDateTime current = LocalDateTime.now();
// ํ…Œ์ŠคํŠธ์šฉ, ์‹ค์ œ๋กœ๋Š” ํ˜„์žฌ ์‹œ๊ฐ„ + accessToken ๋งŒ๋ฃŒ ์‹œ๊ฐ„
LocalDateTime expireDeadLine = current.plusSeconds(20);

Member member = memberRepository.findById(findRefreshToken.getMemberId()).orElseThrow(() -> new RefreshTokenException(ErrorCode.MEMBER_NOT_FOUND));

if(current.isAfter(expireTime)) {
logger.error("์ด๋ฏธ ๋งŒ๋ฃŒ๋œ ๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ ๋ฐœ๊ฒฌ");
throw new RefreshTokenException(ErrorCode.RELOGIN_EXCEPTION);
}

// ์ƒˆ๋กœ ๋ฐœ๊ธ‰ํ•  accessToken๋ณด๋‹ค refreshToken์ด ๋จผ์ € ๋งŒ๋ฃŒ ๋  ๊ฒฝ์šฐ์ธ๊ฐ€?
if(expireTime.isAfter(expireDeadLine)) {
logger.info("๊ธฐ์กด ๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ ๋ฐœ๊ธ‰");
return findRefreshToken.getToken();
}
else {
logger.info("accessToken๋ณด๋‹ค ๋จผ์ € ๋งŒ๋ฃŒ๋  ์˜ˆ์ •์ธ ๋ฆฌํ”„๋ ˆ์‹œ ํ† ํฐ ๋ฐœ๊ฒฌ");
deleteRefreshToken(request.getRefreshToken());
return generateRefreshToken(member.getSocialId(), member.getSocialType());
}
}

@Override
public void deleteRefreshToken(String refreshToken) {
Optional<RefreshToken> target = refreshTokenRepository.findByToken(refreshToken);
if(target.isPresent())
refreshTokenRepository.delete(target.get());
}
}
4 changes: 4 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ spring:
config:
activate:
on-profile: default
data:
host: 43.201.249.220
port : 6379
password: breifing
jwt:
header: Authorization
# dev server
Expand Down
Loading