Skip to content

Commit

Permalink
refac: AuthService에서 인증 및 토큰 관련 로직만 처리하도록 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeongmin39 committed Jan 3, 2025
1 parent 0f62498 commit 2632124
Showing 1 changed file with 32 additions and 31 deletions.
63 changes: 32 additions & 31 deletions src/main/java/com/spot/spotserver/api/auth/service/AuthService.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
package com.spot.spotserver.api.auth.service;

import com.spot.spotserver.api.auth.client.KakaoApiClient;
import com.spot.spotserver.api.auth.client.KakaoAuthApiClient;
import com.spot.spotserver.api.auth.dto.response.KakaoAccessTokenResponse;
import com.spot.spotserver.api.auth.dto.response.KakaoUserResponse;
import com.spot.spotserver.api.auth.dto.response.TokenResponse;
import com.spot.spotserver.api.auth.exception.JwtCustomException;
import com.spot.spotserver.api.auth.exception.OAuth2TokenException;
import com.spot.spotserver.api.auth.handler.UserAuthentication;
import com.spot.spotserver.api.auth.jwt.JwtTokenProvider;
import com.spot.spotserver.api.auth.jwt.JwtValidationType;
import com.spot.spotserver.api.auth.jwt.redis.RefreshTokenService;
import com.spot.spotserver.api.user.domain.User;
import com.spot.spotserver.api.user.exception.UserNotFoundException;
import com.spot.spotserver.api.user.repository.UserRepository;
import com.spot.spotserver.api.user.service.UserService;
import com.spot.spotserver.common.payload.ErrorCode;
import feign.FeignException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
Expand All @@ -24,17 +23,10 @@
@RequiredArgsConstructor
public class AuthService {

private static final String AUTH_CODE = "authorization_code";
private static final String REDIRECT_URI = "http://localhost:8080/api/login/kakao";

@Value("${spring.security.oauth2.client.registration.kakao.client-id}")
private String clientId;

@Value("${spring.security.oauth2.client.registration.kakao.client-secret}")
private String clientSecret;

private final KakaoApiClient kakaoApiClient;
private final KakaoAuthApiClient kakaoAuthApiClient;
private final JwtTokenProvider jwtTokenProvider;
private final UserService userService;
private final UserRepository userRepository;
Expand All @@ -47,39 +39,48 @@ public TokenResponse login(final String accessToken) {
}

// 카카오 액세스 토큰으로 사용자 정보 가져오기
KakaoUserResponse userResponse;
try {
userResponse = getUserInfo(accessToken);
} catch (FeignException e) {
throw new OAuth2TokenException(ErrorCode.USER_INFO_REQUEST_FAILED);
}
KakaoUserResponse userResponse = getUserInfo(accessToken);
Long userId = userService.processUser(userResponse);

// 기존 리프레시 토큰 확인 및 재사용
String existingRefreshToken = refreshTokenService.getRefreshToken(userId);
String jwtRefreshToken = existingRefreshToken != null
? existingRefreshToken
: jwtTokenProvider.issueRefreshToken(new UserAuthentication(userId, null, null));

// 서비스 자체 JWT 액세스 및 리프레시 토큰 생성
UserAuthentication authentication = new UserAuthentication(userResponse.id(), null, null);
String jwtAccessToken = jwtTokenProvider.issueAccessToken(authentication);
String jwtRefreshToken = jwtTokenProvider.issueRefreshToken(authentication);
// Redis에 리프레시 토큰 저장
refreshTokenService.saveRefreshToken(userService.getIdBySocialId(userResponse.id()), jwtRefreshToken);

// 리프레시 토큰 레디스에 저장
refreshTokenService.saveRefreshToken(userResponse.id(), jwtRefreshToken);
// 액세스 토큰 생성
String jwtAccessToken = jwtTokenProvider.issueAccessToken(new UserAuthentication(userId, null, null));

return processUser(userResponse);
return TokenResponse.of(jwtAccessToken, jwtRefreshToken);
}

private KakaoUserResponse getUserInfo(final String accessToken) {
return kakaoApiClient.getUserInformation("Bearer " + accessToken);
}

private TokenResponse processUser(KakaoUserResponse userResponse) {
if (userService.isExistingUser(userResponse.id())) {
return userService.getTokenByUserId(userService.getIdBySocialId(userResponse.id()));
} else {
return userService.getTokenByUserId(userService.createUser(userResponse));
}
}

public User getUserFromAccessToken(String accessToken) {
Long userId = jwtTokenProvider.getUserFromJwt(accessToken);
return userRepository.findById(userId)
.orElseThrow(() -> new UserNotFoundException(ErrorCode.USER_NOT_FOUND));
}

public TokenResponse reissueToken(final String refreshToken) {
JwtValidationType validationType = jwtTokenProvider.validateToken(refreshToken);

if (validationType != JwtValidationType.VALID_JWT) {
throw new JwtCustomException(ErrorCode.INVALID_JWT_TOKEN);
}

Long userId = jwtTokenProvider.getUserFromJwt(refreshToken);
UserAuthentication userAuthentication = new UserAuthentication(userId, null, null);
String newAccessToken = jwtTokenProvider.issueAccessToken(userAuthentication);
String newRefreshToken = jwtTokenProvider.issueRefreshToken(userAuthentication);

// 새로운 리프레시 토큰으로 교체
refreshTokenService.saveRefreshToken(userId, newRefreshToken);
return TokenResponse.of(newAccessToken, newRefreshToken);
}
}

0 comments on commit 2632124

Please sign in to comment.