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

issue/39 ♻️ Refactor : 토큰 발급 수정 #40

Merged
merged 1 commit into from
Oct 3, 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: 2 additions & 0 deletions src/main/java/briefing/BriefingApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignAutoConfiguration;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;

@SpringBootApplication
@EnableFeignClients
@EnableRedisRepositories
@ImportAutoConfiguration({FeignAutoConfiguration.class})
public class BriefingApplication {

Expand Down
29 changes: 21 additions & 8 deletions src/main/java/briefing/member/api/MemberApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,25 @@
import briefing.member.application.dto.MemberResponse;
import briefing.member.domain.Member;
import briefing.member.domain.SocialType;
import briefing.redis.domain.RefreshToken;
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 jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "02-Member \uD83D\uDC64",description = "사용자 관련 API")
@RestController
@Validated
@RequestMapping("/members")
@RequiredArgsConstructor
public class MemberApi {
Expand All @@ -31,6 +36,15 @@ public class MemberApi {

private final RedisService redisService;

@Operation(summary = "Member\uD83D\uDC64 토큰 잘 발급되나 테스트용API", description = "테스트 용")
@GetMapping("/auth/test")
public CommonResponse<MemberResponse.LoginDTO> testGenerateToken(){
Member member = memberQueryService.testForTokenApi();
String accessToken = tokenProvider.createAccessToken(member.getId(), member.getSocialType().toString() ,member.getSocialId(), Arrays.asList(new SimpleGrantedAuthority(member.getRole().name())));
RefreshToken refreshToken = redisService.generateRefreshToken(member.getSocialId(), member.getSocialType());
return CommonResponse.onSuccess(MemberConverter.toLoginDTO(member,accessToken, refreshToken.getToken()));
}

@Operation(summary = "02-01 Member\uD83D\uDC64 소셜 로그인 #FRAME", description = "구글, 애플 소셜로그인 API입니다.")
@PostMapping("/auth/{socialType}")
public CommonResponse<MemberResponse.LoginDTO> login(
Expand All @@ -40,16 +54,15 @@ public CommonResponse<MemberResponse.LoginDTO> login(
Member member = memberCommandService.login(socialType, request);
// TODO - TokenProvider에서 발급해주도록 변경
String accessToken = tokenProvider.createAccessToken(member.getId(),member.getSocialType().toString() ,member.getSocialId(), Arrays.asList(new SimpleGrantedAuthority("USER")));
String refreshToken = redisService.generateRefreshToken(member.getSocialId(),member.getSocialType());
String refreshToken = redisService.generateRefreshToken(member.getSocialId(),member.getSocialType()).getToken();
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));
@PostMapping("/auth/token")
public CommonResponse<MemberResponse.ReIssueTokenDTO> reissueToken(@Valid @RequestBody MemberRequest.ReissueDTO request){
RefreshToken refreshToken = redisService.reGenerateRefreshToken(request);
Member parsedMember = memberCommandService.parseRefreshToken(refreshToken);
String accessToken = tokenProvider.createAccessToken(parsedMember.getId(),parsedMember.getSocialType().toString(), parsedMember.getSocialId(), List.of(new SimpleGrantedAuthority(parsedMember.getRole().toString())));
return CommonResponse.onSuccess(MemberConverter.toReIssueTokenDTO(accessToken,refreshToken.getToken()));
}
}
7 changes: 7 additions & 0 deletions src/main/java/briefing/member/api/MemberConverter.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,11 @@ public static Member toMember(String appleSocialId) {
.status(MemberStatus.ACTIVE)
.build();
}

public static MemberResponse.ReIssueTokenDTO toReIssueTokenDTO(String accessToken, String refreshToken){
return MemberResponse.ReIssueTokenDTO.builder()
.accessToken(accessToken)
.refreshToken(refreshToken)
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import briefing.exception.ErrorCode;
import briefing.exception.handler.AppleOAuthException;
import briefing.exception.handler.MemberException;
import briefing.feign.oauth.apple.client.AppleOauth2Client;
import briefing.feign.oauth.apple.dto.ApplePublicKey;
import briefing.feign.oauth.apple.dto.ApplePublicKeyList;
Expand All @@ -14,6 +15,7 @@
import briefing.member.domain.MemberStatus;
import briefing.member.domain.SocialType;
import briefing.member.domain.repository.MemberRepository;
import briefing.redis.domain.RefreshToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -127,4 +129,8 @@ private PublicKey getPublicKey(ApplePublicKey applePublicKeyDTO) {
throw new AppleOAuthException(ErrorCode.FAIL_TO_MAKE_APPLE_PUBLIC_KEY);
}
}

public Member parseRefreshToken(RefreshToken refreshToken){
return memberRepository.findById(refreshToken.getMemberId()).orElseThrow(() -> new MemberException(ErrorCode.MEMBER_NOT_FOUND));
}
}
10 changes: 10 additions & 0 deletions src/main/java/briefing/member/application/MemberQueryService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package briefing.member.application;

import briefing.member.domain.Member;
import briefing.member.domain.MemberRole;
import briefing.member.domain.SocialType;
import briefing.member.domain.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
Expand All @@ -15,4 +17,12 @@ public class MemberQueryService {
public Member findMember(Long memberId){
return memberRepository.findById(memberId).get();
}

@Transactional
public Member testForTokenApi(){
return memberRepository.findFirstByOrderByCreatedAt().orElseGet(()->
memberRepository.save(Member.builder().nickName(",,,!,1").socialId("1234567").socialType(SocialType.GOOGLE).role(MemberRole.ROLE_USER)
.build())
);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package briefing.member.application.dto;

import jakarta.validation.constraints.NotBlank;
import lombok.Getter;

public class MemberRequest {
Expand All @@ -11,6 +12,7 @@ public static class LoginDTO {

@Getter
public static class ReissueDTO{
@NotBlank
private String refreshToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,12 @@ public static class LoginDTO {
private String accessToken;
private String refreshToken;
}

@Builder @Getter
@NoArgsConstructor
@AllArgsConstructor
public static class ReIssueTokenDTO{
private String accessToken;
private String refreshToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@

public interface MemberRepository extends JpaRepository<Member, Long> {
Optional<Member> findBySocialIdAndSocialType(String socialId, SocialType socialType);

Optional<Member> findFirstByOrderByCreatedAt();
}
5 changes: 3 additions & 2 deletions src/main/java/briefing/redis/service/RedisService.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
package briefing.redis.service;

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

public interface RedisService {

String generateRefreshToken(String socialId, SocialType socialType);
RefreshToken generateRefreshToken(String socialId, SocialType socialType);

// accessToken 만료 시 발급 혹은 그대로 반환
String reGenerateRefreshToken(MemberRequest.ReissueDTO request);
RefreshToken reGenerateRefreshToken(MemberRequest.ReissueDTO request);

void deleteRefreshToken(String refreshToken);
}
8 changes: 4 additions & 4 deletions src/main/java/briefing/redis/service/RedisServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class RedisServiceImpl implements RedisService{

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

// 이 부분 괜찮은지 리뷰
Expand All @@ -50,11 +50,11 @@ public String generateRefreshToken(String socialId, SocialType socialType) {
.memberId(memberId)
.token(token)
.expireTime(expireTime).build()
).getToken();
);
}

@Override
public String reGenerateRefreshToken(MemberRequest.ReissueDTO request) {
public RefreshToken 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));
Expand All @@ -73,7 +73,7 @@ public String reGenerateRefreshToken(MemberRequest.ReissueDTO request) {
// 새로 발급할 accessToken보다 refreshToken이 먼저 만료 될 경우인가?
if(expireTime.isAfter(expireDeadLine)) {
logger.info("기존 리프레시 토큰 발급");
return findRefreshToken.getToken();
return findRefreshToken;
}
else {
logger.info("accessToken보다 먼저 만료될 예정인 리프레시 토큰 발견");
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ spring:
sql:
init:
mode: never
redis:
briefing-redis-ro.0ot2cs.ng.0001.apn2.cache.amazonaws.com
jpa:
properties:
hibernate:
Expand Down
79 changes: 0 additions & 79 deletions src/main/resources/logback-spring.xml

This file was deleted.