Skip to content

Commit

Permalink
refactor: Auth 관련 코드 리팩토링
Browse files Browse the repository at this point in the history
- MemberRole이 Member일때 서비스 이용 가능하게 SecurityConfig 코드 수정
- AuthService에서 RefreshTokenEntity 관련 코드 삽입 및 수정
  • Loading branch information
yunhacandy committed Aug 13, 2024
1 parent 2599f70 commit 2988ad7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 18 deletions.
54 changes: 39 additions & 15 deletions src/main/java/cotato/growingpain/auth/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,15 +50,19 @@ public Token createLoginInfo(LoginRequest request) {
// 기존 회원이 존재하면 로그인 처리
Member member = existingMember.get();
if (!bCryptPasswordEncoder.matches(request.password(), member.getPassword())) {
throw new IllegalArgumentException("이메일 또는 비밀번호가 올바르지 않습니다.");
throw new AppException(ErrorCode.INVALID_PASSWORD);
}

if (member.getMemberRole() == MemberRole.PENDING) {
return jwtTokenProvider.createToken(member.getId(), request.email(), MemberRole.PENDING.getDescription());
}
String role = (member.getMemberRole() == MemberRole.PENDING)
? MemberRole.PENDING.getDescription()
: MemberRole.MEMBER.getDescription();

Token token = jwtTokenProvider.createToken(member.getId(), member.getEmail(), role);

// 토큰 생성 및 반환
return jwtTokenProvider.createToken(member.getId(), request.email(), MemberRole.MEMBER.getDescription());
// RefreshTokenEntity 저장 또는 업데이트
saveOrUpdateRefreshToken(member.getEmail(), token.getRefreshToken());

return token;
}
else {
// 신규 회원일 경우 회원가입 처리
Expand All @@ -67,15 +71,19 @@ public Token createLoginInfo(LoginRequest request) {

log.info("[회원 가입 서비스]: {}", request.email());

Member newMember = Member.builder()
Member member = Member.builder()
.password(bCryptPasswordEncoder.encode(request.password()))
.email(request.email())
.memberRole(MemberRole.PENDING)
.build();
memberRepository.save(newMember);
memberRepository.save(member);

// 회원가입 성공 후 토큰 생성 및 반환
return jwtTokenProvider.createToken(newMember.getId(), request.email(),MemberRole.PENDING.getDescription());
Token token = jwtTokenProvider.createToken(member.getId(), member.getEmail(), MemberRole.PENDING.getDescription());

saveOrUpdateRefreshToken(member.getEmail(), token.getRefreshToken());

return token;
}
}

Expand All @@ -96,7 +104,12 @@ public Token completeSignup(CompleteSignupRequest request, String accessToken) {
member.updateRole(MemberRole.MEMBER);
memberRepository.save(member);

return jwtTokenProvider.createToken(member.getId(), member.getEmail(), MemberRole.MEMBER.getDescription());
Token token = jwtTokenProvider.createToken(member.getId(), member.getEmail(), MemberRole.MEMBER.getDescription());

// RefreshTokenEntity 저장
saveOrUpdateRefreshToken(member.getEmail(), token.getRefreshToken());

return token;
}
log.info("memberRole = {}", member.getMemberRole());
return null;
Expand Down Expand Up @@ -127,25 +140,36 @@ public ReissueResponse tokenReissue(ReissueRequest request) {
throw new AppException(ErrorCode.TOKEN_EXPIRED);
}

if (!request.equals(request)) {
if (!findToken.getRefreshToken().equals(request.refreshToken())) {
log.warn("[쿠키로 들어온 토큰과 DB의 토큰이 일치하지 않음.]");
throw new AppException(ErrorCode.REFRESH_TOKEN_NOT_EXIST);
}

Token token = jwtTokenProvider.createToken(memberId, email, role);
findToken.updateRefreshToken(token.getRefreshToken());
refreshTokenRepository.save(findToken);

log.info("재발급 된 액세스 토큰: {}", token.getAccessToken());
log.info("재발급 된 refresh 토큰: {}", token.getRefreshToken());

// RefreshTokenEntity 업데이트
saveOrUpdateRefreshToken(email, token.getRefreshToken());
return ReissueResponse.from(token.getAccessToken(),token.getRefreshToken());
}

private void saveOrUpdateRefreshToken(String email, String refreshToken) {
RefreshTokenEntity refreshTokenEntity = refreshTokenRepository.findById(email)
.orElse(RefreshTokenEntity.builder().email(email).build());

refreshTokenEntity.updateRefreshToken(refreshToken);
refreshTokenRepository.save(refreshTokenEntity);
}

@Transactional
public void logout(LogoutRequest request) {
String memberId = jwtTokenProvider.getEmail(request.refreshToken());
RefreshTokenEntity existRefreshToken = refreshTokenRepository.findById(memberId)
String email = jwtTokenProvider.getEmail(request.refreshToken());

RefreshTokenEntity existRefreshToken = refreshTokenRepository.findById(email)
.orElseThrow(() -> new AppException(ErrorCode.REFRESH_TOKEN_NOT_EXIST));

setBlackList(request.refreshToken());
log.info("[로그아웃 된 리프레시 토큰 블랙리스트 처리]");
refreshTokenRepository.delete(existRefreshToken);
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/cotato/growingpain/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand Down Expand Up @@ -59,8 +58,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests(request -> request
.requestMatchers(WHITE_LIST).permitAll()
.requestMatchers(HttpMethod.GET, REQUIRED_AUTHENTICATE).authenticated()
.requestMatchers(HttpMethod.GET).permitAll()
.requestMatchers(REQUIRED_AUTHENTICATE).hasAuthority("ROLE_MEMBER")
.anyRequest().authenticated()
);
return http.build();
Expand Down

0 comments on commit 2988ad7

Please sign in to comment.