Repository navigation
feat: 구글 로그인 API (#71) #73
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
Open
ji2081
wants to merge
4
commits into
develop
Choose a base branch
from
feat/71-google-login-api
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+771
−2
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
62 changes: 62 additions & 0 deletions
62
src/main/java/com/sniptext/domain/auth/controller/AuthController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| package com.sniptext.domain.auth.controller; | ||
|
|
||
| import org.springframework.http.HttpHeaders; | ||
| import org.springframework.http.ResponseCookie; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestBody; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
|
|
||
| import com.sniptext.domain.auth.controller.dto.AuthLoginRequest; | ||
| import com.sniptext.domain.auth.controller.dto.AuthLoginResponse; | ||
| import com.sniptext.domain.auth.service.AuthCommandService; | ||
| import com.sniptext.domain.auth.service.RefreshTokenIssuer; | ||
| import com.sniptext.domain.auth.service.dto.result.AuthLoginResult; | ||
| import com.sniptext.global.response.ApiResponse; | ||
| import com.sniptext.global.response.ResultCode; | ||
|
|
||
| import jakarta.validation.Valid; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| /** | ||
| * 로그인 (로그인 불필요, 캐시 금지). 재발급 토큰은 본문이 아니라 HttpOnly·Secure 쿠키로만 내보낸다. | ||
| * 쿠키 경로를 인증 API로 좁혀 다른 API 요청에는 재발급 토큰이 실려 가지 않게 한다. | ||
| */ | ||
| @RestController | ||
| @RequestMapping("/api/v1/auth") | ||
| @RequiredArgsConstructor | ||
| public class AuthController { | ||
|
|
||
| private static final String REFRESH_TOKEN_COOKIE = "refreshToken"; | ||
| private static final String COOKIE_PATH = "/api/v1/auth"; | ||
|
|
||
| private final AuthCommandService authCommandService; | ||
| private final AuthCookieProperties cookieProperties; | ||
|
|
||
| @PostMapping("/login") | ||
| public ResponseEntity<ApiResponse<AuthLoginResponse>> login(@Valid @RequestBody AuthLoginRequest request) { | ||
| AuthLoginResult result = authCommandService.login(request.toCommand()); | ||
| AuthLoginResponse response = AuthLoginResponse.from(result); | ||
|
|
||
| if (!result.completedSignUp()) { | ||
| return ResponseEntity.ok(new ApiResponse<>(true, AuthSuccessCode.LOGGED_IN.getCode(), | ||
| AuthSuccessCode.SIGN_UP_REQUIRED_MESSAGE, response)); | ||
| } | ||
| return withRefreshToken(AuthSuccessCode.LOGGED_IN, response, result.refreshToken()); | ||
| } | ||
|
|
||
| private <T> ResponseEntity<ApiResponse<T>> withRefreshToken(ResultCode resultCode, T response, String refreshToken) { | ||
| ResponseCookie cookie = ResponseCookie.from(REFRESH_TOKEN_COOKIE, refreshToken) | ||
| .httpOnly(true) | ||
| .secure(true) | ||
| .sameSite(cookieProperties.sameSite()) | ||
| .path(COOKIE_PATH) | ||
| .maxAge(RefreshTokenIssuer.TTL) | ||
| .build(); | ||
| return ResponseEntity.status(resultCode.getHttpStatus()) | ||
| .header(HttpHeaders.SET_COOKIE, cookie.toString()) | ||
| .body(ApiResponse.of(resultCode, response)); | ||
| } | ||
|
|
||
| } |
18 changes: 18 additions & 0 deletions
18
src/main/java/com/sniptext/domain/auth/controller/AuthCookieProperties.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package com.sniptext.domain.auth.controller; | ||
|
|
||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
| import org.springframework.boot.context.properties.bind.DefaultValue; | ||
| import org.springframework.validation.annotation.Validated; | ||
|
|
||
| import jakarta.validation.constraints.Pattern; | ||
|
|
||
| /** | ||
| * 재발급 토큰 쿠키 설정. 화면과 API가 같은 사이트면 기본값 Lax로 쿠키가 오간다. | ||
| * 서로 다른 사이트에서 호출하는 환경(예: 로컬 화면 → 개발 서버)은 None이어야 쿠키가 오간다. | ||
| */ | ||
| @Validated | ||
| @ConfigurationProperties("sniptext.auth.cookie") | ||
| public record AuthCookieProperties( | ||
| @DefaultValue("Lax") @Pattern(regexp = "Strict|Lax|None") String sameSite | ||
| ) { | ||
| } |
26 changes: 26 additions & 0 deletions
26
src/main/java/com/sniptext/domain/auth/controller/AuthSuccessCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| package com.sniptext.domain.auth.controller; | ||
|
|
||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| import com.sniptext.global.response.ResultCode; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum AuthSuccessCode implements ResultCode { | ||
|
|
||
| LOGGED_IN(HttpStatus.OK, "AUTH200_2", "로그인에 성공했습니다."); | ||
|
|
||
| /** | ||
| * 처음 온 사용자의 로그인 응답 문구 (명세 1번). 코드는 LOGGED_IN과 같은 AUTH200_2다. | ||
| * 결과 코드 하나에 상수 하나만 둘 수 있어(ResultCodeRegistry가 중복이면 기동을 멈춘다) 문구만 따로 둔다. | ||
| */ | ||
| public static final String SIGN_UP_REQUIRED_MESSAGE = "약관 동의가 필요합니다."; | ||
|
|
||
| private final HttpStatus httpStatus; | ||
| private final String code; | ||
| private final String message; | ||
|
|
||
| } |
24 changes: 24 additions & 0 deletions
24
src/main/java/com/sniptext/domain/auth/controller/dto/AuthLoginRequest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| package com.sniptext.domain.auth.controller.dto; | ||
|
|
||
| import com.sniptext.domain.auth.service.dto.command.AuthLoginCommand; | ||
|
|
||
| import jakarta.validation.constraints.NotBlank; | ||
| import jakarta.validation.constraints.NotNull; | ||
| import jakarta.validation.constraints.Pattern; | ||
|
|
||
| /** | ||
| * 구글 로그인 (명세 1번). 빈 값이 구글까지 가면 구글 오류(AUTH502_1)로 둔갑하므로 여기서 COMMON400_1로 막는다. | ||
| * provider를 열거형으로 받으면 잘못된 값이 AUTH400_1이 아니라 파싱 실패(COMMON400_1)가 되어 문자열로 받는다. | ||
| */ | ||
| public record AuthLoginRequest( | ||
| @NotBlank String code, | ||
| @NotBlank String codeVerifier, | ||
| @NotBlank String redirectUri, | ||
| @NotNull(message = "AUTH400_1") @Pattern(regexp = "GOOGLE", message = "AUTH400_1") String provider | ||
| ) { | ||
|
|
||
| public AuthLoginCommand toCommand() { | ||
| return new AuthLoginCommand(code, codeVerifier, redirectUri); | ||
| } | ||
|
|
||
| } |
31 changes: 31 additions & 0 deletions
31
src/main/java/com/sniptext/domain/auth/controller/dto/AuthLoginResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package com.sniptext.domain.auth.controller.dto; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonProperty; | ||
| import com.sniptext.domain.auth.service.dto.result.AuthLoginResult; | ||
|
|
||
| /** 구글 로그인 결과 (명세 1번). 재발급 토큰은 본문에 넣지 않고 쿠키로 내보낸다. */ | ||
| public record AuthLoginResponse( | ||
| @JsonProperty("isCompletedSignUp") boolean isCompletedSignUp, | ||
| String accessToken, | ||
| Long userId, | ||
| String nickname, | ||
| String signupToken, | ||
| String email, | ||
| String name, | ||
| String profileImageUrl | ||
| ) { | ||
|
|
||
| public static AuthLoginResponse from(AuthLoginResult result) { | ||
| return new AuthLoginResponse( | ||
| result.completedSignUp(), | ||
| result.accessToken(), | ||
| result.userId(), | ||
| result.nickname(), | ||
| result.signupToken(), | ||
| result.email(), | ||
| result.name(), | ||
| result.profileImageUrl() | ||
| ); | ||
| } | ||
|
|
||
| } |
25 changes: 25 additions & 0 deletions
25
src/main/java/com/sniptext/domain/auth/exception/AuthErrorCode.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package com.sniptext.domain.auth.exception; | ||
|
|
||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| import com.sniptext.global.response.ResultCode; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum AuthErrorCode implements ResultCode { | ||
|
|
||
| /** provider 값 오류 (S1은 GOOGLE만). 요청 객체의 검증 어노테이션이 코드로 쓴다 */ | ||
| UNSUPPORTED_PROVIDER(HttpStatus.BAD_REQUEST, "AUTH400_1", "지원하지 않는 로그인 방식이에요."), | ||
| /** 인가 코드가 잘못됨·만료·이미 사용됨, 허용 목록에 없는 redirectUri, ID 토큰 검증 실패, 이메일 미인증 계정 */ | ||
| GOOGLE_LOGIN_REJECTED(HttpStatus.UNAUTHORIZED, "AUTH401_3", "구글 로그인 정보를 확인할 수 없어요. 다시 시도해주세요."), | ||
| /** 구글 장애·연결 실패·시간 초과 */ | ||
| GOOGLE_UNAVAILABLE(HttpStatus.BAD_GATEWAY, "AUTH502_1", "일시적인 오류로 로그인하지 못했어요. 다시 시도해주세요."); | ||
|
|
||
| private final HttpStatus httpStatus; | ||
| private final String code; | ||
| private final String message; | ||
|
|
||
| } |
76 changes: 76 additions & 0 deletions
76
src/main/java/com/sniptext/domain/auth/service/AuthCommandService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| package com.sniptext.domain.auth.service; | ||
|
|
||
| import java.util.Optional; | ||
|
|
||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.support.TransactionTemplate; | ||
|
|
||
| import com.sniptext.domain.auth.entity.SocialAccount; | ||
| import com.sniptext.domain.auth.entity.SocialProvider; | ||
| import com.sniptext.domain.auth.exception.AuthErrorCode; | ||
| import com.sniptext.domain.auth.repository.SocialAccountRepository; | ||
| import com.sniptext.domain.auth.service.dto.command.AuthLoginCommand; | ||
| import com.sniptext.domain.auth.service.dto.result.AuthLoginResult; | ||
| import com.sniptext.domain.user.service.UserCommandService; | ||
| import com.sniptext.domain.user.service.UserQueryService; | ||
| import com.sniptext.global.client.google.GoogleAccount; | ||
| import com.sniptext.global.client.google.GoogleAuthCodeClient; | ||
| import com.sniptext.global.client.google.GoogleLoginException; | ||
| import com.sniptext.global.exception.BusinessException; | ||
| import com.sniptext.global.security.JwtTokenProvider; | ||
| import com.sniptext.global.security.SignupTokenClaims; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| /** | ||
| * 구글 로그인. 클래스에 @Transactional을 붙이지 않는다. | ||
| * 구글 호출(최대 수 초) 동안 DB 연결을 잡고 있지 않도록, DB 작업만 TransactionTemplate으로 묶는다. | ||
| */ | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class AuthCommandService { | ||
|
|
||
| private final GoogleAuthCodeClient googleAuthCodeClient; | ||
| private final SocialAccountRepository socialAccountRepository; | ||
| private final UserCommandService userCommandService; | ||
| private final UserQueryService userQueryService; | ||
| private final RefreshTokenIssuer refreshTokenIssuer; | ||
| private final JwtTokenProvider jwtTokenProvider; | ||
| private final TransactionTemplate transactionTemplate; | ||
|
|
||
| /** | ||
| * 구글 인가 코드로 로그인한다. 사용자 실패는 AUTH401_3, 구글 장애는 AUTH502_1. | ||
| * 처음 온 사용자는 회원을 만들지 않고 가입용 토큰만 준다 (약관 동의 전에는 개인정보를 저장하지 않는다). | ||
| * 연결된 회원이 탈퇴했으면 USER404_1이다. | ||
| */ | ||
| public AuthLoginResult login(AuthLoginCommand command) { | ||
| GoogleAccount account = exchangeCode(command); | ||
|
|
||
| Optional<SocialAccount> socialAccount = socialAccountRepository.findByProviderAndProviderUserId( | ||
| SocialProvider.GOOGLE, account.subject()); | ||
| if (socialAccount.isEmpty()) { | ||
| String signupToken = jwtTokenProvider.issueSignupToken(new SignupTokenClaims( | ||
| account.subject(), account.email(), account.name(), account.pictureUrl())); | ||
| return AuthLoginResult.signUpRequired(signupToken, account.email(), account.name(), account.pictureUrl()); | ||
| } | ||
|
|
||
| Long userId = socialAccount.get().getUserId(); | ||
| return transactionTemplate.execute(status -> { | ||
| userCommandService.recordLogin(userId); | ||
| String refreshToken = refreshTokenIssuer.issueForNewLogin(userId); | ||
| return AuthLoginResult.loggedIn(jwtTokenProvider.issueAccessToken(userId), refreshToken, userId, | ||
| userQueryService.getNickname(userId)); | ||
| }); | ||
| } | ||
|
|
||
| // 구글 호출 실패 원인에는 응답 내용이 들어 있을 수 있어 원인으로 붙이지 않는다 | ||
| private GoogleAccount exchangeCode(AuthLoginCommand command) { | ||
| try { | ||
| return googleAuthCodeClient.exchange(command.code(), command.codeVerifier(), command.redirectUri()) | ||
| .orElseThrow(() -> new BusinessException(AuthErrorCode.GOOGLE_LOGIN_REJECTED)); | ||
| } catch (GoogleLoginException e) { | ||
| throw new BusinessException(AuthErrorCode.GOOGLE_UNAVAILABLE); | ||
|
Comment on lines
+71
to
+72
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. GoogleLoginException을 AUTH502_1로 바꾸면서 로그가 하나도 남지 않아요. 전역 예외 처리도 BusinessException은 로그를 안 남겨서, 구글 장애·클라이언트 시크릿 오류·토큰 엔드포인트 설정 오류가 운영에서 전부 흔적 없이 502로만 보이게 됩니다. 예외 메시지는 GoogleAuthCodeClient에서 이미 민감한 값을 빼고 만들고 있으니, 여기서 log.warn("구글 로그인 실패: {}", e.getMessage()) 정도는 남겨주면 좋을 거 같아요! |
||
| } | ||
| } | ||
|
|
||
| } | ||
64 changes: 64 additions & 0 deletions
64
src/main/java/com/sniptext/domain/auth/service/RefreshTokenIssuer.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| package com.sniptext.domain.auth.service; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
| import java.security.MessageDigest; | ||
| import java.security.NoSuchAlgorithmException; | ||
| import java.security.SecureRandom; | ||
| import java.time.Clock; | ||
| import java.time.Duration; | ||
| import java.time.LocalDateTime; | ||
| import java.util.Base64; | ||
| import java.util.HexFormat; | ||
| import java.util.UUID; | ||
|
|
||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.transaction.annotation.Propagation; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import com.sniptext.domain.auth.entity.ClientType; | ||
| import com.sniptext.domain.auth.entity.RefreshToken; | ||
| import com.sniptext.domain.auth.repository.RefreshTokenRepository; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| /** | ||
| * 재발급 토큰 발급. 원문은 쿠키로만 내보내고 DB에는 SHA-256 해시만 저장한다. | ||
| * 토큰 저장이 회원 저장과 함께 커밋되도록 호출자 트랜잭션 안에서만 동작하게 강제한다. | ||
| */ | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class RefreshTokenIssuer { | ||
|
|
||
| public static final Duration TTL = Duration.ofDays(14); | ||
|
|
||
| private static final int TOKEN_BYTES = 32; | ||
| private static final SecureRandom RANDOM = new SecureRandom(); | ||
|
|
||
| private final RefreshTokenRepository refreshTokenRepository; | ||
| private final Clock clock; | ||
|
|
||
| /** 새 로그인의 웹 재발급 토큰을 저장하고 원문을 돌려준다. 새 로그인이므로 계보(family_id)도 새로 만든다. */ | ||
| @Transactional(propagation = Propagation.MANDATORY) | ||
| public String issueForNewLogin(Long userId) { | ||
| String rawToken = generate(); | ||
| refreshTokenRepository.save(RefreshToken.create(userId, ClientType.WEB, hash(rawToken), | ||
| UUID.randomUUID().toString(), LocalDateTime.now(clock).plus(TTL))); | ||
| return rawToken; | ||
| } | ||
|
|
||
| private static String generate() { | ||
| byte[] bytes = new byte[TOKEN_BYTES]; | ||
| RANDOM.nextBytes(bytes); | ||
| return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); | ||
| } | ||
|
|
||
| private static String hash(String rawToken) { | ||
| try { | ||
| byte[] digest = MessageDigest.getInstance("SHA-256").digest(rawToken.getBytes(StandardCharsets.UTF_8)); | ||
| return HexFormat.of().formatHex(digest); | ||
| } catch (NoSuchAlgorithmException e) { | ||
| throw new IllegalStateException("SHA-256을 쓸 수 없는 환경이다", e); | ||
| } | ||
| } | ||
|
|
||
| } |
12 changes: 12 additions & 0 deletions
12
src/main/java/com/sniptext/domain/auth/service/dto/command/AuthLoginCommand.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.sniptext.domain.auth.service.dto.command; | ||
|
|
||
| /** 구글 로그인 입력. 값은 요청 단계에서 빈 값 검증을 마쳤다. */ | ||
| public record AuthLoginCommand(String code, String codeVerifier, String redirectUri) { | ||
|
|
||
| /** 인가 코드와 코드 검증값은 로그에 남기지 않는다. */ | ||
| @Override | ||
| public String toString() { | ||
| return "AuthLoginCommand[redirectUri=%s]".formatted(redirectUri); | ||
| } | ||
|
|
||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(사소)
recordLogin과getNickname이 각각 회원을 다시 조회해서 로그인 한 번에 같은 회원 조회 쿼리가 두 번 나가요(조건 조회라 1차 캐시를 타지 않음). 급하진 않지만, 연결 지점 모양을 정할 때recordLogin이 닉네임을 돌려주게 하는 방법도 있을 것 같습니다!