forked from devondragon/SpringUserFramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserService.java
488 lines (432 loc) · 15.9 KB
/
UserService.java
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package com.digitalsanctuary.spring.user.service;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.digitalsanctuary.spring.user.dto.UserDto;
import com.digitalsanctuary.spring.user.exceptions.UserAlreadyExistException;
import com.digitalsanctuary.spring.user.persistence.model.PasswordResetToken;
import com.digitalsanctuary.spring.user.persistence.model.User;
import com.digitalsanctuary.spring.user.persistence.model.VerificationToken;
import com.digitalsanctuary.spring.user.persistence.repository.PasswordResetTokenRepository;
import com.digitalsanctuary.spring.user.persistence.repository.RoleRepository;
import com.digitalsanctuary.spring.user.persistence.repository.UserRepository;
import com.digitalsanctuary.spring.user.persistence.repository.VerificationTokenRepository;
import com.digitalsanctuary.spring.user.util.TimeLogger;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Service class for managing users. Provides methods for user registration, authentication, password management, and user-related operations. This
* class is transactional and uses various repositories and services for its operations.
*
* <p>
* This class is transactional, meaning that any failure causes the entire operation to roll back to the previous state.
* </p>
*
* <p>
* Dependencies:
* </p>
* <ul>
* <li>{@link UserRepository}</li>
* <li>{@link VerificationTokenRepository}</li>
* <li>{@link PasswordResetTokenRepository}</li>
* <li>{@link PasswordEncoder}</li>
* <li>{@link RoleRepository}</li>
* <li>{@link SessionRegistry}</li>
* <li>{@link UserEmailService}</li>
* <li>{@link UserVerificationService}</li>
* <li>{@link DSUserDetailsService}</li>
* </ul>
*
* <p>
* Configuration:
* </p>
* <ul>
* <li>sendRegistrationVerificationEmail: Flag to determine if a verification email should be sent upon registration.</li>
* </ul>
*
* <p>
* Enum:
* </p>
* <ul>
* <li>{@link TokenValidationResult}: Enum representing the result of token validation.</li>
* </ul>
*
* <p>
* Methods:
* </p>
* <ul>
* <li>{@link #registerNewUserAccount(UserDto)}: Registers a new user account.</li>
* <li>{@link #saveRegisteredUser(User)}: Saves a registered user.</li>
* <li>{@link #deleteUser(User)}: Deletes a user and cleans up associated tokens.</li>
* <li>{@link #findUserByEmail(String)}: Finds a user by email.</li>
* <li>{@link #getPasswordResetToken(String)}: Gets a password reset token by token string.</li>
* <li>{@link #getUserByPasswordResetToken(String)}: Gets a user by password reset token.</li>
* <li>{@link #findUserByID(long)}: Finds a user by ID.</li>
* <li>{@link #changeUserPassword(User, String)}: Changes the user's password.</li>
* <li>{@link #checkIfValidOldPassword(User, String)}: Checks if the provided old password is valid.</li>
* <li>{@link #validatePasswordResetToken(String)}: Validates a password reset token.</li>
* <li>{@link #getUsersFromSessionRegistry()}: Gets the list of users from the session registry.</li>
* <li>{@link #authWithoutPassword(User)}: Authenticates a user without a password.</li>
* </ul>
*
* <p>
* Private Methods:
* </p>
* <ul>
* <li>{@link #emailExists(String)}: Checks if an email exists in the user repository.</li>
* <li>{@link #authenticateUser(DSUserDetails, Collection)}: Authenticates a user by setting the authentication object in the security context.</li>
* <li>{@link #storeSecurityContextInSession()}: Stores the current security context in the session.</li>
* </ul>
*
* <p>
* Annotations:
* </p>
* <ul>
* <li>{@link Slf4j}: For logging.</li>
* <li>{@link Service}: Indicates that this class is a service component in Spring.</li>
* <li>{@link RequiredArgsConstructor}: Generates a constructor with required arguments.</li>
* <li>{@link Transactional}: Indicates that the class or methods should be transactional.</li>
* <li>{@link Value}: Injects property values.</li>
* </ul>
*
* @author Devon Hillard
*/
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class UserService {
/**
* Enum representing the result of token validation.
*/
public enum TokenValidationResult {
/**
* Indicates that the token is valid and can be used.
*/
VALID("valid"),
/**
* Indicates that the token is invalid, either due to tampering or an unknown format.
*/
INVALID_TOKEN("invalidToken"),
/**
* Indicates that the token was valid but has expired and is no longer usable.
*/
EXPIRED("expired");
private final String value;
/**
* Instantiates a new token validation result.
*
* @param value the string representation of the token validation result.
*/
TokenValidationResult(String value) {
this.value = value;
}
/**
* Gets the string representation of the token validation result.
*
* @return the value of the token validation result.
*/
public String getValue() {
return value;
}
}
/** The user role name. */
private static final String USER_ROLE_NAME = "ROLE_USER";
/** The user repository. */
private final UserRepository userRepository;
/** The token repository. */
private final VerificationTokenRepository tokenRepository;
/** The password token repository. */
private final PasswordResetTokenRepository passwordTokenRepository;
/** The password encoder. */
private final PasswordEncoder passwordEncoder;
/** The role repository. */
private final RoleRepository roleRepository;
/** The session registry. */
private final SessionRegistry sessionRegistry;
/** The user email service. */
public final UserEmailService userEmailService;
/** The user verification service. */
public final UserVerificationService userVerificationService;
private final AuthorityService authorityService;
/** The user details service. */
private final DSUserDetailsService dsUserDetailsService;
/** The send registration verification email flag. */
@Value("${user.registration.sendVerificationEmail:false}")
private boolean sendRegistrationVerificationEmail;
/**
* Registers a new user account with the provided user data.
* If the email already exists, throws a UserAlreadyExistException.
* If sendRegistrationVerificationEmail is false, the user is enabled immediately.
*
* @param newUserDto the data transfer object containing the user registration information
* @return the newly created user entity
* @throws UserAlreadyExistException if an account with the same email already exists
*/
public User registerNewUserAccount(final UserDto newUserDto) {
TimeLogger timeLogger = new TimeLogger(log, "UserService.registerNewUserAccount");
log.debug("UserService.registerNewUserAccount: called with userDto: {}", newUserDto);
if (emailExists(newUserDto.getEmail())) {
log.debug("UserService.registerNewUserAccount:" + "email already exists: {}", newUserDto.getEmail());
throw new UserAlreadyExistException("There is an account with that email address: " + newUserDto.getEmail());
}
// Create a new User entity
User user = new User();
user.setFirstName(newUserDto.getFirstName());
user.setLastName(newUserDto.getLastName());
user.setPassword(passwordEncoder.encode(newUserDto.getPassword()));
user.setEmail(newUserDto.getEmail());
user.setRoles(Arrays.asList(roleRepository.findByName(USER_ROLE_NAME)));
// If we are not sending a verification email
if (!sendRegistrationVerificationEmail) {
// Enable the user immediately
user.setEnabled(true);
}
user = userRepository.save(user);
// authWithoutPassword(user);
timeLogger.end();
return user;
}
/**
* Save registered user.
*
* @param user the user
* @return the user
*/
public User saveRegisteredUser(final User user) {
return userRepository.save(user);
}
/**
* Delete user.
*
* @param user the user
*/
public void deleteUser(final User user) {
// Clean up any Tokens associated with this user
final VerificationToken verificationToken = tokenRepository.findByUser(user);
if (verificationToken != null) {
tokenRepository.delete(verificationToken);
}
final PasswordResetToken passwordToken = passwordTokenRepository.findByUser(user);
if (passwordToken != null) {
passwordTokenRepository.delete(passwordToken);
}
// Delete the user
userRepository.delete(user);
}
/**
* Find user by email.
*
* @param email the email
* @return the user
*/
public User findUserByEmail(final String email) {
return userRepository.findByEmail(email);
}
/**
* Gets the password reset token.
*
* @param token the token
* @return the password reset token
*/
public PasswordResetToken getPasswordResetToken(final String token) {
return passwordTokenRepository.findByToken(token);
}
/**
* Gets the user by password reset token.
*
* @param token the token
* @return the user by password reset token
*/
public Optional<User> getUserByPasswordResetToken(final String token) {
return Optional.ofNullable(passwordTokenRepository.findByToken(token).getUser());
}
/**
* Gets the user by ID.
*
* @param id the id
* @return the user by ID
*/
public Optional<User> findUserByID(final long id) {
return userRepository.findById(id);
}
/**
* Change user password.
*
* @param user the user
* @param password the password
*/
public void changeUserPassword(final User user, final String password) {
user.setPassword(passwordEncoder.encode(password));
userRepository.save(user);
}
/**
* Check if valid old password.
*
* @param user the user
* @param oldPassword the old password
* @return true, if successful
*/
public boolean checkIfValidOldPassword(final User user, final String oldPassword) {
// Removed System.out.println, using log.debug for minimal output (avoid logging passwords in production)
log.debug("Verifying old password for user: {}", user.getEmail());
return passwordEncoder.matches(oldPassword, user.getPassword());
}
/**
* See if the Email exists in the user repository.
*
* @param email the email address to lookup
* @return true, if the email address is already in the user repository
*/
private boolean emailExists(final String email) {
return userRepository.findByEmail(email.toLowerCase()) != null;
}
/**
* Validate password reset token.
*
* @param token the token
* @return the password reset token validation result enum
*/
public TokenValidationResult validatePasswordResetToken(String token) {
final PasswordResetToken passToken = passwordTokenRepository.findByToken(token);
if (passToken == null) {
return TokenValidationResult.INVALID_TOKEN;
}
final Calendar cal = Calendar.getInstance();
if (passToken.getExpiryDate().before(cal.getTime())) {
passwordTokenRepository.delete(passToken);
return TokenValidationResult.EXPIRED;
}
return TokenValidationResult.VALID;
}
/**
* Gets the users from session registry.
*
* @return the users from session registry
*/
public List<String> getUsersFromSessionRegistry() {
return sessionRegistry.getAllPrincipals().stream().filter((u) -> !sessionRegistry.getAllSessions(u, false).isEmpty()).map(o -> {
if (o instanceof User) {
return ((User) o).getEmail();
} else {
return o.toString();
}
}).collect(Collectors.toList());
}
/**
* Authenticates the given user without requiring a password. This method loads the user's details,
* generates their authorities from their roles and privileges, and stores these details in the
* security context and session.
*
* <p><strong>SECURITY WARNING:</strong> This is a potentially dangerous method as it authenticates
* a user without password verification. This method should only be used in specific controlled scenarios,
* such as after successful email verification or OAuth authentication.</p>
*
* @param user The user to authenticate without password verification
*/
public void authWithoutPassword(User user) {
log.debug("UserService.authWithoutPassword: authenticating user: {}", user);
if (user == null || user.getEmail() == null) {
log.error("Invalid user or user email");
return;
}
DSUserDetails userDetails;
try {
userDetails = dsUserDetailsService.loadUserByUsername(user.getEmail());
} catch (UsernameNotFoundException e) {
log.error("User not found: {}", user.getEmail(), e);
return;
}
// Generate authorities from user roles and privileges
Collection<? extends GrantedAuthority> authorities = authorityService.getAuthoritiesFromUser(user);
// Authenticate user
authenticateUser(userDetails, authorities);
// Store security context in session
storeSecurityContextInSession();
log.debug("UserService.authWithoutPassword: authenticated user: {}", user.getEmail());
}
/**
* Locks a user's account.
*
* @param email The email of the user.
*/
public void lockAccount(String email) {
log.debug("UserService.lockAccount: locking user account for: {}", email);
User user = userRepository.findByEmail(email);
if (user == null) {
log.error("UserService.lockAccount: user not found: {}", email);
throw new UsernameNotFoundException("User not found: " + email);
}
if (user.isLocked()) {
log.warn("UserService.lockAccount: user is already locked: {}", email);
return;
}
user.setLocked(true);
user.setLockedDate(new java.util.Date());
userRepository.save(user);
log.info("UserService.lockAccount: user account locked: {}", email);
}
/**
* Unlocks a user's account.
*
* @param email The email of the user.
*/
public void unlockAccount(String email) {
log.debug("UserService.unlockAccount: unlocking user account for: {}", email);
User user = userRepository.findByEmail(email);
if (user == null) {
log.error("UserService.unlockAccount: user not found: {}", email);
throw new UsernameNotFoundException("User not found: " + email);
}
if (!user.isLocked()) {
log.warn("UserService.unlockAccount: user is already unlocked: {}", email);
return;
}
user.setLocked(false);
user.setLockedDate(null);
userRepository.save(user);
log.info("UserService.unlockAccount: user account unlocked: {}", email);
}
/**
* Authenticates the user by creating an authentication object and setting it in the security context.
*
* @param userDetails The user details.
* @param authorities The list of authorities for the user.
*/
private void authenticateUser(DSUserDetails userDetails, Collection<? extends GrantedAuthority> authorities) {
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, authorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
/**
* Stores the current security context in the session.
*/
private void storeSecurityContextInSession() {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// Check if request attributes are available
if (servletRequestAttributes == null) {
log.error("Could not get request attributes");
return;
}
HttpServletRequest request = servletRequestAttributes.getRequest();
HttpSession session = request.getSession(true);
// Store the security context in the session
session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
}
}