-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathUserAPI.java
More file actions
453 lines (406 loc) · 18.5 KB
/
Copy pathUserAPI.java
File metadata and controls
453 lines (406 loc) · 18.5 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
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
package com.digitalsanctuary.spring.user.api;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
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.digitalsanctuary.spring.user.audit.AuditEvent;
import com.digitalsanctuary.spring.user.dto.PasswordDto;
import com.digitalsanctuary.spring.user.dto.PasswordResetRequestDto;
import com.digitalsanctuary.spring.user.dto.SavePasswordDto;
import com.digitalsanctuary.spring.user.dto.UserDto;
import com.digitalsanctuary.spring.user.dto.UserProfileUpdateDto;
import com.digitalsanctuary.spring.user.event.OnRegistrationCompleteEvent;
import com.digitalsanctuary.spring.user.exceptions.InvalidOldPasswordException;
import com.digitalsanctuary.spring.user.exceptions.UserAlreadyExistException;
import com.digitalsanctuary.spring.user.persistence.model.User;
import com.digitalsanctuary.spring.user.service.DSUserDetails;
import com.digitalsanctuary.spring.user.service.PasswordPolicyService;
import com.digitalsanctuary.spring.user.service.UserEmailService;
import com.digitalsanctuary.spring.user.service.UserService;
import com.digitalsanctuary.spring.user.util.JSONResponse;
import com.digitalsanctuary.spring.user.util.UserUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* REST API controller for user management operations.
* <p>
* Provides JSON endpoints for user registration, authentication, profile updates,
* password management, and account deletion. All endpoints are mapped under
* {@code /user} and return JSON responses.
* </p>
*
* @author Devon Hillard
* @see UserService
* @see UserEmailService
*/
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping(path = "/user", produces = "application/json")
public class UserAPI {
private final UserService userService;
private final UserEmailService userEmailService;
private final MessageSource messages;
private final ApplicationEventPublisher eventPublisher;
private final PasswordPolicyService passwordPolicyService;
@Value("${user.security.registrationPendingURI}")
private String registrationPendingURI;
@Value("${user.security.registrationSuccessURI}")
private String registrationSuccessURI;
@Value("${user.security.forgotPasswordPendingURI}")
private String forgotPasswordPendingURI;
/**
* Registers a new user account.
*
* @param userDto the user data transfer object containing user details
* @param request the HTTP servlet request
* @return a ResponseEntity containing a JSONResponse with the registration
* result
*/
@PostMapping("/registration")
public ResponseEntity<JSONResponse> registerUserAccount(@Valid @RequestBody UserDto userDto,
HttpServletRequest request) {
try {
validateUserDto(userDto);
// Password Policy Enforcement
// Note: Passing null for user during registration means password history
// is not checked (new users have no history). This is intentional - only
// existing users are checked against their own password history.
List<String> errors = passwordPolicyService.validate(null, userDto.getPassword(),
userDto.getEmail(), request.getLocale());
// Check if any password validation errors exist
if (!errors.isEmpty()) {
log.warn("Password validation failed: {}", errors);
return buildErrorResponse(String.join(" ", errors), 1, HttpStatus.BAD_REQUEST);
}
User registeredUser = userService.registerNewUserAccount(userDto);
publishRegistrationEvent(registeredUser, request);
logAuditEvent("Registration", "Success", "Registration Successful", registeredUser, request);
String nextURL = registeredUser.isEnabled() ? handleAutoLogin(registeredUser) : registrationPendingURI;
return buildSuccessResponse("Registration Successful!", nextURL);
} catch (UserAlreadyExistException ex) {
log.warn("User already exists with email: {}", userDto.getEmail());
logAuditEvent("Registration", "Failure", "User Already Exists", null, request);
return buildErrorResponse("An account already exists for the email address", 2, HttpStatus.CONFLICT);
} catch (Exception ex) {
log.error("Unexpected error during registration.", ex);
logAuditEvent("Registration", "Failure", ex.getMessage(), null, request);
return buildErrorResponse("System Error!", 5, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Resends the registration token. This is used when the user did not receive
* the initial registration email.
*
* @param userDto the user data transfer object containing user details
* @param request the HTTP servlet request
* @return a ResponseEntity containing a JSONResponse with the registration
* result
*/
@PostMapping("/resendRegistrationToken")
public ResponseEntity<JSONResponse> resendRegistrationToken(@Valid @RequestBody UserDto userDto,
HttpServletRequest request) {
User user = userService.findUserByEmail(userDto.getEmail());
if (user != null) {
if (user.isEnabled()) {
return buildErrorResponse("Account is already verified.", 1, HttpStatus.CONFLICT);
}
userEmailService.sendRegistrationVerificationEmail(user, UserUtils.getAppUrl(request));
logAuditEvent("Resend Reg Token", "Success", "Verification Email Resent", user, request);
return buildSuccessResponse("Verification Email Resent Successfully!", registrationPendingURI);
}
return buildErrorResponse("System Error!", 2, HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* Updates the user's profile (first name, last name). This is used when the
* user is logged in and wants to update their profile information.
*
* @param userDetails the authenticated user details
* @param profileUpdateDto the profile update DTO containing first and last name
* @param request the HTTP servlet request
* @param locale the locale
* @return a ResponseEntity containing a JSONResponse with the profile update
* result
*/
@PostMapping("/updateUser")
public ResponseEntity<JSONResponse> updateUserAccount(@AuthenticationPrincipal DSUserDetails userDetails,
@Valid @RequestBody UserProfileUpdateDto profileUpdateDto,
HttpServletRequest request, Locale locale) {
validateAuthenticatedUser(userDetails);
// Re-fetch user from database to ensure we have an attached entity
User user = userService.findUserByEmail(userDetails.getUser().getEmail());
if (user == null) {
log.error("User not found in database: {}", userDetails.getUser().getEmail());
return buildErrorResponse(messages.getMessage("message.user.not-found", null, "User not found", locale), 1, HttpStatus.BAD_REQUEST);
}
user.setFirstName(profileUpdateDto.getFirstName());
user.setLastName(profileUpdateDto.getLastName());
userService.saveRegisteredUser(user);
logAuditEvent("ProfileUpdate", "Success", "User profile updated", user, request);
return buildSuccessResponse(messages.getMessage("message.update-user.success", null, "Profile updated successfully", locale), null);
}
/**
* This is used when the user has forgotten their password and wants to reset
* their password. This will send an email to the user with a link to
* reset their password.
*
* @param passwordResetRequest the password reset request containing the email address
* @param request the HTTP servlet request
* @return a ResponseEntity containing a JSONResponse with the password reset
* email send result
*/
@PostMapping("/resetPassword")
public ResponseEntity<JSONResponse> resetPassword(@Valid @RequestBody PasswordResetRequestDto passwordResetRequest, HttpServletRequest request) {
User user = userService.findUserByEmail(passwordResetRequest.getEmail());
if (user != null) {
userEmailService.sendForgotPasswordVerificationEmail(user, UserUtils.getAppUrl(request));
logAuditEvent("Reset Password", "Success", "Password reset email sent", user, request);
}
return buildSuccessResponse("If account exists, password reset email has been sent!", forgotPasswordPendingURI);
}
/**
* Saves a new password after password reset token validation.
* This endpoint is called from the password reset form after the user
* clicks the link in their email and enters a new password.
*
* @param savePasswordDto DTO containing token and new password
* @param request HTTP servlet request
* @param locale locale for messages
* @return ResponseEntity with success or error response
*/
@PostMapping("/savePassword")
public ResponseEntity<JSONResponse> savePassword(@Valid @RequestBody SavePasswordDto savePasswordDto,
HttpServletRequest request, Locale locale) {
try {
// Validate passwords match
// Note: Using equals() is safe here - we're comparing two user-provided strings
// from the same request (not comparing against a stored secret), so timing attacks
// are not a concern. Constant-time comparison is only needed when comparing
// against stored credentials, which is handled by Spring's PasswordEncoder.
if (!savePasswordDto.getNewPassword().equals(savePasswordDto.getConfirmPassword())) {
return buildErrorResponse(messages.getMessage("message.password.mismatch", null, "Passwords do not match", locale), 1,
HttpStatus.BAD_REQUEST);
}
// Validate the reset token
UserService.TokenValidationResult tokenResult = userService
.validatePasswordResetToken(savePasswordDto.getToken());
if (tokenResult != UserService.TokenValidationResult.VALID) {
String messageKey = "auth.message." + tokenResult.getValue();
return buildErrorResponse(messages.getMessage(messageKey, null, "Invalid or expired token", locale), 2, HttpStatus.BAD_REQUEST);
}
// Get user by token
Optional<User> userOptional = userService.getUserByPasswordResetToken(savePasswordDto.getToken());
if (userOptional.isEmpty()) {
return buildErrorResponse(messages.getMessage("auth.message.invalid", null, "Invalid token", locale), 3,
HttpStatus.BAD_REQUEST);
}
User user = userOptional.get();
// Validate new password against policy
List<String> errors = passwordPolicyService.validate(user, savePasswordDto.getNewPassword(),
user.getEmail(), locale);
if (!errors.isEmpty()) {
log.warn("Password validation failed during reset for user {}: {}", user.getEmail(), errors);
return buildErrorResponse(String.join(" ", errors), 4, HttpStatus.BAD_REQUEST);
}
// Save the new password (this also saves to history)
userService.changeUserPassword(user, savePasswordDto.getNewPassword());
// Delete the reset token (it's been used)
userService.deletePasswordResetToken(savePasswordDto.getToken());
logAuditEvent("PasswordReset", "Success", "Password reset completed", user, request);
return buildSuccessResponse(messages.getMessage("message.reset-password.success", null, "Password has been reset successfully", locale),
"/user/login.html");
} catch (Exception ex) {
log.error("Unexpected error during password reset.", ex);
logAuditEvent("PasswordReset", "Failure", ex.getMessage(), null, request);
return buildErrorResponse("System Error!", 5, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Updates the user's password. This is used when the user is logged in and
* wants to change their password.
*
* @param userDetails the authenticated user details
* @param passwordDto the password data transfer object containing the old and
* new passwords
* @param request the HTTP servlet request
* @param locale the locale
* @return a ResponseEntity containing a JSONResponse with the password update
* result
*/
@PostMapping("/updatePassword")
public ResponseEntity<JSONResponse> updatePassword(@AuthenticationPrincipal DSUserDetails userDetails,
@Valid @RequestBody PasswordDto passwordDto, HttpServletRequest request, Locale locale) {
validateAuthenticatedUser(userDetails);
// Re-fetch user from database to ensure we have an attached entity
User user = userService.findUserByEmail(userDetails.getUser().getEmail());
if (user == null) {
log.error("User not found in database: {}", userDetails.getUser().getEmail());
return buildErrorResponse(messages.getMessage("message.user.not-found", null, "User not found", locale), 1, HttpStatus.BAD_REQUEST);
}
try {
// Verify old password is correct
if (!userService.checkIfValidOldPassword(user, passwordDto.getOldPassword())) {
throw new InvalidOldPasswordException("Invalid old password");
}
// Validate new password against policy
List<String> errors = passwordPolicyService.validate(user, passwordDto.getNewPassword(), user.getEmail(),
locale);
if (!errors.isEmpty()) {
log.warn("Password validation failed for user {}: {}", user.getEmail(), errors);
return buildErrorResponse(String.join(" ", errors), 2, HttpStatus.BAD_REQUEST);
}
// Save the new password (this also saves to history)
userService.changeUserPassword(user, passwordDto.getNewPassword());
logAuditEvent("PasswordUpdate", "Success", "User password updated", user, request);
return buildSuccessResponse(messages.getMessage("message.update-password.success", null, "Password updated successfully", locale), null);
} catch (InvalidOldPasswordException ex) {
logAuditEvent("PasswordUpdate", "Failure", "Invalid old password", user, request);
return buildErrorResponse(messages.getMessage("message.update-password.invalid-old", null, "Invalid old password", locale), 1,
HttpStatus.BAD_REQUEST);
} catch (Exception ex) {
log.error("Unexpected error during password update.", ex);
logAuditEvent("PasswordUpdate", "Failure", ex.getMessage(), user, request);
return buildErrorResponse("System Error!", 5, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
/**
* Deletes the user's account. This is used when the user wants to delete their
* account. This will either delete the account or disable it based
* on the configuration of the actuallyDeleteAccount property. After the account
* is disabled or deleted, the user will be logged out.
*
* @param userDetails the authenticated user details
* @param request the HTTP servlet request
* @return a ResponseEntity containing a JSONResponse with the account deletion
* result
*/
@DeleteMapping("/deleteAccount")
public ResponseEntity<JSONResponse> deleteAccount(@AuthenticationPrincipal DSUserDetails userDetails,
HttpServletRequest request) {
validateAuthenticatedUser(userDetails);
User user = userDetails.getUser();
userService.deleteOrDisableUser(user);
logAuditEvent("AccountDelete", "Success", "User account deleted", user, request);
logoutUser(request);
return buildSuccessResponse("Account Deleted", null);
}
// Helper Methods
/**
* Validates the user data transfer object.
*
* @param userDto the user data transfer object
*/
private void validateUserDto(UserDto userDto) {
if (isNullOrEmpty(userDto.getEmail())) {
throw new IllegalArgumentException("Email is required.");
}
if (isNullOrEmpty(userDto.getPassword())) {
throw new IllegalArgumentException("Password is required.");
}
}
/**
* Validates the authenticated user.
*
* @param userDetails the authenticated user details
*/
private void validateAuthenticatedUser(DSUserDetails userDetails) {
if (userDetails == null || userDetails.getUser() == null) {
throw new SecurityException("User not logged in.");
}
}
/**
* Handles the auto login of the user after registration.
*
* @param user the registered user
* @return the URI to redirect to after registration
*/
private String handleAutoLogin(User user) {
userService.authWithoutPassword(user);
return registrationSuccessURI;
}
/**
* Logs out the user.
*
* @param request the HTTP servlet request
*/
private void logoutUser(HttpServletRequest request) {
try {
SecurityContextHolder.clearContext();
request.logout();
} catch (ServletException e) {
log.warn("Logout failed during account deletion.", e);
}
}
/**
* Publishes a registration event.
*
* @param user the registered user
* @param request the HTTP servlet request
*/
private void publishRegistrationEvent(User user, HttpServletRequest request) {
String appUrl = UserUtils.getAppUrl(request);
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user, request.getLocale(), appUrl));
}
/**
* Logs an audit event.
*
* @param action the action performed
* @param status the status of the action
* @param message the message describing the action
* @param user the user involved in the action
* @param request the HTTP servlet request
*/
private void logAuditEvent(String action, String status, String message, User user, HttpServletRequest request) {
AuditEvent event = AuditEvent.builder().source(this).user(user).sessionId(request.getSession().getId())
.ipAddress(UserUtils.getClientIP(request))
.userAgent(request.getHeader("User-Agent")).action(action).actionStatus(status).message(message)
.build();
eventPublisher.publishEvent(event);
}
/**
* Checks if a string is null or empty.
*
* @param value
* @return true if the string is null or empty, false otherwise
*/
private boolean isNullOrEmpty(String value) {
return value == null || value.isEmpty();
}
/**
* Builds an error response.
*
* @param message
* @param code
* @param status
* @return a ResponseEntity containing a JSONResponse with the error response
*/
private ResponseEntity<JSONResponse> buildErrorResponse(String message, int code, HttpStatus status) {
return ResponseEntity.status(status)
.body(JSONResponse.builder().success(false).code(code).message(message).build());
}
/**
* Builds a success response.
*
* @param message
* @param redirectUrl
* @return a ResponseEntity containing a JSONResponse with the success response
*/
private ResponseEntity<JSONResponse> buildSuccessResponse(String message, String redirectUrl) {
return ResponseEntity
.ok(JSONResponse.builder().success(true).code(0).message(message).redirectUrl(redirectUrl).build());
}
}