-
Notifications
You must be signed in to change notification settings - Fork 0
Feat: 회원, 인증 기능 구현 #1
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
326044f
Feat: 회원, 인증 기능 구현
dungbik de62347
Feat: 회원가입시 이메일 인증 여부 체크 추가
dungbik 67f057b
Chore: 스프링 부트 버전업
dungbik 1400fda
Feat: 모든 세션 무효화 기능 로직 수정
dungbik 7abf0ed
Feat: 예외 응답 스펙대로 수정
dungbik c5c32ca
Refactor: 프로젝트 구조 수정
dungbik a28e784
Feat: Executor 설정 추가
dungbik 5ee7b78
Feat: 토큰 무효화시 남은 ttl이 없을 경우 무효화 코드 호출 안되도록
dungbik 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
Some comments aren't visible on the classic Files Changed page.
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
232 changes: 232 additions & 0 deletions
232
src/main/java/flipnote/user/auth/application/AuthService.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,232 @@ | ||
| package flipnote.user.auth.application; | ||
|
|
||
| import flipnote.user.auth.domain.AuthErrorCode; | ||
| import flipnote.user.auth.domain.TokenClaims; | ||
| import flipnote.user.auth.domain.TokenPair; | ||
| import flipnote.user.auth.domain.event.EmailVerificationSendEvent; | ||
| import flipnote.user.auth.domain.event.PasswordResetCreateEvent; | ||
| import flipnote.user.auth.infrastructure.jwt.JwtProvider; | ||
| import flipnote.user.auth.infrastructure.redis.EmailVerificationRepository; | ||
| import flipnote.user.auth.infrastructure.redis.PasswordResetRepository; | ||
| import flipnote.user.auth.infrastructure.redis.PasswordResetTokenGenerator; | ||
| import flipnote.user.auth.infrastructure.redis.SessionInvalidationRepository; | ||
| import flipnote.user.auth.infrastructure.redis.TokenBlacklistRepository; | ||
| import flipnote.user.auth.infrastructure.redis.VerificationCodeGenerator; | ||
| import flipnote.user.auth.presentation.dto.request.ChangePasswordRequest; | ||
| import flipnote.user.auth.presentation.dto.request.LoginRequest; | ||
| import flipnote.user.auth.presentation.dto.request.SignupRequest; | ||
| import flipnote.user.auth.presentation.dto.response.SocialLinksResponse; | ||
| import flipnote.user.auth.presentation.dto.response.TokenValidateResponse; | ||
| import flipnote.user.auth.presentation.dto.response.UserResponse; | ||
| import flipnote.user.global.config.ClientProperties; | ||
| import flipnote.user.global.exception.UserException; | ||
| import flipnote.user.user.domain.OAuthLink; | ||
| import flipnote.user.user.domain.OAuthLinkRepository; | ||
| import flipnote.user.user.domain.User; | ||
| import flipnote.user.user.domain.UserErrorCode; | ||
| import flipnote.user.user.domain.UserRepository; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.context.ApplicationEventPublisher; | ||
| import org.springframework.security.crypto.password.PasswordEncoder; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| @Transactional(readOnly = true) | ||
| public class AuthService { | ||
|
|
||
| private final UserRepository userRepository; | ||
| private final PasswordEncoder passwordEncoder; | ||
| private final JwtProvider jwtProvider; | ||
| private final TokenBlacklistRepository tokenBlacklistRepository; | ||
| private final EmailVerificationRepository emailVerificationRepository; | ||
| private final PasswordResetRepository passwordResetRepository; | ||
| private final OAuthLinkRepository oAuthLinkRepository; | ||
| private final SessionInvalidationRepository sessionInvalidationRepository; | ||
| private final VerificationCodeGenerator verificationCodeGenerator; | ||
| private final PasswordResetTokenGenerator passwordResetTokenGenerator; | ||
| private final ClientProperties clientProperties; | ||
| private final ApplicationEventPublisher eventPublisher; | ||
|
|
||
| @Transactional | ||
| public UserResponse register(SignupRequest request) { | ||
| if (!emailVerificationRepository.isVerified(request.getEmail())) { | ||
| throw new UserException(AuthErrorCode.UNVERIFIED_EMAIL); | ||
| } | ||
|
|
||
| if (userRepository.existsByEmail(request.getEmail())) { | ||
| throw new UserException(AuthErrorCode.EMAIL_ALREADY_EXISTS); | ||
| } | ||
|
|
||
| User user = User.builder() | ||
| .email(request.getEmail()) | ||
| .password(passwordEncoder.encode(request.getPassword())) | ||
| .name(request.getName()) | ||
| .nickname(request.getNickname()) | ||
| .phone(request.getPhone()) | ||
| .smsAgree(Boolean.TRUE.equals(request.getSmsAgree())) | ||
| .build(); | ||
|
|
||
| User savedUser = userRepository.save(user); | ||
| return UserResponse.from(savedUser); | ||
| } | ||
|
|
||
| public TokenPair login(LoginRequest request) { | ||
| User user = userRepository.findByEmailAndStatus(request.getEmail(), User.Status.ACTIVE) | ||
| .orElseThrow(() -> new UserException(AuthErrorCode.INVALID_CREDENTIALS)); | ||
|
|
||
| if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) { | ||
| throw new UserException(AuthErrorCode.INVALID_CREDENTIALS); | ||
| } | ||
|
|
||
| return jwtProvider.generateTokenPair(user); | ||
| } | ||
|
|
||
| public void logout(String refreshToken) { | ||
| if (refreshToken != null && jwtProvider.isTokenValid(refreshToken)) { | ||
| long remaining = jwtProvider.getRemainingExpiration(refreshToken); | ||
| if (remaining > 0) { | ||
| tokenBlacklistRepository.add(refreshToken, remaining); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public TokenPair refreshToken(String refreshToken) { | ||
| if (refreshToken == null || !jwtProvider.isTokenValid(refreshToken)) { | ||
| throw new UserException(AuthErrorCode.INVALID_TOKEN); | ||
| } | ||
|
|
||
| if (tokenBlacklistRepository.isBlacklisted(refreshToken)) { | ||
| throw new UserException(AuthErrorCode.BLACKLISTED_TOKEN); | ||
| } | ||
|
|
||
| TokenClaims claims = jwtProvider.extractClaims(refreshToken); | ||
|
|
||
| sessionInvalidationRepository.getInvalidatedAtMillis(claims.userId()).ifPresent(invalidatedAtMillis -> { | ||
| if (jwtProvider.getIssuedAt(refreshToken).getTime() < invalidatedAtMillis) { | ||
| throw new UserException(AuthErrorCode.INVALIDATED_SESSION); | ||
| } | ||
| }); | ||
|
|
||
| User user = findActiveUser(claims.userId()); | ||
|
|
||
| long remaining = jwtProvider.getRemainingExpiration(refreshToken); | ||
| if (remaining > 0) { | ||
| tokenBlacklistRepository.add(refreshToken, remaining); | ||
| } | ||
|
|
||
| return jwtProvider.generateTokenPair(user); | ||
| } | ||
|
|
||
| @Transactional | ||
| public void changePassword(Long userId, ChangePasswordRequest request) { | ||
| User user = findActiveUser(userId); | ||
|
|
||
| if (!passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) { | ||
| throw new UserException(AuthErrorCode.PASSWORD_MISMATCH); | ||
| } | ||
|
|
||
| user.changePassword(passwordEncoder.encode(request.getNewPassword())); | ||
| sessionInvalidationRepository.invalidate(user.getId(), jwtProvider.getRefreshTokenExpiration()); | ||
| } | ||
|
|
||
| public TokenValidateResponse validateToken(String token) { | ||
| if (!jwtProvider.isTokenValid(token)) { | ||
| throw new UserException(AuthErrorCode.INVALID_TOKEN); | ||
| } | ||
|
|
||
| if (tokenBlacklistRepository.isBlacklisted(token)) { | ||
| throw new UserException(AuthErrorCode.BLACKLISTED_TOKEN); | ||
| } | ||
|
|
||
| TokenClaims claims = jwtProvider.extractClaims(token); | ||
|
|
||
| sessionInvalidationRepository.getInvalidatedAtMillis(claims.userId()).ifPresent(invalidatedAtMillis -> { | ||
| if (jwtProvider.getIssuedAt(token).getTime() < invalidatedAtMillis) { | ||
| throw new UserException(AuthErrorCode.INVALIDATED_SESSION); | ||
| } | ||
| }); | ||
|
|
||
| findActiveUser(claims.userId()); | ||
|
|
||
| return new TokenValidateResponse(claims.userId(), claims.email(), claims.role()); | ||
| } | ||
|
|
||
| public void sendEmailVerificationCode(String email) { | ||
| if (emailVerificationRepository.hasCode(email)) { | ||
| throw new UserException(AuthErrorCode.ALREADY_ISSUED_VERIFICATION_CODE); | ||
| } | ||
|
|
||
| String code = verificationCodeGenerator.generate(); | ||
| emailVerificationRepository.saveCode(email, code); | ||
| eventPublisher.publishEvent(new EmailVerificationSendEvent(email, code)); | ||
| } | ||
|
|
||
| public void verifyEmail(String email, String code) { | ||
| if (!emailVerificationRepository.hasCode(email)) { | ||
| throw new UserException(AuthErrorCode.NOT_ISSUED_VERIFICATION_CODE); | ||
| } | ||
|
|
||
| String savedCode = emailVerificationRepository.getCode(email); | ||
| if (!code.equals(savedCode)) { | ||
| throw new UserException(AuthErrorCode.INVALID_VERIFICATION_CODE); | ||
| } | ||
|
|
||
| emailVerificationRepository.deleteCode(email); | ||
| emailVerificationRepository.markVerified(email); | ||
| } | ||
|
|
||
| public void requestPasswordReset(String email) { | ||
| // 사용자가 없어도 정상 반환 (이메일 존재 여부 노출 방지) | ||
| if (!userRepository.existsByEmail(email)) { | ||
| return; | ||
| } | ||
|
|
||
| if (passwordResetRepository.hasToken(email)) { | ||
| throw new UserException(AuthErrorCode.ALREADY_SENT_PASSWORD_RESET_LINK); | ||
| } | ||
|
|
||
| String token = passwordResetTokenGenerator.generate(); | ||
| passwordResetRepository.save(token, email); | ||
|
|
||
| String link = clientProperties.getUrl() + clientProperties.getPaths().getPasswordReset() | ||
| + "?token=" + token; | ||
| eventPublisher.publishEvent(new PasswordResetCreateEvent(email, link)); | ||
| } | ||
|
|
||
| @Transactional | ||
| public void resetPassword(String token, String newPassword) { | ||
| String email = passwordResetRepository.findEmailByToken(token); | ||
| if (email == null) { | ||
| throw new UserException(AuthErrorCode.INVALID_PASSWORD_RESET_TOKEN); | ||
| } | ||
|
|
||
| User user = userRepository.findByEmailAndStatus(email, User.Status.ACTIVE) | ||
| .orElseThrow(() -> new UserException(UserErrorCode.USER_NOT_FOUND)); | ||
|
|
||
| user.changePassword(passwordEncoder.encode(newPassword)); | ||
| sessionInvalidationRepository.invalidate(user.getId(), jwtProvider.getRefreshTokenExpiration()); | ||
| passwordResetRepository.delete(token, email); | ||
| } | ||
|
|
||
| public SocialLinksResponse getSocialLinks(Long userId) { | ||
| List<OAuthLink> links = oAuthLinkRepository.findByUser_Id(userId); | ||
| return SocialLinksResponse.from(links); | ||
| } | ||
|
|
||
| @Transactional | ||
| public void deleteSocialLink(Long userId, Long socialLinkId) { | ||
| if (!oAuthLinkRepository.existsByIdAndUser_Id(socialLinkId, userId)) { | ||
| throw new UserException(AuthErrorCode.NOT_REGISTERED_SOCIAL_ACCOUNT); | ||
| } | ||
| oAuthLinkRepository.deleteById(socialLinkId); | ||
| } | ||
|
|
||
| private User findActiveUser(Long userId) { | ||
| return userRepository.findByIdAndStatus(userId, User.Status.ACTIVE) | ||
| .orElseThrow(() -> new UserException(UserErrorCode.USER_NOT_FOUND)); | ||
| } | ||
| } |
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.
dependencyManagement블록이 중복 선언되어 있습니다. 첫 번째 블록(lines 27–31)을 제거하세요.Lines 27–31과 63–67이 동일한 Spring gRPC BOM을 두 번 임포트하고 있습니다. 첫 번째 블록은 버전을
"1.0.2"로 하드코딩하고 있으며, 24번 줄에 선언된springGrpcVersionextra property를 사용하지 않아 일관성도 깨집니다. 두 번째 블록(lines 63–67)이 property를 올바르게 참조하므로, 첫 번째 블록을 제거해야 합니다.🔧 수정 제안
Also applies to: 63-67
🤖 Prompt for AI Agents