-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthService.java
More file actions
232 lines (189 loc) · 9.59 KB
/
AuthService.java
File metadata and controls
232 lines (189 loc) · 9.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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));
}
}