• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmrs / openmrs-core / 43497228006

13 Nov 2026 07:48PM UTC coverage: 69.295% (+0.3%) from 68.956%
43497228006

push

github

ibacher
Refine how UserService saves users, roles and user properties (#6831)

552 of 595 new or added lines in 14 files covered. (92.77%)

9 existing lines in 5 files now uncovered.

26888 of 38802 relevant lines covered (69.3%)

0.69 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.51
/api/src/main/java/org/openmrs/api/impl/UserServiceImpl.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 *
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs.api.impl;
11

12
import java.util.ArrayList;
13
import java.util.Collection;
14
import java.util.Collections;
15
import java.util.Date;
16
import java.util.HashMap;
17
import java.util.HashSet;
18
import java.util.List;
19
import java.util.Locale;
20
import java.util.Map;
21
import java.util.Objects;
22
import java.util.Optional;
23
import java.util.Properties;
24
import java.util.Set;
25
import java.util.TreeSet;
26
import java.util.function.Consumer;
27
import java.util.stream.Collectors;
28

29
import org.apache.commons.lang3.RandomStringUtils;
30
import org.apache.commons.lang3.StringUtils;
31
import org.hibernate.collection.spi.PersistentCollection;
32
import org.openmrs.Person;
33
import org.openmrs.Privilege;
34
import org.openmrs.Role;
35
import org.openmrs.User;
36
import org.openmrs.annotation.Authorized;
37
import org.openmrs.annotation.Logging;
38
import org.openmrs.api.APIException;
39
import org.openmrs.api.AdministrationService;
40
import org.openmrs.api.CannotDeleteRoleWithChildrenException;
41
import org.openmrs.api.InvalidActivationKeyException;
42
import org.openmrs.api.UserService;
43
import org.openmrs.api.cache.RolePrivilegeCache;
44
import org.openmrs.api.context.Context;
45
import org.openmrs.api.db.DAOException;
46
import org.openmrs.api.db.LoginCredential;
47
import org.openmrs.api.db.StoredRole;
48
import org.openmrs.api.db.UserDAO;
49
import org.openmrs.messagesource.MessageSourceService;
50
import org.openmrs.notification.MessageException;
51
import org.openmrs.patient.impl.LuhnIdentifierValidator;
52
import org.openmrs.util.LocaleUtility;
53
import org.openmrs.util.OpenmrsConstants;
54
import org.openmrs.util.OpenmrsUtil;
55
import org.openmrs.util.PrivilegeConstants;
56
import org.openmrs.util.RoleConstants;
57
import org.openmrs.util.Security;
58
import org.slf4j.Logger;
59
import org.slf4j.LoggerFactory;
60
import org.springframework.cache.annotation.CacheEvict;
61
import org.springframework.transaction.annotation.Transactional;
62
import org.springframework.transaction.support.TransactionSynchronization;
63
import org.springframework.transaction.support.TransactionSynchronizationManager;
64

65
/**
66
 * Default implementation of the user service. This class should not be used on its own. The current
67
 * OpenMRS implementation should be fetched from the Context
68
 *
69
 * @see org.openmrs.api.UserService
70
 * @see org.openmrs.api.context.Context
71
 */
72
@Transactional
73
public class UserServiceImpl extends BaseOpenmrsService implements UserService {
74
        
75
        private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
1 ✔
76
        
77
        protected UserDAO dao;
78

79
        private RolePrivilegeCache rolePrivilegeCache;
80

81
        private static final int MAX_VALID_TIME = 12 * 60 * 60 * 1000; //Period of 12 hours
82
        
83
        private static final int MIN_VALID_TIME = 60 * 1000; //Period of 1 minute
84
        
85
        private static final int DEFAULT_VALID_TIME = 10 * 60 * 1000; //Default time of 10 minute
86
        
87
        public UserServiceImpl() {
1 ✔
88
        }
1 ✔
89
        
90
        public void setUserDAO(UserDAO dao) {
91
                this.dao = dao;
1 ✔
92
        }
1 ✔
93
        
94
        public void setRolePrivilegeCache(RolePrivilegeCache rolePrivilegeCache) {
95
                this.rolePrivilegeCache = rolePrivilegeCache;
1 ✔
96
        }
1 ✔
97
        
98
        /**
99
         * Thread-scoped permit that marks the current thread as executing inside the user service. The
100
         * {@link UserDAO} implementation consults {@link #isPermitted()} before mutating a user's password
101
         * or login credential, so that those mutations can only happen on a code path that went through
102
         * {@link UserService} rather than straight to the DAO.
103
         * <p>
104
         * The permit is raised and lowered by {@code UserServiceImpl} alone: {@code enter()} and
105
         * {@code exit()} are private, and only a nestmate of {@code UserServiceImpl} can reach them. It is
106
         * re-entrant, so a service call nested inside another one leaves the permit raised until the
107
         * outermost call returns.
108
         * <p>
109
         * Reflection can still forge a permit. That is acceptable: this guards against accidentally routing
110
         * credential changes around the service layer, not against hostile code sharing the JVM, which
111
         * could already reach the DAO by other means.
112
         *
113
         * @since 2.8.10
114
         */
115
        public static final class UserPasswordGuard {
116

117
                private static final ThreadLocal<Integer> DEPTH = new ThreadLocal<>();
1 ✔
118

119
                private UserPasswordGuard() {
120
                }
121

122
                private static void enter() {
123
                        Integer depth = DEPTH.get();
1 ✔
124
                        DEPTH.set(depth == null ? 1 : depth + 1);
1 ✔
125
                }
1 ✔
126

127
                private static void exit() {
128
                        Integer depth = DEPTH.get();
1 ✔
129
                        if (depth == null || depth <= 1) {
1 ✔
130
                                DEPTH.remove();
1 ✔
131
                        } else {
132
                                DEPTH.set(depth - 1);
×
133
                        }
134
                }
1 ✔
135

136
                /**
137
                 * @return true if the calling thread is currently executing inside the user service
138
                 */
139
                public static boolean isPermitted() {
140
                        return DEPTH.get() != null;
1 ✔
141
                }
142
        }
143

144
        /**
145
         * The service's single entry point to {@link UserDAO#saveUser(User, String)}, raising the permit
146
         * that the DAO requires of anything that can change a password.
147
         *
148
         * @see UserPasswordGuard
149
         */
150
        private User daoSaveUser(User user, String password) {
151
                UserPasswordGuard.enter();
1 ✔
152
                try {
153
                        return dao.saveUser(user, password);
1 ✔
154
                } finally {
155
                        UserPasswordGuard.exit();
1 ✔
156
                }
157
        }
158

159
        /**
160
         * The service's single entry point to {@link UserDAO#changePassword(User, String)}.
161
         *
162
         * @see UserPasswordGuard
163
         */
164
        private void daoChangePassword(User user, String newPassword) {
165
                UserPasswordGuard.enter();
1 ✔
166
                try {
167
                        dao.changePassword(user, newPassword);
1 ✔
168
                } finally {
169
                        UserPasswordGuard.exit();
1 ✔
170
                }
171
        }
1 ✔
172

173
        /**
174
         * The service's single entry point to {@link UserDAO#changeHashedPassword(User, String, String)}.
175
         *
176
         * @see UserPasswordGuard
177
         */
178
        private void daoChangeHashedPassword(User user, String hashedPassword, String salt) {
179
                UserPasswordGuard.enter();
1 ✔
180
                try {
181
                        dao.changeHashedPassword(user, hashedPassword, salt);
1 ✔
182
                } finally {
183
                        UserPasswordGuard.exit();
1 ✔
184
                }
185
        }
1 ✔
186

187
        /**
188
         * @return the validTime for which the password reset activation key will be valid
189
         */
190
        private int getValidTime() {
191
                String validTimeGp = Context.getAdministrationService()
1 ✔
192
                        .getGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_VALIDTIME);
1 ✔
193
                final int validTime = StringUtils.isBlank(validTimeGp) ? DEFAULT_VALID_TIME : Integer.parseInt(validTimeGp);
1 ✔
194
                //if valid time is less that a minute or greater than 12hrs reset valid time to 1 minutes else set it to the required time.
195
                return (validTime < MIN_VALID_TIME) || (validTime > MAX_VALID_TIME) ? DEFAULT_VALID_TIME : validTime;
1 ✔
196
        }
197
        
198
        /**
199
         * @see org.openmrs.api.UserService#createUser(org.openmrs.User, java.lang.String)
200
         */
201
        @Override
202
        public User createUser(User user, String password) throws APIException {
203
                if (user.getUserId() != null) {
1 ✔
204
                        throw new APIException("This method can be used for only creating new users");
1 ✔
205
                }
206
                
207
                Context.requirePrivilege(PrivilegeConstants.ADD_USERS);
1 ✔
208

209
                useStoredRoles(user);
1 ✔
210
                checkPrivileges(user);
1 ✔
211
                
212
                // if a password wasn't supplied, throw an error
213
                if (password == null || password.isEmpty()) {
1 ✔
214
                        throw new APIException("User.creating.password.required", (Object[]) null);
×
215
                }
216
                
217
                if (hasDuplicateUsername(user)) {
1 ✔
218
                        throw new DAOException("Username " + user.getUsername() + " or system id " + user.getSystemId()
1 ✔
219
                                + " is already in use.");
220
                }
221
                
222
                // TODO Check required fields for user!!
223
                OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
1 ✔
224

225
                return daoSaveUser(user, password);
1 ✔
226
        }
227
        
228
        /**
229
         * @see org.openmrs.api.UserService#getUser(java.lang.Integer)
230
         */
231
        @Override
232
        @Transactional(readOnly = true)
233
        public User getUser(Integer userId) throws APIException {
234
                return dao.getUser(userId);
1 ✔
235
        }
236
        
237
        /**
238
         * @see org.openmrs.api.UserService#getUserByUsername(java.lang.String)
239
         */
240
        @Override
241
        @Transactional(readOnly = true)
242
        public User getUserByUsername(String username) throws APIException {
243
                return dao.getUserByUsername(username);
1 ✔
244
        }
245
        
246
        /**
247
         * @see org.openmrs.api.UserService#hasDuplicateUsername(org.openmrs.User)
248
         */
249
        @Override
250
        @Transactional(readOnly = true)
251
        public boolean hasDuplicateUsername(User user) throws APIException {
252
                return dao.hasDuplicateUsername(user.getUsername(), user.getSystemId(), user.getUserId());
1 ✔
253
        }
254
        
255
        /**
256
         * @see org.openmrs.api.UserService#getUsersByRole(org.openmrs.Role)
257
         */
258
        @Override
259
        @Transactional(readOnly = true)
260
        public List<User> getUsersByRole(Role role) throws APIException {
261
                List<Role> roles = new ArrayList<>();
1 ✔
262
                roles.add(role);
1 ✔
263
                
264
                return Context.getUserService().getUsers(null, roles, false);
1 ✔
265
        }
266
        
267
        /**
268
         * @see org.openmrs.api.UserService#saveUser(org.openmrs.User)
269
         */
270
        @Override
271
        @CacheEvict(value = "userSearchLocales", allEntries = true)
272
        public User saveUser(User user) throws APIException {
273
                if (user.getUserId() == null) {
1 ✔
274
                        throw new APIException("This method can be called only to update existing users");
×
275
                }
276
                
277
                Context.requirePrivilege(PrivilegeConstants.EDIT_USERS);
1 ✔
278
                // checked against the roles as stored, since the save may be what removes superuser status
279
                requireCanChangeSuperUser(user.getUserId());
1 ✔
280

281
                useStoredRoles(user);
1 ✔
282
                checkPrivileges(user);
1 ✔
283
                
284
                if (hasDuplicateUsername(user)) {
1 ✔
285
                        throw new DAOException("Username " + user.getUsername() + " or system id " + user.getSystemId()
×
286
                                + " is already in use.");
287
                }
288

289
                User saved = daoSaveUser(user, null);
1 ✔
290
                if (user.getUserId().equals(Context.getUserContext().getAuthenticatedUserId())) {
1 ✔
291
                        refreshAuthenticatedUserOnCommit();
1 ✔
292
                }
293
                return saved;
1 ✔
294
        }
295

296
        /**
297
         * Privilege checks use the roles the authenticated user held when loaded, so once a change to their
298
         * own roles is stored, they are loaded again. Other sessions of the same user keep the roles they
299
         * loaded until they're refreshed.
300
         */
301
        private void refreshAuthenticatedUserOnCommit() {
302
                if (!TransactionSynchronizationManager.isSynchronizationActive()) {
1 ✔
NEW
303
                        Context.refreshAuthenticatedUser();
×
NEW
304
                        return;
×
305
                }
306
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
1 ✔
307

308
                        @Override
309
                        public void afterCommit() {
310
                                Context.refreshAuthenticatedUser();
1 ✔
311
                        }
1 ✔
312
                });
313
        }
1 ✔
314
        
315
        public User voidUser(User user, String reason) throws APIException {
316
                return Context.getUserService().retireUser(user, reason);
×
317
        }
318
        
319
        /**
320
         * @see org.openmrs.api.UserService#retireUser(org.openmrs.User, java.lang.String)
321
         */
322
        @Override
323
        public User retireUser(User user, String reason) throws APIException {
324
                user.setRetired(true);
1 ✔
325
                user.setRetireReason(reason);
1 ✔
326
                user.setRetiredBy(Context.getAuthenticatedUser());
1 ✔
327
                user.setDateRetired(new Date());
1 ✔
328
                
329
                return saveUser(user);
1 ✔
330
        }
331
        
332
        public User unvoidUser(User user) throws APIException {
333
                return Context.getUserService().unretireUser(user);
×
334
        }
335
        
336
        /**
337
         * @see org.openmrs.api.UserService#unretireUser(org.openmrs.User)
338
         */
339
        @Override
340
        public User unretireUser(User user) throws APIException {
341
                user.setRetired(false);
1 ✔
342
                user.setRetireReason(null);
1 ✔
343
                user.setRetiredBy(null);
1 ✔
344
                user.setDateRetired(null);
1 ✔
345
                
346
                return saveUser(user);
1 ✔
347
        }
348
        
349
        /**
350
         * @see org.openmrs.api.UserService#getAllUsers()
351
         */
352
        @Override
353
        @Transactional(readOnly = true)
354
        public List<User> getAllUsers() throws APIException {
355
                return dao.getAllUsers();
1 ✔
356
        }
357
        
358
        /**
359
         * @see org.openmrs.api.UserService#getAllPrivileges()
360
         */
361
        @Override
362
        @Transactional(readOnly = true)
363
        public List<Privilege> getAllPrivileges() throws APIException {
364
                return dao.getAllPrivileges();
1 ✔
365
        }
366
        
367
        /**
368
         * @see org.openmrs.api.UserService#getPrivilege(java.lang.String)
369
         */
370
        @Override
371
        @Transactional(readOnly = true)
372
        public Privilege getPrivilege(String p) throws APIException {
373
                return dao.getPrivilege(p);
1 ✔
374
        }
375
        
376
        /**
377
         * @see org.openmrs.api.UserService#purgePrivilege(org.openmrs.Privilege)
378
         */
379
        @Override
380
        public void purgePrivilege(Privilege privilege) throws APIException {
381
                if (OpenmrsUtil.getCorePrivileges().keySet().contains(privilege.getPrivilege())) {
1 ✔
382
                        throw new APIException("Privilege.cannot.delete.core", (Object[]) null);
1 ✔
383
                }
384
                
385
                dao.deletePrivilege(privilege);
1 ✔
386
                rolePrivilegeCache.clear();
1 ✔
387
        }
1 ✔
388
        
389
        /**
390
         * @see org.openmrs.api.UserService#savePrivilege(org.openmrs.Privilege)
391
         */
392
        @Override
393
        public Privilege savePrivilege(Privilege privilege) throws APIException {
394
                Privilege saved = dao.savePrivilege(privilege);
1 ✔
395
                rolePrivilegeCache.clear();
1 ✔
396
                return saved;
1 ✔
397
        }
398
        
399
        /**
400
         * @see org.openmrs.api.UserService#getAllRoles()
401
         */
402
        @Override
403
        @Transactional(readOnly = true)
404
        public List<Role> getAllRoles() throws APIException {
405
                return dao.getAllRoles();
1 ✔
406
        }
407
        
408
        /**
409
         * @see org.openmrs.api.UserService#getRole(java.lang.String)
410
         */
411
        @Override
412
        @Transactional(readOnly = true)
413
        public Role getRole(String r) throws APIException {
414
                return dao.getRole(r);
1 ✔
415
        }
416
        
417
        /**
418
         * @see org.openmrs.api.UserService#purgeRole(org.openmrs.Role)
419
         */
420
        @Override
421
        public void purgeRole(Role role) throws APIException {
422
                if (role == null || role.getRole() == null) {
1 ✔
423
                        return;
1 ✔
424
                }
425
                
426
                if (OpenmrsUtil.getCoreRoles().keySet().contains(role.getRole())) {
1 ✔
427
                        throw new APIException("Role.cannot.delete.core", (Object[]) null);
1 ✔
428
                }
429
                
430
                if (role.hasChildRoles()) {
1 ✔
431
                        throw new CannotDeleteRoleWithChildrenException();
1 ✔
432
                }
433
                
434
                dao.deleteRole(role);
1 ✔
435
                rolePrivilegeCache.clear();
1 ✔
436
        }
1 ✔
437
        
438
        /**
439
         * @see org.openmrs.api.UserService#saveRole(org.openmrs.Role)
440
         */
441
        @Override
442
        public Role saveRole(Role role) throws APIException {
443
                // Validated before the role is changed, so a rejected change is never left on a loaded role.
444
                // The database may match a name loosely (on MySQL, ignoring accents or trailing spaces), and
445
                // saving under such a name would overwrite the role stored under the other spelling.
446
                StoredRole sameName = role.getRole() == null ? null : dao.getStoredRole(role.getRole());
1 ✔
447
                if (sameName != null && !sameName.getName().equals(role.getRole())) {
1 ✔
448
                        throw new APIException("Role.duplicateName", (Object[]) null);
1 ✔
449
                }
450
                RoleAssignments.requireCanChangeSuperuser("Role.superuser.privilegeRequired", Collections.singleton(role.getRole()),
1 ✔
451
                    dao::getStoredRole);
452
                Set<String> unflushed = new HashSet<>();
1 ✔
453
                Set<Role> parents = loadStoredRoles(role.getInheritedRoles(), unflushed);
1 ✔
454
                if (!unflushed.isEmpty()) {
1 ✔
455
                        // the checks read roles as stored, so a parent saved earlier in this transaction is flushed
456
                        // first, once the role holds nothing but managed instances; the flush is checked by
457
                        // RoleWriteGuardListener, so a rejected change can be left on the role only in this case
458
                        useStoredContents(role, parents);
1 ✔
459
                        Context.flushSession();
1 ✔
460
                }
461
                RoleAssignments.requireNoInheritanceCycle(role.getRole(), roleNames(parents), dao::getStoredRole);
1 ✔
462
                checkPrivileges(role, parents);
1 ✔
463
                if (unflushed.isEmpty()) {
1 ✔
464
                        useStoredContents(role, parents);
1 ✔
465
                }
466

467
                Role saved = dao.saveRole(role);
1 ✔
468
                rolePrivilegeCache.clear();
1 ✔
469
                return saved;
1 ✔
470
        }
471
        
472
        /**
473
         * @see org.openmrs.api.UserService#changePassword(java.lang.String, java.lang.String)
474
         */
475
        @Override
476
        public void changePassword(String oldPassword, String newPassword) throws APIException {
477
                User user = Context.getAuthenticatedUser();
1 ✔
478
                changePassword(user, oldPassword, newPassword);
1 ✔
479
        }
1 ✔
480
        
481
        /**
482
         * @see org.openmrs.api.UserService#changeHashedPassword(User, String, String)
483
         */
484
        @Override
485
        public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException {
486
                requireCanChangeSuperUser(user.getUserId());
1 ✔
487
                daoChangeHashedPassword(user, hashedPassword, salt);
1 ✔
488
        }
1 ✔
489
        
490
        /**
491
         * @see org.openmrs.api.UserService#changeQuestionAnswer(User, String, String)
492
         */
493
        @Override
494
        public void changeQuestionAnswer(User u, String question, String answer) throws APIException {
495
                requireCanChangeSuperUser(u.getUserId());
1 ✔
496
                dao.changeQuestionAnswer(u, question, answer);
1 ✔
497
        }
1 ✔
498
        
499
        /**
500
         * @see org.openmrs.api.UserService#changeQuestionAnswer(java.lang.String, java.lang.String,
501
         * java.lang.String)
502
         */
503
        @Override
504
        public void changeQuestionAnswer(String pw, String q, String a) {
505
                dao.changeQuestionAnswer(pw, q, a);
1 ✔
506
        }
1 ✔
507
        
508
        /**
509
         * @see org.openmrs.api.UserService#isSecretAnswer(org.openmrs.User, java.lang.String)
510
         */
511
        @Override
512
        @Transactional(readOnly = true)
513
        public boolean isSecretAnswer(User u, String answer) {
514
                return dao.isSecretAnswer(u, answer);
1 ✔
515
        }
516
        
517
        /**
518
         * @see org.openmrs.api.UserService#getUsersByName(java.lang.String, java.lang.String, boolean)
519
         */
520
        @Override
521
        @Transactional(readOnly = true)
522
        public List<User> getUsersByName(String givenName, String familyName, boolean includeVoided) throws APIException {
523
                return dao.getUsersByName(givenName, familyName, includeVoided);
1 ✔
524
        }
525
        
526
        /**
527
         * @see org.openmrs.api.UserService#getUsersByPerson(org.openmrs.Person, boolean)
528
         */
529
        @Override
530
        @Transactional(readOnly = true)
531
        public List<User> getUsersByPerson(Person person, boolean includeRetired) throws APIException {
532
                return dao.getUsersByPerson(person, includeRetired);
1 ✔
533
        }
534
        
535
        /**
536
         * @see org.openmrs.api.UserService#getUsers(java.lang.String, java.util.List, boolean)
537
         */
538
        @Override
539
        @Transactional(readOnly = true)
540
        public List<User> getUsers(String nameSearch, List<Role> roles, boolean includeVoided) throws APIException {
541
                return Context.getUserService().getUsers(nameSearch, roles, includeVoided, null, null);
1 ✔
542
        }
543
        
544
        /**
545
         * Checks that the authenticated user may hand out the user's roles (see {@link RoleAssignments}).
546
         *
547
         * @param user user that has privileges
548
         */
549
        private void checkPrivileges(User user) {
550
                List<String> requiredPrivs = new ArrayList<>(
1 ✔
551
                        RoleAssignments.missingPrivileges(roleNames(user.getRoles()), dao::getStoredRole));
1 ✔
552
                if (requiredPrivs.size() == 1) {
1 ✔
553
                        throw new APIException("User.you.must.have.privilege", new Object[] { requiredPrivs.get(0) });
1 ✔
554
                } else if (requiredPrivs.size() > 1) {
1 ✔
555
                        throw new APIException("User.you.must.have.privileges", new Object[] { String.join(", ", requiredPrivs) });
1 ✔
556
                }
557
        }
1 ✔
558

559
        /**
560
         * Returns the managed role stored under each role's name or, for a role saved earlier in this
561
         * transaction but not yet flushed, the session's instance of it. A caller-supplied role must never
562
         * be checked or persisted in place of the managed one, since its privileges and parents need not
563
         * match.
564
         *
565
         * @param unflushed receives the names of the roles that are not yet flushed
566
         * @throws APIException if there is no such role
567
         */
568
        private Set<Role> loadStoredRoles(Collection<Role> roles, Set<String> unflushed) {
569
                Set<Role> loaded = new HashSet<>();
1 ✔
570
                for (String name : roleNames(roles)) {
1 ✔
571
                        StoredRole stored = dao.getStoredRole(name);
1 ✔
572
                        Role role = dao.getRole(stored == null ? name : stored.getName());
1 ✔
573
                        if (role == null) {
1 ✔
574
                                throw new APIException("Role.unknown", new Object[] { name });
1 ✔
575
                        }
576
                        if (stored == null) {
1 ✔
577
                                unflushed.add(name);
1 ✔
578
                        }
579
                        loaded.add(role);
1 ✔
580
                }
1 ✔
581
                return loaded;
1 ✔
582
        }
583

584
        /**
585
         * Puts the managed instance of each of the user's roles in place of the caller's. The checks read
586
         * roles as stored, so a role saved earlier in this transaction is then flushed, which runs
587
         * {@link org.openmrs.api.db.hibernate.RoleWriteGuardListener}'s checks on the flush. That flush
588
         * only happens once the user holds nothing but managed roles, which the guard requires.
589
         */
590
        private void useStoredRoles(User user) {
591
                Set<String> unflushed = new HashSet<>();
1 ✔
592
                user.setRoles(replaceContents(user.getRoles(), loadStoredRoles(user.getRoles(), unflushed)));
1 ✔
593
                if (!unflushed.isEmpty()) {
1 ✔
594
                        Context.flushSession();
1 ✔
595
                }
596
        }
1 ✔
597

598
        /**
599
         * Puts the managed instance of each of the role's privileges and inherited roles in place of the
600
         * caller's
601
         */
602
        private void useStoredContents(Role role, Set<Role> parents) {
603
                if (role.getPrivileges() != null) {
1 ✔
604
                        role.setPrivileges(replaceContents(role.getPrivileges(), loadStoredPrivileges(role.getPrivileges())));
1 ✔
605
                }
606
                role.setInheritedRoles(replaceContents(role.getInheritedRoles(), parents));
1 ✔
607
        }
1 ✔
608

609
        /**
610
         * Returns the managed privilege stored under each privilege's name, as {@link #loadStoredRoles}
611
         * does for roles, since a role may only hold privileges the session manages.
612
         *
613
         * @throws APIException if there is no such privilege
614
         */
615
        private Set<Privilege> loadStoredPrivileges(Collection<Privilege> privileges) {
616
                Set<Privilege> loaded = new HashSet<>();
1 ✔
617
                privileges.stream().filter(Objects::nonNull).map(Privilege::getPrivilege).filter(Objects::nonNull).distinct()
1 ✔
618
                        .forEach(name -> {
1 ✔
619
                                Privilege stored = dao.getPrivilege(name);
1 ✔
620
                                if (stored == null) {
1 ✔
621
                                        throw new APIException("Privilege.unknown", new Object[] { name });
1 ✔
622
                                }
623
                                loaded.add(stored);
1 ✔
624
                        });
1 ✔
625
                return loaded;
1 ✔
626
        }
627

628
        /**
629
         * Makes {@code current} hold exactly {@code stored}. A collection Hibernate tracks is changed in
630
         * place, and only if it doesn't already hold the same instances, since replacing or rewriting it
631
         * would make Hibernate rewrite its rows. Any other set, which may be immutable, is simply replaced.
632
         *
633
         * @return {@code current}, or {@code stored} if {@code current} isn't a collection Hibernate tracks
634
         */
635
        private static <T> Set<T> replaceContents(Set<T> current, Set<T> stored) {
636
                if (!(current instanceof PersistentCollection)) {
1 ✔
637
                        return stored;
1 ✔
638
                }
639
                boolean same = current.size() == stored.size()
1 ✔
640
                        && current.stream().allMatch(r -> stored.stream().anyMatch(s -> s == r));
1 ✔
641
                if (!same) {
1 ✔
642
                        current.clear();
1 ✔
643
                        current.addAll(stored);
1 ✔
644
                }
645
                return current;
1 ✔
646
        }
647

648
        private static Set<String> roleNames(Collection<Role> roles) {
649
                Set<String> names = new HashSet<>();
1 ✔
650
                if (roles != null) {
1 ✔
651
                        roles.stream().filter(Objects::nonNull).map(Role::getRole).filter(Objects::nonNull).forEach(names::add);
1 ✔
652
                }
653
                return names;
1 ✔
654
        }
655
        
656
        /**
657
         * @see org.openmrs.api.UserService#setUserProperty(User, String, String)
658
         */
659
        @Override
660
        @CacheEvict(value = "userSearchLocales", allEntries = true)
661
        public User setUserProperty(User user, String key, String value) {
662
                if (user != null) {
1 ✔
663
                        requireCanEditProperties(user);
1 ✔
664
                        saveStoredUserProperties(user.getUserId(), properties -> properties.put(key, value));
1 ✔
665
                        user.setUserProperty(key, value);
1 ✔
666
                }
667
                
668
                return user;
1 ✔
669
        }
670
        
671
        /**
672
         * @see org.openmrs.api.UserService#removeUserProperty(org.openmrs.User, java.lang.String)
673
         */
674
        @Override
675
        @CacheEvict(value = "userSearchLocales", allEntries = true)
676
        public User removeUserProperty(User user, String key) {
677
                if (user != null) {
1 ✔
678
                        requireCanEditProperties(user);
1 ✔
679
                        saveStoredUserProperties(user.getUserId(), properties -> properties.remove(key));
1 ✔
680
                        user.removeUserProperty(key);
1 ✔
681
                }
682
                
683
                return user;
1 ✔
684
        }
685

686
        private void requireCanEditProperties(User user) {
687
                if (isAuthenticatedUser(user.getUserId())) {
1 ✔
688
                        return;
1 ✔
689
                }
690
                if (!Context.hasPrivilege(PrivilegeConstants.EDIT_USERS)) {
1 ✔
NEW
691
                        throw new APIException("you.are.not.authorized.change.properties", new Object[] { user.getUserId() });
×
692
                }
693
                requireCanChangeSuperUser(user.getUserId());
1 ✔
694
        }
1 ✔
695

696
        /**
697
         * @return true if the id is the authenticated user's, as loaded rather than as set on the
698
         *         authenticated user object
699
         */
700
        private static boolean isAuthenticatedUser(Integer userId) {
701
                return userId != null && userId.equals(Context.getUserContext().getAuthenticatedUserId());
1 ✔
702
        }
703

704
        /**
705
         * Requires {@link PrivilegeConstants#ASSIGN_SYSTEM_DEVELOPER_ROLE}, held through roles, to change
706
         * another user who is a superuser as stored. Narrower privileges, like a help desk's, suffice for
707
         * other users' passwords, properties or roles.
708
         *
709
         * @param userId the id of the user being changed
710
         * @throws APIException if the user is a superuser and the authenticated user may not change them
711
         */
712
        private void requireCanChangeSuperUser(Integer userId) {
713
                if (userId == null || isAuthenticatedUser(userId)
1 ✔
714
                        || RoleAssignments.holds(PrivilegeConstants.ASSIGN_SYSTEM_DEVELOPER_ROLE)) {
1 ✔
715
                        return;
1 ✔
716
                }
717
                RoleAssignments.requireCanChangeSuperuser("User.superuser.privilegeRequired", dao.getStoredRoleNames(userId),
1 ✔
718
                    dao::getStoredRole);
719
        }
1 ✔
720

721
        /**
722
         * Applies {@code change} to the properties of the user loaded by id, which Hibernate writes on
723
         * flush. Loading by id, rather than using the caller's copy, means nothing else on that copy, such
724
         * as roles or the retired flag of a user captured at login, is written back. For the authenticated
725
         * user, the change is mirrored onto the session's copy so it sees its own writes.
726
         */
727
        private User saveStoredUserProperties(Integer userId, Consumer<Map<String, String>> change) {
728
                if (userId == null) {
1 ✔
NEW
729
                        throw new APIException("This method can be called only to update existing users");
×
730
                }
731
                User stored = dao.getUser(userId);
1 ✔
732
                if (stored == null) {
1 ✔
NEW
733
                        throw new APIException("no.authenticated.user.found", (Object[]) null);
×
734
                }
735
                change.accept(stored.getUserProperties());
1 ✔
736

737
                User authenticated = Context.getAuthenticatedUser();
1 ✔
738
                if (authenticated != null && authenticated != stored && isAuthenticatedUser(userId)) {
1 ✔
739
                        change.accept(authenticated.getUserProperties());
1 ✔
740
                }
741
                return stored;
1 ✔
742
        }
743

744
        /**
745
         * Generates system ids based on the following algorithm scheme: user_id-check digit
746
         *
747
         * @see org.openmrs.api.UserService#generateSystemId()
748
         */
749
        @Override
750
        @Transactional(readOnly = true)
751
        public String generateSystemId() {
752
                // Hardcoding Luhn algorithm since all existing openmrs user ids have
753
                // had check digits generated this way.
754
                LuhnIdentifierValidator liv = new LuhnIdentifierValidator();
1 ✔
755
                
756
                String systemId;
757
                Integer offset = 0;
1 ✔
758
                do {
759
                        // generate and increment the system id if necessary
760
                        Integer generatedId = dao.generateSystemId() + offset++;
1 ✔
761
                        
762
                        systemId = generatedId.toString();
1 ✔
763
                        
764
                        try {
765
                                systemId = liv.getValidIdentifier(systemId);
1 ✔
766
                        }
767
                        catch (Exception e) {
×
768
                                log.error("error getting check digit", e);
×
769
                                return systemId;
×
770
                        }
1 ✔
771
                        
772
                        // loop until we find a system id that no one has 
773
                } while (dao.hasDuplicateUsername(null, systemId, null));
1 ✔
774
                
775
                return systemId;
1 ✔
776
        }
777
        
778
        /**
779
         * @see org.openmrs.api.UserService#purgeUser(org.openmrs.User)
780
         */
781
        @Override
782
        public void purgeUser(User user) throws APIException {
783
                // by the id the row is deleted under, which the user object's own id need not match
784
                requireCanChangeSuperUser(dao.getStoredUserId(user));
1 ✔
785
                dao.deleteUser(user);
1 ✔
786
        }
1 ✔
787
        
788
        /**
789
         * @see org.openmrs.api.UserService#purgeUser(org.openmrs.User, boolean)
790
         */
791
        @Override
792
        public void purgeUser(User user, boolean cascade) throws APIException {
793
                if (cascade) {
1 ✔
794
                        throw new APIException("cascade.do.not.think", (Object[]) null);
1 ✔
795
                }
796

797
                requireCanChangeSuperUser(dao.getStoredUserId(user));
1 ✔
798
                dao.deleteUser(user);
1 ✔
799
        }
1 ✔
800
        
801
        /**
802
         * @return the id of the authenticated user, as loaded
803
         * @throws APIException if no stored user is authenticated
804
         */
805
        private static Integer requireAuthenticatedUserId() {
806
                Integer userId = Context.getAuthenticatedUserId();
1 ✔
807
                if (userId == null) {
1 ✔
NEW
808
                        throw new APIException("no.authenticated.user.found", (Object[]) null);
×
809
                }
810
                return userId;
1 ✔
811
        }
812

813
        /**
814
         * Checks that the authenticated user holds every privilege the role grants directly, and may hand
815
         * out the roles it inherits from (see {@link RoleAssignments}).
816
         *
817
         * @param role the role being saved
818
         * @param parents the stored roles it is to inherit from
819
         */
820
        private void checkPrivileges(Role role, Set<Role> parents) {
821
                Set<String> missing = new TreeSet<>(RoleAssignments.missingPrivileges(roleNames(parents), dao::getStoredRole));
1 ✔
822
                Optional.ofNullable(role.getPrivileges())
1 ✔
823
                        .ifPresent(p -> missing.addAll(RoleAssignments.notHeld(p.stream().map(Privilege::getPrivilege).collect(Collectors.toList()))));
1 ✔
824
                if (!missing.isEmpty()) {
1 ✔
825
                        throw new APIException("Role.you.must.have.privileges", new Object[] { String.join(", ", missing) });
1 ✔
826
                }
827
        }
1 ✔
828
        
829
        /**
830
         * @see org.openmrs.api.UserService#getPrivilegeByUuid(java.lang.String)
831
         */
832
        @Override
833
        @Transactional(readOnly = true)
834
        public Privilege getPrivilegeByUuid(String uuid) throws APIException {
835
                return dao.getPrivilegeByUuid(uuid);
1 ✔
836
        }
837
        
838
        /**
839
         * @see org.openmrs.api.UserService#getRoleByUuid(java.lang.String)
840
         */
841
        @Override
842
        @Transactional(readOnly = true)
843
        public Role getRoleByUuid(String uuid) throws APIException {
844
                return dao.getRoleByUuid(uuid);
1 ✔
845
        }
846
        
847
        /**
848
         * @see org.openmrs.api.UserService#getUserByUuid(java.lang.String)
849
         */
850
        @Override
851
        @Transactional(readOnly = true)
852
        public User getUserByUuid(String uuid) throws APIException {
853
                return dao.getUserByUuid(uuid);
1 ✔
854
        }
855
        
856
        /**
857
         * @see UserService#getCountOfUsers(String, List, boolean)
858
         */
859
        @Override
860
        @Transactional(readOnly = true)
861
        public Integer getCountOfUsers(String name, List<Role> roles, boolean includeRetired) {
862
                if (name != null) {
×
863
                        name = StringUtils.replace(name, ", ", " ");
×
864
                }
865
                
866
                // if the authenticated role is in the list of searched roles, then all
867
                // persons should be searched
868
                Role authRole = getRole(RoleConstants.AUTHENTICATED);
×
869
                if (roles.contains(authRole)) {
×
870
                        return dao.getCountOfUsers(name, new ArrayList<>(), includeRetired);
×
871
                }
872
                
873
                return dao.getCountOfUsers(name, roles, includeRetired);
×
874
        }
875
        
876
        /**
877
         * @see UserService#getUsers(String, List, boolean, Integer, Integer)
878
         */
879
        @Override
880
        @Transactional(readOnly = true)
881
        public List<User> getUsers(String name, List<Role> roles, boolean includeRetired, Integer start, Integer length)
882
                throws APIException {
883
                if (name != null) {
1 ✔
884
                        name = StringUtils.replace(name, ", ", " ");
1 ✔
885
                }
886
                
887
                if (roles == null) {
1 ✔
888
                        roles = new ArrayList<>();
1 ✔
889
                }
890
                
891
                // if the authenticated role is in the list of searched roles, then all
892
                // persons should be searched
893
                Role authRole = getRole(RoleConstants.AUTHENTICATED);
1 ✔
894
                if (roles.contains(authRole)) {
1 ✔
895
                        return dao.getUsers(name, new ArrayList<>(), includeRetired, start, length);
×
896
                }
897
                
898
                // add the requested roles and all child roles for consideration
899
                Set<Role> allRoles = new HashSet<>();
1 ✔
900
                for (Role r : roles) {
1 ✔
901
                        allRoles.add(r);
1 ✔
902
                        allRoles.addAll(r.getAllChildRoles());
1 ✔
903
                }
1 ✔
904
                
905
                return dao.getUsers(name, new ArrayList<>(allRoles), includeRetired, start, length);
1 ✔
906
        }
907
        
908
        @Override
909
        public User saveUserProperty(String key, String value) {
910
                return saveStoredUserProperties(requireAuthenticatedUserId(), properties -> properties.put(key, value));
1 ✔
911
        }
912
        
913
        @Override
914
        public User saveUserProperties(Map<String, String> properties) {
915
                // copied first, since properties may be the very map being cleared
916
                Map<String, String> replacement = new HashMap<>(properties);
1 ✔
917
                return saveStoredUserProperties(requireAuthenticatedUserId(), stored -> {
1 ✔
918
                        stored.clear();
1 ✔
919
                        stored.putAll(replacement);
1 ✔
920
                });
1 ✔
921
        }
922
        
923
        /**
924
         * @see UserService#changePassword(User, String, String)
925
         */
926
        @Override
927
        @Authorized(PrivilegeConstants.EDIT_USER_PASSWORDS)
928
        @Logging(ignoredArgumentIndexes = { 1, 2 })
929
        public void changePassword(User user, String oldPassword, String newPassword) throws APIException {
930
                if (user.getUserId() == null) {
1 ✔
931
                        throw new APIException("user.must.exist", (Object[]) null);
1 ✔
932
                }
933
                
934
                if (oldPassword == null) {
1 ✔
935
                        if (!Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) {
1 ✔
936
                                throw new APIException("null.old.password.privilege.required", (Object[]) null);
×
937
                        }
938
                        // an anonymous caller is the forgot-password flow, which has already checked the secret answer
939
                        if (Context.isAuthenticated()) {
1 ✔
940
                                requireCanChangeSuperUser(user.getUserId());
1 ✔
941
                        }
942
                } else if (!dao.getLoginCredential(user).checkPassword(oldPassword)) {
1 ✔
943
                        throw new APIException("old.password.not.correct", (Object[]) null);
1 ✔
944
                        
945
                } else if (oldPassword.equals(newPassword)) {
1 ✔
946
                        throw new APIException("new.password.equal.to.old", (Object[]) null);
×
947
                }
948
                
949
                if (("admin".equals(user.getSystemId()) || "admin".equals(user.getUsername())) && Boolean.parseBoolean(
1 ✔
950
                        Context.getRuntimeProperties().getProperty(ADMIN_PASSWORD_LOCKED_PROPERTY, "false"))) {
1 ✔
951
                        throw new APIException("admin.password.is.locked");
1 ✔
952
                }
953
                
954
                updatePassword(user, newPassword);
1 ✔
955
        }
1 ✔
956
        
957
        @Override
958
        @Logging(ignoredArgumentIndexes = { 1 })
959
        public void changePassword(User user, String newPassword) {
960
                Context.getUserService().changePassword(user, null, newPassword);
1 ✔
961
        }
1 ✔
962
        
963
        @Override
964
        @Logging(ignoredArgumentIndexes = { 1, 2 })
965
        public void changePasswordUsingSecretAnswer(String secretAnswer, String pw) throws APIException {
966
                User user = Context.getAuthenticatedUser();
1 ✔
967
                
968
                if (!isSecretAnswer(user, secretAnswer)) {
1 ✔
969
                        throw new APIException("secret.answer.not.correct", (Object[]) null);
1 ✔
970
                }
971
                
972
                updatePassword(user, pw);
1 ✔
973
        }
1 ✔
974

975
        private void updatePassword(User user, String newPassword) {
976
                OpenmrsUtil.validatePassword(user.getUsername(), newPassword, user.getSystemId());
1 ✔
977
                daoChangePassword(user, newPassword);
1 ✔
978
        }
1 ✔
979
        
980
        @Override
981
        public String getSecretQuestion(User user) throws APIException {
982
                if (user.getUserId() != null) {
×
983
                        LoginCredential loginCredential = dao.getLoginCredential(user);
×
984
                        return loginCredential.getSecretQuestion();
×
985
                } else {
986
                        return null;
×
987
                }
988
        }
989
        
990
        /**
991
         * @see org.openmrs.api.UserService#getUserByUsernameOrEmail(java.lang.String)
992
         */
993
        @Override
994
        @Transactional(readOnly = true)
995
        public User getUserByUsernameOrEmail(String usernameOrEmail) {
996
                if (StringUtils.isNotBlank(usernameOrEmail)) {
1 ✔
997
                        User user = dao.getUserByEmail(usernameOrEmail);
1 ✔
998
                        if (user == null) {
1 ✔
999
                                return getUserByUsername(usernameOrEmail);
1 ✔
1000
                        }
1001
                        return user;
1 ✔
1002
                }
1003
                throw new APIException("error.usernameOrEmail.notNullOrBlank", (Object[]) null);
1 ✔
1004
        }
1005
        
1006
        /**
1007
         * @see org.openmrs.api.UserService#getUserByActivationKey(java.lang.String)
1008
         */
1009
        @Override
1010
        @Transactional(readOnly = true)
1011
        public User getUserByActivationKey(String activationKey) {
1012
                LoginCredential loginCred = dao.getLoginCredentialByActivationKey(activationKey);
1 ✔
1013
                if (loginCred != null) {
1 ✔
1014
                        String[] credTokens = loginCred.getActivationKey().split(":");
1 ✔
1015
                        if (System.currentTimeMillis() <= Long.parseLong(credTokens[1])) {
1 ✔
1016
                                return getUser(loginCred.getUserId());
1 ✔
1017
                        }
1018
                }
1019
                return null;
1 ✔
1020
        }
1021
        
1022
        /**
1023
         * @throws APIException
1024
         * @throws MessageException
1025
         * @see org.openmrs.api.UserService#setUserActivationKey(org.openmrs.User)
1026
         */
1027
        @Override
1028
        public User setUserActivationKey(User user) throws MessageException {
1029
                // an anonymous caller is the forgot-password flow, which sends the link to the user themselves
1030
                if (Context.isAuthenticated()) {
1 ✔
1031
                        requireCanChangeSuperUser(user.getUserId());
1 ✔
1032
                }
1033
                String token = RandomStringUtils.secure().nextAlphanumeric(20);
1 ✔
1034
                long time = System.currentTimeMillis() + getValidTime();
1 ✔
1035
                String hashedKey = Security.encodeString(token);
1 ✔
1036
                String activationKey = hashedKey + ":" + time;
1 ✔
1037
                LoginCredential credentials = dao.getLoginCredential(user);
1 ✔
1038
                credentials.setActivationKey(activationKey);
1 ✔
1039
                dao.setUserActivationKey(credentials);
1 ✔
1040
                
1041
                MessageSourceService messages = Context.getMessageSourceService();
1 ✔
1042
                AdministrationService adminService = Context.getAdministrationService();
1 ✔
1043
                Locale locale = getDefaultLocaleForUser(user);
1 ✔
1044
                
1045
                //                Delete this method call when removing {@link OpenmrsConstants#GP_HOST_URL}
1046
                copyHostURLGlobalPropertyToPasswordResetGlobalProperty(adminService);
1 ✔
1047
                
1048
                String link = adminService.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_URL)
1 ✔
1049
                        .replace("{activationKey}", token);
1 ✔
1050
                
1051
                Properties mailProperties = Context.getMailProperties();
1 ✔
1052
                
1053
                String sender = mailProperties.getProperty("mail.from");
1 ✔
1054
                
1055
                String subject = messages.getMessage("mail.passwordreset.subject", null, locale);
1 ✔
1056
                
1057
                String body = messages.getMessage("mail.passwordreset.content", null, locale).replace("{name}", user.getUsername())
1 ✔
1058
                        .replace("{time}", String.valueOf(getValidTime() / 60000)).replace("{link}", "");
1 ✔
1059
                
1060
                String msg;
1061
                if (mailProperties.getProperty("mail.default_content_type", "text/plain").startsWith("text/html")) {
1 ✔
1062
                        String escapedLink = link.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"",
1 ✔
1063
                            "&quot;");
1064
                        msg = body + "<br/><br/><a href=\"" + escapedLink + "\">" + escapedLink + "</a>";
1 ✔
1065
                } else {
1 ✔
1066
                        msg = body + "\n\n" + link + "\n";
1 ✔
1067
                }
1068
                
1069
                Context.getMessageService().sendMessage(user.getEmail(), sender, subject, msg);
1 ✔
1070
                
1071
                return user;
1 ✔
1072
        }
1073
        
1074
        /**
1075
         * Delete this method when deleting {@link OpenmrsConstants#GP_HOST_URL}
1076
         */
1077
        private void copyHostURLGlobalPropertyToPasswordResetGlobalProperty(AdministrationService adminService) {
1078
                String hostURLGP = adminService.getGlobalProperty(OpenmrsConstants.GP_HOST_URL);
1 ✔
1079
                String passwordResetGP = adminService.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_URL);
1 ✔
1080
                if (StringUtils.isNotBlank(hostURLGP) && StringUtils.isBlank(passwordResetGP)) {
1 ✔
1081
                        adminService.setGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_URL, hostURLGP);
×
1082
                }
1083
        }
1 ✔
1084
        
1085
        /**
1086
         * @see UserService#getDefaultLocaleForUser(User)
1087
         */
1088
        @Override
1089
        public Locale getDefaultLocaleForUser(User user) {
1090
                Locale locale = null;
1 ✔
1091
                if (user != null) {
1 ✔
1092
                        try {
1093
                                String preferredLocale = user.getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE);
1 ✔
1094
                                if (StringUtils.isNotBlank(preferredLocale)) {
1 ✔
1095
                                        locale = LocaleUtility.fromSpecification(preferredLocale);
1 ✔
1096
                                }
1097
                        }
1098
                        catch (Exception e) {
×
1099
                                log.warn("Unable to parse user locale into a Locale", e);
×
1100
                        }
1 ✔
1101
                }
1102
                if (locale == null) {
1 ✔
1103
                        locale = Context.getLocale();
1 ✔
1104
                }
1105
                return locale;
1 ✔
1106
        }
1107
        
1108
        /**
1109
         * @see org.openmrs.api.UserService#changePasswordUsingActivationKey(String, String);
1110
         */
1111
        @Override
1112
        public void changePasswordUsingActivationKey(String activationKey, String newPassword) {
1113
                User user = getUserByActivationKey(activationKey);
1 ✔
1114
                if (user == null) {
1 ✔
1115
                        throw new InvalidActivationKeyException("activation.key.not.correct");
1 ✔
1116
                }
1117
                
1118
                LoginCredential credentials = dao.getLoginCredentialForUpdate(user);
1 ✔
1119
                String storedKey = credentials.getActivationKey();
1 ✔
1120
                if (storedKey == null || !storedKey.startsWith(Security.encodeString(activationKey) + ":")) {
1 ✔
1121
                        throw new InvalidActivationKeyException("activation.key.not.correct");
1 ✔
1122
                }
1123
                
1124
                updatePassword(user, newPassword);
1 ✔
1125
        }
1 ✔
1126

1127
        /**
1128
         * @see org.openmrs.api.UserService#getLastLoginTime(User)
1129
         */
1130
        public String getLastLoginTime(User user) {
1131
                return dao.getLastLoginTime(user);
1 ✔
1132
        }
1133
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc