Repository navigation
Expand file tree
/
Copy pathAuthService.java
More file actions
230 lines (187 loc) · 8.37 KB
/
Copy pathAuthService.java
File metadata and controls
230 lines (187 loc) · 8.37 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
package flipnote.user.application;
import java.util.List;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import flipnote.user.application.command.ChangePasswordCommand;
import flipnote.user.application.command.LoginCommand;
import flipnote.user.application.command.SignupCommand;
import flipnote.user.application.result.SocialLinksResult;
import flipnote.user.application.result.TokenValidateResult;
import flipnote.user.application.result.UserRegisterResult;
import flipnote.user.domain.AuthErrorCode;
import flipnote.user.domain.TokenClaims;
import flipnote.user.domain.TokenPair;
import flipnote.user.domain.UserErrorCode;
import flipnote.user.domain.common.BizException;
import flipnote.user.domain.entity.OAuthLink;
import flipnote.user.domain.entity.User;
import flipnote.user.domain.event.EmailVerificationSendEvent;
import flipnote.user.domain.event.PasswordResetCreateEvent;
import flipnote.user.domain.repository.OAuthLinkRepository;
import flipnote.user.domain.repository.UserRepository;
import flipnote.user.infrastructure.config.ClientProperties;
import flipnote.user.infrastructure.jwt.JwtProvider;
import flipnote.user.infrastructure.mail.PasswordResetTokenGenerator;
import flipnote.user.infrastructure.mail.VerificationCodeGenerator;
import flipnote.user.infrastructure.redis.EmailVerificationRepository;
import flipnote.user.infrastructure.redis.PasswordResetRepository;
import flipnote.user.infrastructure.redis.SessionInvalidationRepository;
import flipnote.user.infrastructure.redis.TokenBlacklistRepository;
import lombok.RequiredArgsConstructor;
@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 UserRegisterResult register(SignupCommand command) {
if (!emailVerificationRepository.isVerified(command.email())) {
throw new BizException(AuthErrorCode.UNVERIFIED_EMAIL);
}
if (userRepository.existsByEmail(command.email())) {
throw new BizException(AuthErrorCode.EMAIL_ALREADY_EXISTS);
}
User user = User.builder()
.email(command.email())
.password(passwordEncoder.encode(command.password()))
.name(command.name())
.nickname(command.nickname())
.phone(command.phone())
.smsAgree(command.smsAgree())
.build();
User savedUser = userRepository.save(user);
return UserRegisterResult.from(savedUser);
}
public TokenPair login(LoginCommand command) {
User user = userRepository.findByEmailAndStatus(command.email(), User.Status.ACTIVE)
.orElseThrow(() -> new BizException(AuthErrorCode.INVALID_CREDENTIALS));
if (!passwordEncoder.matches(command.password(), user.getPassword())) {
throw new BizException(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 BizException(AuthErrorCode.INVALID_TOKEN);
}
if (tokenBlacklistRepository.isBlacklisted(refreshToken)) {
throw new BizException(AuthErrorCode.BLACKLISTED_TOKEN);
}
TokenClaims claims = jwtProvider.extractClaims(refreshToken);
sessionInvalidationRepository.getInvalidatedAtMillis(claims.userId()).ifPresent(invalidatedAtMillis -> {
if (jwtProvider.getIssuedAt(refreshToken).getTime() < invalidatedAtMillis) {
throw new BizException(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, ChangePasswordCommand command) {
User user = findActiveUser(userId);
if (!passwordEncoder.matches(command.currentPassword(), user.getPassword())) {
throw new BizException(AuthErrorCode.PASSWORD_MISMATCH);
}
user.changePassword(passwordEncoder.encode(command.newPassword()));
sessionInvalidationRepository.invalidate(user.getId(), jwtProvider.getRefreshTokenExpiration());
}
public TokenValidateResult validateToken(String token) {
if (!jwtProvider.isTokenValid(token)) {
throw new BizException(AuthErrorCode.INVALID_TOKEN);
}
if (tokenBlacklistRepository.isBlacklisted(token)) {
throw new BizException(AuthErrorCode.BLACKLISTED_TOKEN);
}
TokenClaims claims = jwtProvider.extractClaims(token);
sessionInvalidationRepository.getInvalidatedAtMillis(claims.userId()).ifPresent(invalidatedAtMillis -> {
if (jwtProvider.getIssuedAt(token).getTime() < invalidatedAtMillis) {
throw new BizException(AuthErrorCode.INVALIDATED_SESSION);
}
});
return new TokenValidateResult(claims.userId(), claims.email(), claims.role());
}
public void sendEmailVerificationCode(String email) {
if (emailVerificationRepository.hasCode(email)) {
throw new BizException(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 BizException(AuthErrorCode.NOT_ISSUED_VERIFICATION_CODE);
}
String savedCode = emailVerificationRepository.getCode(email);
if (!code.equals(savedCode)) {
throw new BizException(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 BizException(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 BizException(AuthErrorCode.INVALID_PASSWORD_RESET_TOKEN);
}
User user = userRepository.findByEmailAndStatus(email, User.Status.ACTIVE)
.orElseThrow(() -> new BizException(UserErrorCode.USER_NOT_FOUND));
user.changePassword(passwordEncoder.encode(newPassword));
sessionInvalidationRepository.invalidate(user.getId(), jwtProvider.getRefreshTokenExpiration());
passwordResetRepository.delete(token, email);
}
public SocialLinksResult getSocialLinks(Long userId) {
List<OAuthLink> links = oAuthLinkRepository.findByUser_Id(userId);
return SocialLinksResult.from(links);
}
@Transactional
public void deleteSocialLink(Long userId, Long socialLinkId) {
if (!oAuthLinkRepository.existsByIdAndUser_Id(socialLinkId, userId)) {
throw new BizException(AuthErrorCode.NOT_REGISTERED_SOCIAL_ACCOUNT);
}
oAuthLinkRepository.deleteById(socialLinkId);
}
private User findActiveUser(Long userId) {
return userRepository.findByIdAndStatus(userId, User.Status.ACTIVE)
.orElseThrow(() -> new BizException(UserErrorCode.USER_NOT_FOUND));
}
}