Repository navigation
Expand file tree
/
Copy pathUserAuthorizationResource.java
More file actions
748 lines (689 loc) · 29.1 KB
/
Copy pathUserAuthorizationResource.java
File metadata and controls
748 lines (689 loc) · 29.1 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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/*******************************************************************************
* Copyright 2015 Defense Health Agency (DHA)
*
* If your use of this software does not include any GPLv2 components:
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ----------------------------------------------------------------------------
* If your use of this software includes any GPLv2 components:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*******************************************************************************/
package prerna.semoss.web.services.local.auth;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.json.JSONTokener;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.Response;
import prerna.auth.AccessToken;
import prerna.auth.AuthProvider;
import prerna.auth.PasswordRequirements;
import prerna.auth.User;
import prerna.auth.utils.SecurityNativeUserUtils;
import prerna.auth.utils.SecurityPasswordResetUtils;
import prerna.auth.utils.SecurityUserAccessKeyUtils;
import prerna.auth.utils.SecurityUserUtils;
import prerna.auth.utils.UserRegistrationEmailService;
import prerna.date.SemossDate;
import prerna.semoss.web.services.local.ResourceUtility;
import prerna.theme.AdminThemeUtils;
import prerna.usertracking.AuditEventType;
import prerna.usertracking.UserAuditTrailUtils;
import prerna.util.Constants;
import prerna.util.SocialPropertiesUtil;
import prerna.util.Utility;
import prerna.web.services.util.WebUtility;
@Path("/auth/user")
@PermitAll
public class UserAuthorizationResource {
private static final Logger classLogger = LogManager.getLogger(UserAuthorizationResource.class);
private static final String RESET_PASSWORD = "/resetPassword/";
private static final Set<String> PASSWORD_RESET_TYPES = Set.of(AuthProvider.NATIVE.name(),
AuthProvider.LDAP.name(), AuthProvider.LINOTP.name());
private static final String RESET_REQUESTED_MESSAGE = "If an account with that email exists, a password reset link has been sent to it.";
private static final String DEFAULT_PRODUCT_NAME = "SEMOSS";
final Executor passwordResetSender;
/**
* Creates the resource the way RESTEasy does, sending password reset emails on
* virtual threads.
*/
public UserAuthorizationResource() {
this(task -> Thread.ofVirtual().name("password-reset-email").start(task));
}
/**
* Creates the resource with the executor that stores the reset token and sends
* the reset email once the request has answered.
*
* @param passwordResetSender runs each password reset email
*/
UserAuthorizationResource(Executor passwordResetSender) {
this.passwordResetSender = passwordResetSender;
}
/**
* Edit user properties. The user information is passed in the request body as a
* JSON object or as a form parameter.
*
* @param request The HTTP request.
* @return A response indicating whether the user was edited successfully.
*/
@POST
@Path("/editUser")
@Produces("application/json")
@Consumes({ "application/json", "application/x-www-form-urlencoded" })
public Response editUser(@Context HttpServletRequest request) {
return ResourceUtility.respond(request, "edit their user details", user -> {
Map<String, Object> userInfo = null;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
try {
StringBuilder jsonBuffer = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
}
JSONObject jsonObj = new JSONObject(jsonBuffer.toString());
userInfo = jsonObj.toMap();
} catch (IOException | org.json.JSONException e) {
throw new IllegalArgumentException("Error reading request body.");
}
} else {
// for x-www-form-urlencoded, assume it's in a 'user' parameter as a JSON string
String userJson = WebUtility.inputSQLSanitizer(request.getParameter("user"));
try {
JSONObject jsonObj = new JSONObject(userJson);
userInfo = jsonObj.toMap();
} catch (org.json.JSONException e) {
throw new IllegalArgumentException("Error parsing user JSON from form data.");
}
}
boolean update = SecurityUserUtils.editUser(user, userInfo);
if (update) {
AccessToken authToken = AccessToken.copyToken(user.getAccessToken(user.getLogins().get(0)));
authToken.setName((String) userInfo.get("name"));
authToken.setEmail((String) userInfo.get("newEmail"));
// Refresh the authenticated session without reporting a new authentication.
user.setAccessToken(authToken);
WebUtility.loggingContextLoginEvent(request.getSession(false));
UserAuditTrailUtils.recordUserAdmin(user, null, AuditEventType.USER_UPDATE, authToken.getId(),
authToken.getProvider() == null ? null : authToken.getProvider().getLabel(),
authToken.getName(), null, null,
Map.of("changedFields", new ArrayList<>(userInfo.keySet()), "selfService", true));
}
return userInfo;
});
}
/**
* Delete a user.
*
* @param request The HTTP request.
* @return A response indicating whether the user was deleted successfully.
*/
@POST
@Produces("application/json")
@Path("/deleteUser")
@Consumes({ "application/json", "application/x-www-form-urlencoded" })
public Response deleteUser(@Context HttpServletRequest request) {
User user = null;
try {
user = ResourceUtility.getUser(request);
} catch (IllegalAccessException e) {
classLogger.error("Failed to delete user.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
// need to actually build out this logic...
return null;
}
/**
* Create a new user access key. The token name and description are passed in
* the request body as a JSON object or as form parameters.
*
* @param request The HTTP request.
* @return A response containing the new access key details.
*/
@POST
@Produces("application/json")
@Path("createUserAccessKey")
@Consumes({ "application/json", "application/x-www-form-urlencoded" })
public Response createUserAccessKey(@Context HttpServletRequest request) {
return ResourceUtility.respond(request, "create an access key", user -> {
AccessToken token = user.getPrimaryLoginToken();
boolean accessKeysAllowed = SocialPropertiesUtil.getInstance().accessKeysAllowed(token.getProvider());
if (!accessKeysAllowed) {
throw new IllegalAccessException(
"Creating access keys is not allowed. Please reach out to an administrator if you require this functionality");
}
String tokenName = null;
String tokenDescription = null;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
try {
StringBuilder jsonBuffer = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
}
JSONObject root = new JSONObject(jsonBuffer.toString());
tokenName = root.has("tokenName") ? root.getString("tokenName") : null;
tokenDescription = root.has("tokenDescription") ? root.getString("tokenDescription") : null;
} catch (IOException | org.json.JSONException e) {
throw new IllegalArgumentException("Error parsing JSON request body.");
}
} else {
tokenName = request.getParameter("tokenName");
tokenDescription = request.getParameter("tokenDescription");
}
tokenName = WebUtility.inputSQLSanitizer(tokenName);
if (tokenName != null && tokenName.length() > 255) {
throw new IllegalArgumentException("Token name must be less than 255 characters long");
}
tokenDescription = WebUtility.inputSQLSanitizer(tokenDescription);
if (tokenDescription != null && tokenDescription.length() > 500) {
throw new IllegalArgumentException("Token description must be less than 500 characters long");
}
return SecurityUserAccessKeyUtils.createUserAccessToken(token, tokenName, tokenDescription);
});
}
/**
* Delete a user access key. The access key is passed in the request body as a
* JSON object or as a form parameter.
*
* @param request The HTTP request.
* @return A response indicating whether the access key was deleted
* successfully.
*/
@POST
@Produces("application/json")
@Path("deleteUserAccessKey")
@Consumes({ "application/json", "application/x-www-form-urlencoded" })
public Response deleteUserAccessKey(@Context HttpServletRequest request) {
User user = null;
try {
user = ResourceUtility.getUser(request);
} catch (IllegalAccessException e) {
classLogger.error("Failed to delete user access key.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
Map<String, Object> retMap = new HashMap<>();
AccessToken token = user.getPrimaryLoginToken();
String accessKey = null;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
try {
StringBuilder jsonBuffer = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
}
JSONObject root = new JSONObject(jsonBuffer.toString());
accessKey = root.getString("accessKey");
} catch (IOException | org.json.JSONException e) {
classLogger.error("Failed to delete user access key.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Error parsing JSON request body.");
return WebUtility.getResponse(errorMap, 400);
}
} else {
accessKey = request.getParameter("accessKey");
}
accessKey = WebUtility.inputSQLSanitizer(accessKey);
if (accessKey == null || accessKey.isEmpty()) {
retMap.put(Constants.ERROR_MESSAGE, "accessKey parameter is not defined");
return WebUtility.getResponse(retMap, 400);
}
try {
boolean success = SecurityUserAccessKeyUtils.deleteUserAccessToken(token, accessKey);
retMap.put("success", success);
if (success) {
classLogger.info("User has deleted access key {}", accessKey);
return WebUtility.getResponse(retMap, 200);
} else {
classLogger.info("User could not delete access key {}", accessKey);
return WebUtility.getResponse(retMap, 400);
}
} catch (Exception e) {
classLogger.error("Error trying to delete access key {}", accessKey, e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 400);
}
}
/**
* Get the user access keys for the currently logged-in user.
*
* @param request The HTTP request.
* @return A response containing a list of access keys.
*/
@GET
@Path("/getUserAccessKeys")
@Produces("application/json")
public Response getUserAccessKeys(@Context HttpServletRequest request) {
return ResourceUtility.respond(request, "list their access keys",
user -> SecurityUserAccessKeyUtils.getUserAccessKeyInfo(user.getPrimaryLoginToken()));
}
/**
* Set up a password reset request for a user. When an account with the email
* exists for the login type, it is emailed a link to this application's reset
* page, built from the configured application URL; the request (a
* caller-supplied URL or the Host header) never decides where the reset token
* goes, and the subject comes from the active theme, not the caller. The answer
* is the same whether or not the account exists, so the endpoint cannot be used
* to find out which emails are registered. The token and the email are handled
* on a background thread after the answer, so an existing account does not take
* longer to answer than a missing one.
*
* @param context The servlet context.
* @param request The HTTP request.
* @return 200 with the same message whether or not the account exists; 400 for
* a missing email or a login type that cannot reset passwords; 401 when
* only administrators may change passwords; 500 when no mail server is
* configured
*/
@POST
@Produces("application/json")
@Path("/setupResetPassword")
@Consumes({ "application/json", "application/x-www-form-urlencoded" })
public Response setupResetPassword(@Context ServletContext context, @Context HttpServletRequest request) {
// do we allow users to change their password?
try {
if (!PasswordRequirements.getInstance().isAllowUserChangePassword()) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Only the administrator is allowed to change the user password");
return WebUtility.getResponse(errorMap, 401);
}
} catch (Exception e) {
classLogger.error("Failed to setup reset password.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
String email = null;
String type = null;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
try {
StringBuilder jsonBuffer = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
}
JSONObject root = new JSONObject(jsonBuffer.toString());
email = root.has("email") ? root.getString("email") : null;
type = root.has("type") ? root.getString("type") : null;
} catch (IOException | org.json.JSONException e) {
classLogger.error("Failed to setup reset password.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Error parsing JSON request body.");
return WebUtility.getResponse(errorMap, 400);
}
} else {
email = request.getParameter("email");
type = request.getParameter("type");
}
email = WebUtility.inputSQLSanitizer(email);
type = WebUtility.inputSQLSanitizer(type);
if (email == null || (email = email.trim()).isEmpty()) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "An email is required to reset a password");
return WebUtility.getResponse(errorMap, 400);
}
if (type == null || !PASSWORD_RESET_TYPES.contains(type)) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Passwords can only be reset for NATIVE, LDAP and LINOTP logins");
return WebUtility.getResponse(errorMap, 400);
}
if (SocialPropertiesUtil.getInstance().getSmtpEngine() == null) {
classLogger.error("Cannot send password reset emails, no mail server is configured");
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Password reset emails are not available on this server");
return WebUtility.getResponse(errorMap, 500);
}
if (!SecurityPasswordResetUtils.userEmailExists(email, type)) {
classLogger.info("Password reset requested for an email with no {} account", type);
return resetRequestedResponse();
}
String accountEmail = email;
String accountType = type;
passwordResetSender.execute(() -> sendResetEmail(accountEmail, accountType));
return resetRequestedResponse();
}
/**
* Stores a reset token for an existing account and emails it the reset link.
* It runs after the request has answered, so failures only reach the log; a
* token whose email did not go out is deleted.
*
* @param email the account's email
* @param type the account's login type
*/
private static void sendResetEmail(String email, String type) {
String uniqueToken = null;
try {
uniqueToken = SecurityPasswordResetUtils.allowUserResetPassword(email, type);
String resetEmailUrl = Utility.getApplicationUrl() + RESET_PASSWORD + "index.html?token=" + uniqueToken;
if (UserRegistrationEmailService.getInstance().sendPasswordResetRequestEmail(email, resetEmailUrl,
resetEmailSubject())) {
classLogger.info("User has requested a password reset for email = {}", email);
return;
}
classLogger.error("Failed to send the password reset email for a {} account", type);
} catch (Exception e) {
classLogger.error("Failed to set up the password reset for a {} account", type, e);
}
if (uniqueToken != null) {
try {
SecurityPasswordResetUtils.deleteToken(uniqueToken);
} catch (RuntimeException e) {
classLogger.error("Failed to delete an unsent password reset token", e);
}
}
}
/**
* Returns the one answer a password reset request gets, whether or not the
* account exists and whether or not its email went out.
*
* @return 200 with {@link #RESET_REQUESTED_MESSAGE}
*/
private static Response resetRequestedResponse() {
Map<String, Object> retMap = new HashMap<>();
retMap.put("success", true);
retMap.put("message", RESET_REQUESTED_MESSAGE);
return WebUtility.getResponse(retMap, 200);
}
/**
* Builds the subject of the password reset email from the active admin theme's
* name, the name the login page shows, so a caller cannot choose the wording of
* an email the server sends to someone else.
*
* @return the subject, such as {@code SEMOSS Reset Password Request}
*/
private static String resetEmailSubject() {
String name = null;
if (AdminThemeUtils.getActiveAdminTheme() instanceof Map<?, ?> theme
&& theme.get("THEME_MAP") instanceof String themeMap) {
try {
Object parsed = new JSONTokener(themeMap).nextValue();
// some servers store the theme encoded twice, as a JSON string of JSON
if (parsed instanceof String encoded) {
parsed = new JSONTokener(encoded).nextValue();
}
if (parsed instanceof JSONObject json && json.opt("name") instanceof String themeName) {
name = themeName;
}
} catch (org.json.JSONException e) {
classLogger.warn("The active admin theme map is not valid JSON", e);
}
}
// whitespace runs, line breaks included, become single spaces in a mail header
if (name == null || (name = name.replaceAll("\\s+", " ").trim()).isEmpty()) {
name = DEFAULT_PRODUCT_NAME;
}
return name + " Reset Password Request";
}
/**
* Reset the user's password using a reset token.
*
* @param context The servlet context.
* @param request The HTTP request.
* @return A response indicating whether the password was reset successfully.
*/
@POST
@Produces("application/json")
@Path("/resetPassword")
@Consumes({ "application/json", "application/x-www-form-urlencoded" })
public Response resetPassword(@Context ServletContext context, @Context HttpServletRequest request) {
// do we allow users to change their password?
try {
if (!PasswordRequirements.getInstance().isAllowUserChangePassword()) {
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Only the administrator is allowed to change the user password");
return WebUtility.getResponse(errorMap, 401);
}
} catch (Exception e) {
classLogger.error("Failed to reset password.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
String token = null;
String password = null;
String sender = null;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
try {
StringBuilder jsonBuffer = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
}
JSONObject root = new JSONObject(jsonBuffer.toString());
token = root.has("token") ? root.getString("token") : null;
password = root.has("password") ? root.getString("password") : null;
sender = root.has("sender") ? root.getString("sender") : null;
} catch (IOException | org.json.JSONException e) {
classLogger.error("Failed to reset password.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Error parsing JSON request body.");
return WebUtility.getResponse(errorMap, 400);
}
} else {
token = request.getParameter("token");
password = request.getParameter("password");
sender = request.getParameter("sender");
}
token = WebUtility.inputSQLSanitizer(token);
password = WebUtility.inputSQLSanitizer(password);
sender = WebUtility.inputSQLSanitizer(sender);
Map<String, Object> resetDetails = null;
try {
resetDetails = SecurityPasswordResetUtils.userResetPassword(token, password);
} catch (Exception e) {
classLogger.error("Failed to reset password.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
String userId = (String) resetDetails.get("userId");
String email = (String) resetDetails.get("email");
SemossDate dateAdded = (SemossDate) resetDetails.get("dateAdded");
classLogger.info("User has changed password for user id = {} for reset request on {} with email {}", userId,
dateAdded, email);
UserAuditTrailUtils.recordUserAdmin(null, null, AuditEventType.USER_PASSWORD_RESET, userId, null, null, null,
null, Map.of("method", "RESET_LINK"));
UserRegistrationEmailService.getInstance().sendPasswordResetSuccessEmail(email, sender);
Map<String, Object> retMap = new HashMap<>();
retMap.put("success", true);
retMap.put("userId", userId);
retMap.put("message", "Email has been sent to: " + email);
return WebUtility.getResponse(retMap, 200);
}
/**
* Set user metadata
*
* @param request
* @param form
* @return
*/
@POST
@Path("setUserMetadata")
@Produces("application/json")
public Response setUserMetadata(@Context HttpServletRequest request) {
return ResourceUtility.respond(request, "set their user metadata", user -> {
String metaKey = null;
Object metaValue = null;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
try {
StringBuilder jsonBuffer = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
}
JSONObject root = new JSONObject(jsonBuffer.toString());
metaKey = root.has("metaKey") ? root.getString("metaKey") : null;
boolean arrayValue = root.optJSONArray("metaValue") != null;
if (arrayValue) {
metaValue = root.getJSONArray("metaValue").toList();
} else {
metaValue = root.has("metaValue") ? root.getString("metaValue") : null;
}
} catch (IOException | org.json.JSONException e) {
throw new IllegalArgumentException("Error parsing JSON request body.");
}
} else {
Map<String, String[]> paramMap = request.getParameterMap();
metaKey = paramMap.get("metaKey") != null ? paramMap.get("metaKey")[0] : null;
metaValue = paramMap.get("metaValue") != null ? Arrays.asList(paramMap.get("metaValue")) : null;
}
if (metaKey == null) {
throw new IllegalArgumentException("Parameter metaKey cannot be null");
}
if (metaValue == null) {
throw new IllegalArgumentException("Parameter metaValue cannot be null");
}
SecurityUserUtils.updateUserMetadata(user, metaKey, metaValue);
Map<String, String> successMap = new HashMap<>();
successMap.put("userMetadata", "Metadata " + metaKey + " updated to " + metaValue);
return successMap;
});
}
/**
* Change the user's password. The current and new passwords are passed in the
* request body as a JSON object or as form parameters.
*
* @param context The servlet context.
* @param request The HTTP request.
* @return A response indicating whether the password was changed successfully.
*/
@POST
@Produces("application/json")
@Consumes({ "application/json", "application/x-www-form-urlencoded" })
@Path("/changePassword")
public Response changePassword(@Context ServletContext context, @Context HttpServletRequest request) {
User user = null;
String userId = null;
try {
user = ResourceUtility.getUser(request);
AuthProvider authProvider = user.getPrimaryLogin();
if (authProvider != AuthProvider.NATIVE) {
throw new IllegalArgumentException("Can only change password for NATIVE logins");
}
userId = user.getPrimaryLoginToken().getId();
String currentPassword = null;
String newPassword = null;
String contentType = request.getContentType();
if (contentType != null && contentType.startsWith("application/json")) {
// Handle JSON content
StringBuilder jsonBuffer = new StringBuilder();
String line;
try (BufferedReader reader = request.getReader()) {
while ((line = reader.readLine()) != null) {
jsonBuffer.append(line);
}
JSONObject root = new JSONObject(jsonBuffer.toString());
if (root == null || !root.has("currentPassword") || !root.has("newPassword")) {
Map<String, Object> retMap = new HashMap<>();
retMap.put("success", false);
retMap.put("userId", userId);
retMap.put("message",
"Missing required fields. Must have 'currentPassword' and 'newPassword' ");
return WebUtility.getResponse(retMap, 400);
}
currentPassword = root.getString("currentPassword");
newPassword = root.getString("newPassword");
} catch (IOException | org.json.JSONException e) {
classLogger.error("Failed to change password.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, "Error parsing JSON request body.");
return WebUtility.getResponse(errorMap, 400);
}
} else {
// Handle form data
currentPassword = request.getParameter("currentPassword");
newPassword = request.getParameter("newPassword");
}
currentPassword = WebUtility.inputSQLSanitizer(currentPassword);
if (SecurityNativeUserUtils.isCurrentPassword(userId, authProvider, currentPassword)) {
newPassword = WebUtility.inputSQLSanitizer(newPassword);
if (PasswordRequirements.getInstance().validatePassword(newPassword)) {
SecurityNativeUserUtils.performResetPassword(userId, newPassword);
classLogger.info("User has changed their password");
UserAuditTrailUtils.recordUserAdmin(null, null, AuditEventType.USER_PASSWORD_RESET, userId, null,
null, null, null, Map.of("method", "CHANGE_PASSWORD", "selfService", true));
Map<String, Object> retMap = new HashMap<>();
retMap.put("success", true);
retMap.put("userId", userId);
retMap.put("message", "User has changed the password for user id = " + userId);
classLogger.info("User has changed the password for user id = {}", userId);
return WebUtility.getResponse(retMap, 200);
} else {
classLogger.warn("User entered invalid new password");
Map<String, Object> retMap = new HashMap<>();
retMap.put("success", false);
retMap.put("userId", userId);
retMap.put("message", "The new password is not valid");
return WebUtility.getResponse(retMap, 401);
}
} else {
classLogger.warn("User entered the wrong password");
Map<String, Object> retMap = new HashMap<>();
retMap.put("success", false);
retMap.put("userId", userId);
retMap.put("message", "The current password for the user is wrong. Try again.");
return WebUtility.getResponse(retMap, 401);
}
} catch (Exception e) {
classLogger.error("Failed to change password.", e);
Map<String, String> errorMap = new HashMap<String, String>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
return WebUtility.getResponse(errorMap, 401);
}
}
}