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

openmrs / openmrs-core / 41717832711

30 Oct 2026 04:16PM UTC coverage: 66.75% (+0.003%) from 66.747%
41717832711

push

github

ibacher
TRUNK-6863: Remove the generation token before clearing a node's cache locally (#6791)

1 of 1 new or added line in 1 file covered. (100.0%)

419 existing lines in 31 files now uncovered.

26279 of 39369 relevant lines covered (66.75%)

0.67 hits per line

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

89.55
/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.Date;
15
import java.util.HashSet;
16
import java.util.List;
17
import java.util.Locale;
18
import java.util.Map;
19
import java.util.Objects;
20
import java.util.Optional;
21
import java.util.Properties;
22
import java.util.Set;
23
import java.util.stream.Collectors;
24

25
import org.apache.commons.lang.RandomStringUtils;
26
import org.apache.commons.lang3.StringUtils;
27
import org.openmrs.Person;
28
import org.openmrs.Privilege;
29
import org.openmrs.Role;
30
import org.openmrs.User;
31
import org.openmrs.annotation.Authorized;
32
import org.openmrs.annotation.Logging;
33
import org.openmrs.api.APIException;
34
import org.openmrs.api.AdministrationService;
35
import org.openmrs.api.CannotDeleteRoleWithChildrenException;
36
import org.openmrs.api.InvalidActivationKeyException;
37
import org.openmrs.api.UserService;
38
import org.openmrs.api.cache.RolePrivilegeCache;
39
import org.openmrs.api.context.Context;
40
import org.openmrs.api.db.DAOException;
41
import org.openmrs.api.db.LoginCredential;
42
import org.openmrs.api.db.UserDAO;
43
import org.openmrs.messagesource.MessageSourceService;
44
import org.openmrs.notification.MessageException;
45
import org.openmrs.patient.impl.LuhnIdentifierValidator;
46
import org.openmrs.util.LocaleUtility;
47
import org.openmrs.util.OpenmrsConstants;
48
import org.openmrs.util.OpenmrsUtil;
49
import org.openmrs.util.PrivilegeConstants;
50
import org.openmrs.util.RoleConstants;
51
import org.openmrs.util.Security;
52
import org.slf4j.Logger;
53
import org.slf4j.LoggerFactory;
54
import org.springframework.cache.annotation.CacheEvict;
55
import org.springframework.transaction.annotation.Transactional;
56

57
/**
58
 * Default implementation of the user service. This class should not be used on its own. The current
59
 * OpenMRS implementation should be fetched from the Context
60
 *
61
 * @see org.openmrs.api.UserService
62
 * @see org.openmrs.api.context.Context
63
 */
64
@Transactional
65
public class UserServiceImpl extends BaseOpenmrsService implements UserService {
66
        
67
        private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
1 ✔
68
        
69
        protected UserDAO dao;
70

71
        private RolePrivilegeCache rolePrivilegeCache;
72

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

109
                private static final ThreadLocal<Integer> DEPTH = new ThreadLocal<>();
1 ✔
110

111
                private UserPasswordGuard() {
112
                }
113

114
                private static void enter() {
115
                        Integer depth = DEPTH.get();
1 ✔
116
                        DEPTH.set(depth == null ? 1 : depth + 1);
1 ✔
117
                }
1 ✔
118

119
                private static void exit() {
120
                        Integer depth = DEPTH.get();
1 ✔
121
                        if (depth == null || depth <= 1) {
1 ✔
122
                                DEPTH.remove();
1 ✔
123
                        } else {
124
                                DEPTH.set(depth - 1);
×
125
                        }
126
                }
1 ✔
127

128
                /**
129
                 * @return true if the calling thread is currently executing inside the user service
130
                 */
131
                public static boolean isPermitted() {
132
                        return DEPTH.get() != null;
1 ✔
133
                }
134
        }
135

136
        /**
137
         * The service's single entry point to {@link UserDAO#saveUser(User, String)}, raising the permit
138
         * that the DAO requires of anything that can change a password.
139
         *
140
         * @see UserPasswordGuard
141
         */
142
        private User daoSaveUser(User user, String password) {
143
                UserPasswordGuard.enter();
1 ✔
144
                try {
145
                        return dao.saveUser(user, password);
1 ✔
146
                } finally {
147
                        UserPasswordGuard.exit();
1 ✔
148
                }
149
        }
150

151
        /**
152
         * The service's single entry point to {@link UserDAO#changePassword(User, String)}.
153
         *
154
         * @see UserPasswordGuard
155
         */
156
        private void daoChangePassword(User user, String newPassword) {
157
                UserPasswordGuard.enter();
1 ✔
158
                try {
159
                        dao.changePassword(user, newPassword);
1 ✔
160
                } finally {
161
                        UserPasswordGuard.exit();
1 ✔
162
                }
163
        }
1 ✔
164

165
        /**
166
         * The service's single entry point to {@link UserDAO#changeHashedPassword(User, String, String)}.
167
         *
168
         * @see UserPasswordGuard
169
         */
170
        private void daoChangeHashedPassword(User user, String hashedPassword, String salt) {
171
                UserPasswordGuard.enter();
1 ✔
172
                try {
173
                        dao.changeHashedPassword(user, hashedPassword, salt);
1 ✔
174
                } finally {
175
                        UserPasswordGuard.exit();
1 ✔
176
                }
177
        }
1 ✔
178

179
        /**
180
         * @return the validTime for which the password reset activation key will be valid
181
         */
182
        private int getValidTime() {
183
                String validTimeGp = Context.getAdministrationService()
1 ✔
184
                        .getGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_VALIDTIME);
1 ✔
185
                final int validTime = StringUtils.isBlank(validTimeGp) ? DEFAULT_VALID_TIME : Integer.parseInt(validTimeGp);
1 ✔
186
                //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.
187
                return (validTime < MIN_VALID_TIME) || (validTime > MAX_VALID_TIME) ? DEFAULT_VALID_TIME : validTime;
1 ✔
188
        }
189
        
190
        /**
191
         * @see org.openmrs.api.UserService#createUser(org.openmrs.User, java.lang.String)
192
         */
193
        @Override
194
        public User createUser(User user, String password) throws APIException {
195
                if (user.getUserId() != null) {
1 ✔
196
                        throw new APIException("This method can be used for only creating new users");
1 ✔
197
                }
198
                
199
                Context.requirePrivilege(PrivilegeConstants.ADD_USERS);
1 ✔
200
                
201
                checkPrivileges(user);
1 ✔
202
                
203
                // if a password wasn't supplied, throw an error
204
                if (password == null || password.isEmpty()) {
1 ✔
205
                        throw new APIException("User.creating.password.required", (Object[]) null);
×
206
                }
207
                
208
                if (hasDuplicateUsername(user)) {
1 ✔
209
                        throw new DAOException("Username " + user.getUsername() + " or system id " + user.getSystemId()
1 ✔
210
                                + " is already in use.");
211
                }
212
                
213
                // TODO Check required fields for user!!
214
                OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
1 ✔
215

216
                return daoSaveUser(user, password);
1 ✔
217
        }
218
        
219
        /**
220
         * @see org.openmrs.api.UserService#getUser(java.lang.Integer)
221
         */
222
        @Override
223
        @Transactional(readOnly = true)
224
        public User getUser(Integer userId) throws APIException {
225
                return dao.getUser(userId);
1 ✔
226
        }
227
        
228
        /**
229
         * @see org.openmrs.api.UserService#getUserByUsername(java.lang.String)
230
         */
231
        @Override
232
        @Transactional(readOnly = true)
233
        public User getUserByUsername(String username) throws APIException {
234
                return dao.getUserByUsername(username);
1 ✔
235
        }
236
        
237
        /**
238
         * @see org.openmrs.api.UserService#hasDuplicateUsername(org.openmrs.User)
239
         */
240
        @Override
241
        @Transactional(readOnly = true)
242
        public boolean hasDuplicateUsername(User user) throws APIException {
243
                return dao.hasDuplicateUsername(user.getUsername(), user.getSystemId(), user.getUserId());
1 ✔
244
        }
245
        
246
        /**
247
         * @see org.openmrs.api.UserService#getUsersByRole(org.openmrs.Role)
248
         */
249
        @Override
250
        @Transactional(readOnly = true)
251
        public List<User> getUsersByRole(Role role) throws APIException {
252
                List<Role> roles = new ArrayList<>();
1 ✔
253
                roles.add(role);
1 ✔
254
                
255
                return Context.getUserService().getUsers(null, roles, false);
1 ✔
256
        }
257
        
258
        /**
259
         * @see org.openmrs.api.UserService#saveUser(org.openmrs.User)
260
         */
261
        @Override
262
        @CacheEvict(value = "userSearchLocales", allEntries = true)
263
        public User saveUser(User user) throws APIException {
264
                if (user.getUserId() == null) {
1 ✔
265
                        throw new APIException("This method can be called only to update existing users");
×
266
                }
267
                
268
                Context.requirePrivilege(PrivilegeConstants.EDIT_USERS);
1 ✔
269
                
270
                checkPrivileges(user);
1 ✔
271
                
272
                if (hasDuplicateUsername(user)) {
1 ✔
273
                        throw new DAOException("Username " + user.getUsername() + " or system id " + user.getSystemId()
×
274
                                + " is already in use.");
275
                }
276

277
                return daoSaveUser(user, null);
1 ✔
278
        }
279
        
280
        public User voidUser(User user, String reason) throws APIException {
281
                return Context.getUserService().retireUser(user, reason);
×
282
        }
283
        
284
        /**
285
         * @see org.openmrs.api.UserService#retireUser(org.openmrs.User, java.lang.String)
286
         */
287
        @Override
288
        public User retireUser(User user, String reason) throws APIException {
289
                user.setRetired(true);
1 ✔
290
                user.setRetireReason(reason);
1 ✔
291
                user.setRetiredBy(Context.getAuthenticatedUser());
1 ✔
292
                user.setDateRetired(new Date());
1 ✔
293
                
294
                return saveUser(user);
1 ✔
295
        }
296
        
297
        public User unvoidUser(User user) throws APIException {
298
                return Context.getUserService().unretireUser(user);
×
299
        }
300
        
301
        /**
302
         * @see org.openmrs.api.UserService#unretireUser(org.openmrs.User)
303
         */
304
        @Override
305
        public User unretireUser(User user) throws APIException {
306
                user.setRetired(false);
1 ✔
307
                user.setRetireReason(null);
1 ✔
308
                user.setRetiredBy(null);
1 ✔
309
                user.setDateRetired(null);
1 ✔
310
                
311
                return saveUser(user);
1 ✔
312
        }
313
        
314
        /**
315
         * @see org.openmrs.api.UserService#getAllUsers()
316
         */
317
        @Override
318
        @Transactional(readOnly = true)
319
        public List<User> getAllUsers() throws APIException {
320
                return dao.getAllUsers();
1 ✔
321
        }
322
        
323
        /**
324
         * @see org.openmrs.api.UserService#getAllPrivileges()
325
         */
326
        @Override
327
        @Transactional(readOnly = true)
328
        public List<Privilege> getAllPrivileges() throws APIException {
329
                return dao.getAllPrivileges();
1 ✔
330
        }
331
        
332
        /**
333
         * @see org.openmrs.api.UserService#getPrivilege(java.lang.String)
334
         */
335
        @Override
336
        @Transactional(readOnly = true)
337
        public Privilege getPrivilege(String p) throws APIException {
338
                return dao.getPrivilege(p);
1 ✔
339
        }
340
        
341
        /**
342
         * @see org.openmrs.api.UserService#purgePrivilege(org.openmrs.Privilege)
343
         */
344
        @Override
345
        public void purgePrivilege(Privilege privilege) throws APIException {
346
                if (OpenmrsUtil.getCorePrivileges().keySet().contains(privilege.getPrivilege())) {
1 ✔
347
                        throw new APIException("Privilege.cannot.delete.core", (Object[]) null);
1 ✔
348
                }
349
                
350
                dao.deletePrivilege(privilege);
1 ✔
351
                rolePrivilegeCache.clear();
1 ✔
352
        }
1 ✔
353
        
354
        /**
355
         * @see org.openmrs.api.UserService#savePrivilege(org.openmrs.Privilege)
356
         */
357
        @Override
358
        public Privilege savePrivilege(Privilege privilege) throws APIException {
359
                Privilege saved = dao.savePrivilege(privilege);
1 ✔
360
                rolePrivilegeCache.clear();
1 ✔
361
                return saved;
1 ✔
362
        }
363
        
364
        /**
365
         * @see org.openmrs.api.UserService#getAllRoles()
366
         */
367
        @Override
368
        @Transactional(readOnly = true)
369
        public List<Role> getAllRoles() throws APIException {
370
                return dao.getAllRoles();
1 ✔
371
        }
372
        
373
        /**
374
         * @see org.openmrs.api.UserService#getRole(java.lang.String)
375
         */
376
        @Override
377
        @Transactional(readOnly = true)
378
        public Role getRole(String r) throws APIException {
379
                return dao.getRole(r);
1 ✔
380
        }
381
        
382
        /**
383
         * @see org.openmrs.api.UserService#purgeRole(org.openmrs.Role)
384
         */
385
        @Override
386
        public void purgeRole(Role role) throws APIException {
387
                if (role == null || role.getRole() == null) {
1 ✔
388
                        return;
1 ✔
389
                }
390
                
391
                if (OpenmrsUtil.getCoreRoles().keySet().contains(role.getRole())) {
1 ✔
392
                        throw new APIException("Role.cannot.delete.core", (Object[]) null);
1 ✔
393
                }
394
                
395
                if (role.hasChildRoles()) {
1 ✔
396
                        throw new CannotDeleteRoleWithChildrenException();
1 ✔
397
                }
398
                
399
                dao.deleteRole(role);
1 ✔
400
                rolePrivilegeCache.clear();
1 ✔
401
        }
1 ✔
402
        
403
        /**
404
         * @see org.openmrs.api.UserService#saveRole(org.openmrs.Role)
405
         */
406
        @Override
407
        public Role saveRole(Role role) throws APIException {
408
                // make sure one of the parents of this role isn't itself...this would
409
                // cause an infinite loop
410
                if (role.getAllParentRoles().contains(role)) {
1 ✔
411
                        throw new APIException("Role.cannot.inherit.descendant", (Object[]) null);
1 ✔
412
                }
413
                
414
                checkPrivileges(role);
1 ✔
415

416
                Role saved = dao.saveRole(role);
1 ✔
417
                rolePrivilegeCache.clear();
1 ✔
418
                return saved;
1 ✔
419
        }
420
        
421
        /**
422
         * @see org.openmrs.api.UserService#changePassword(java.lang.String, java.lang.String)
423
         */
424
        @Override
425
        public void changePassword(String oldPassword, String newPassword) throws APIException {
426
                User user = Context.getAuthenticatedUser();
1 ✔
427
                changePassword(user, oldPassword, newPassword);
1 ✔
428
        }
1 ✔
429
        
430
        /**
431
         * @see org.openmrs.api.UserService#changeHashedPassword(User, String, String)
432
         */
433
        @Override
434
        public void changeHashedPassword(User user, String hashedPassword, String salt) throws APIException {
435
                daoChangeHashedPassword(user, hashedPassword, salt);
1 ✔
436
        }
1 ✔
437
        
438
        /**
439
         * @see org.openmrs.api.UserService#changeQuestionAnswer(User, String, String)
440
         */
441
        @Override
442
        public void changeQuestionAnswer(User u, String question, String answer) throws APIException {
443
                dao.changeQuestionAnswer(u, question, answer);
1 ✔
444
        }
1 ✔
445
        
446
        /**
447
         * @see org.openmrs.api.UserService#changeQuestionAnswer(java.lang.String, java.lang.String,
448
         * java.lang.String)
449
         */
450
        @Override
451
        public void changeQuestionAnswer(String pw, String q, String a) {
452
                dao.changeQuestionAnswer(pw, q, a);
1 ✔
453
        }
1 ✔
454
        
455
        /**
456
         * @see org.openmrs.api.UserService#isSecretAnswer(org.openmrs.User, java.lang.String)
457
         */
458
        @Override
459
        @Transactional(readOnly = true)
460
        public boolean isSecretAnswer(User u, String answer) {
461
                return dao.isSecretAnswer(u, answer);
1 ✔
462
        }
463
        
464
        /**
465
         * @see org.openmrs.api.UserService#getUsersByName(java.lang.String, java.lang.String, boolean)
466
         */
467
        @Override
468
        @Transactional(readOnly = true)
469
        public List<User> getUsersByName(String givenName, String familyName, boolean includeVoided) throws APIException {
470
                return dao.getUsersByName(givenName, familyName, includeVoided);
1 ✔
471
        }
472
        
473
        /**
474
         * @see org.openmrs.api.UserService#getUsersByPerson(org.openmrs.Person, boolean)
475
         */
476
        @Override
477
        @Transactional(readOnly = true)
478
        public List<User> getUsersByPerson(Person person, boolean includeRetired) throws APIException {
479
                return dao.getUsersByPerson(person, includeRetired);
1 ✔
480
        }
481
        
482
        /**
483
         * @see org.openmrs.api.UserService#getUsers(java.lang.String, java.util.List, boolean)
484
         */
485
        @Override
486
        @Transactional(readOnly = true)
487
        public List<User> getUsers(String nameSearch, List<Role> roles, boolean includeVoided) throws APIException {
488
                return Context.getUserService().getUsers(nameSearch, roles, includeVoided, null, null);
1 ✔
489
        }
490
        
491
        /**
492
         * Convenience method to check if the authenticated user has all privileges they are giving out
493
         *
494
         * @param user user that has privileges
495
         */
496
        private void checkPrivileges(User user) {
497
                List<String> requiredPrivs = user.getAllRoles().stream().peek(this::checkSuperUserPrivilege)
1 ✔
498
                        .map(Role::getPrivileges).filter(Objects::nonNull).flatMap(Collection::stream)
1 ✔
499
                        .map(Privilege::getPrivilege).filter(p -> !Context.hasPrivilege(p)).sorted().collect(Collectors.toList());
1 ✔
500
                if (requiredPrivs.size() == 1) {
1 ✔
501
                        throw new APIException("User.you.must.have.privilege", new Object[] { requiredPrivs.get(0) });
1 ✔
502
                } else if (requiredPrivs.size() > 1) {
1 ✔
503
                        throw new APIException("User.you.must.have.privileges", new Object[] { String.join(", ", requiredPrivs) });
1 ✔
504
                }
505
        }
1 ✔
506
        
507
        private void checkSuperUserPrivilege(Role r) {
508
                if (r.getRole().equals(RoleConstants.SUPERUSER)
1 ✔
509
                        && !Context.hasPrivilege(PrivilegeConstants.ASSIGN_SYSTEM_DEVELOPER_ROLE)) {
1 ✔
510
                        throw new APIException("User.you.must.have.role", new Object[] { RoleConstants.SUPERUSER });
1 ✔
511
                }
512
        }
1 ✔
513
        
514
        /**
515
         * @see org.openmrs.api.UserService#setUserProperty(User, String, String)
516
         */
517
        @Override
518
        public User setUserProperty(User user, String key, String value) {
519
                if (user != null) {
1 ✔
520
                        if (!Context.hasPrivilege(PrivilegeConstants.EDIT_USERS) && !user.equals(Context.getAuthenticatedUser())) {
1 ✔
521
                                throw new APIException("you.are.not.authorized.change.properties", new Object[] { user.getUserId() });
×
522
                        }
523
                        
524
                        user.setUserProperty(key, value);
1 ✔
525
                        try {
526
                                Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);
1 ✔
527
                                Context.getUserService().saveUser(user);
1 ✔
528
                        }
529
                        finally {
530
                                Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
1 ✔
531
                        }
532
                }
533
                
534
                return user;
1 ✔
535
        }
536
        
537
        /**
538
         * @see org.openmrs.api.UserService#removeUserProperty(org.openmrs.User, java.lang.String)
539
         */
540
        @Override
541
        public User removeUserProperty(User user, String key) {
542
                if (user != null) {
1 ✔
543
                        
544
                        // if the current user isn't allowed to edit users and
545
                        // the user being edited is not the current user, throw an
546
                        // exception
547
                        if (!Context.hasPrivilege(PrivilegeConstants.EDIT_USERS) && !user.equals(Context.getAuthenticatedUser())) {
1 ✔
548
                                throw new APIException("you.are.not.authorized.change.properties", new Object[] { user.getUserId() });
×
549
                        }
550
                        
551
                        user.removeUserProperty(key);
1 ✔
552
                        
553
                        try {
554
                                Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);
1 ✔
555
                                Context.getUserService().saveUser(user);
1 ✔
556
                        }
557
                        finally {
558
                                Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
1 ✔
559
                        }
560
                }
561
                
562
                return user;
1 ✔
563
        }
564
        
565
        /**
566
         * Generates system ids based on the following algorithm scheme: user_id-check digit
567
         *
568
         * @see org.openmrs.api.UserService#generateSystemId()
569
         */
570
        @Override
571
        @Transactional(readOnly = true)
572
        public String generateSystemId() {
573
                // Hardcoding Luhn algorithm since all existing openmrs user ids have
574
                // had check digits generated this way.
575
                LuhnIdentifierValidator liv = new LuhnIdentifierValidator();
1 ✔
576
                
577
                String systemId;
578
                Integer offset = 0;
1 ✔
579
                do {
580
                        // generate and increment the system id if necessary
581
                        Integer generatedId = dao.generateSystemId() + offset++;
1 ✔
582
                        
583
                        systemId = generatedId.toString();
1 ✔
584
                        
585
                        try {
586
                                systemId = liv.getValidIdentifier(systemId);
1 ✔
587
                        }
588
                        catch (Exception e) {
×
589
                                log.error("error getting check digit", e);
×
590
                                return systemId;
×
591
                        }
1 ✔
592
                        
593
                        // loop until we find a system id that no one has 
594
                } while (dao.hasDuplicateUsername(null, systemId, null));
1 ✔
595
                
596
                return systemId;
1 ✔
597
        }
598
        
599
        /**
600
         * @see org.openmrs.api.UserService#purgeUser(org.openmrs.User)
601
         */
602
        @Override
603
        public void purgeUser(User user) throws APIException {
604
                dao.deleteUser(user);
1 ✔
605
        }
1 ✔
606
        
607
        /**
608
         * @see org.openmrs.api.UserService#purgeUser(org.openmrs.User, boolean)
609
         */
610
        @Override
611
        public void purgeUser(User user, boolean cascade) throws APIException {
612
                if (cascade) {
1 ✔
613
                        throw new APIException("cascade.do.not.think", (Object[]) null);
1 ✔
614
                }
615
                
616
                dao.deleteUser(user);
1 ✔
617
        }
1 ✔
618
        
619
        /**
620
         * Convenience method to check if the authenticated user has all privileges they are giving out
621
         * to the new role
622
         *
623
         * @param role
624
         */
625
        private void checkPrivileges(Role role) {
626
                Optional.ofNullable(role.getPrivileges())
1 ✔
627
                        .map(p -> p.stream().filter(pr -> !Context.hasPrivilege(pr.getPrivilege())).map(Privilege::getPrivilege)
1 ✔
628
                                .distinct().collect(Collectors.joining(", ")))
1 ✔
629
                        .ifPresent(missing -> {
1 ✔
630
                                if (StringUtils.isNotBlank(missing)) {
1 ✔
631
                                        throw new APIException("Role.you.must.have.privileges", new Object[] { missing });
1 ✔
632
                                }
633
                        });
1 ✔
634
        }
1 ✔
635
        
636
        /**
637
         * @see org.openmrs.api.UserService#getPrivilegeByUuid(java.lang.String)
638
         */
639
        @Override
640
        @Transactional(readOnly = true)
641
        public Privilege getPrivilegeByUuid(String uuid) throws APIException {
642
                return dao.getPrivilegeByUuid(uuid);
1 ✔
643
        }
644
        
645
        /**
646
         * @see org.openmrs.api.UserService#getRoleByUuid(java.lang.String)
647
         */
648
        @Override
649
        @Transactional(readOnly = true)
650
        public Role getRoleByUuid(String uuid) throws APIException {
651
                return dao.getRoleByUuid(uuid);
1 ✔
652
        }
653
        
654
        /**
655
         * @see org.openmrs.api.UserService#getUserByUuid(java.lang.String)
656
         */
657
        @Override
658
        @Transactional(readOnly = true)
659
        public User getUserByUuid(String uuid) throws APIException {
660
                return dao.getUserByUuid(uuid);
1 ✔
661
        }
662
        
663
        /**
664
         * @see UserService#getCountOfUsers(String, List, boolean)
665
         */
666
        @Override
667
        @Transactional(readOnly = true)
668
        public Integer getCountOfUsers(String name, List<Role> roles, boolean includeRetired) {
669
                if (name != null) {
×
670
                        name = StringUtils.replace(name, ", ", " ");
×
671
                }
672
                
673
                // if the authenticated role is in the list of searched roles, then all
674
                // persons should be searched
675
                Role authRole = getRole(RoleConstants.AUTHENTICATED);
×
676
                if (roles.contains(authRole)) {
×
677
                        return dao.getCountOfUsers(name, new ArrayList<>(), includeRetired);
×
678
                }
679
                
680
                return dao.getCountOfUsers(name, roles, includeRetired);
×
681
        }
682
        
683
        /**
684
         * @see UserService#getUsers(String, List, boolean, Integer, Integer)
685
         */
686
        @Override
687
        @Transactional(readOnly = true)
688
        public List<User> getUsers(String name, List<Role> roles, boolean includeRetired, Integer start, Integer length)
689
                throws APIException {
690
                if (name != null) {
1 ✔
691
                        name = StringUtils.replace(name, ", ", " ");
1 ✔
692
                }
693
                
694
                if (roles == null) {
1 ✔
695
                        roles = new ArrayList<>();
1 ✔
696
                }
697
                
698
                // if the authenticated role is in the list of searched roles, then all
699
                // persons should be searched
700
                Role authRole = getRole(RoleConstants.AUTHENTICATED);
1 ✔
701
                if (roles.contains(authRole)) {
1 ✔
702
                        return dao.getUsers(name, new ArrayList<>(), includeRetired, start, length);
×
703
                }
704
                
705
                // add the requested roles and all child roles for consideration
706
                Set<Role> allRoles = new HashSet<>();
1 ✔
707
                for (Role r : roles) {
1 ✔
708
                        allRoles.add(r);
1 ✔
709
                        allRoles.addAll(r.getAllChildRoles());
1 ✔
710
                }
1 ✔
711
                
712
                return dao.getUsers(name, new ArrayList<>(allRoles), includeRetired, start, length);
1 ✔
713
        }
714
        
715
        @Override
716
        public User saveUserProperty(String key, String value) {
717
                User user = Context.getAuthenticatedUser();
1 ✔
718
                if (user == null) {
1 ✔
719
                        throw new APIException("no.authenticated.user.found", (Object[]) null);
×
720
                }
721
                user.setUserProperty(key, value);
1 ✔
722
                return daoSaveUser(user, null);
1 ✔
723
        }
724
        
725
        @Override
726
        public User saveUserProperties(Map<String, String> properties) {
727
                User user = Context.getAuthenticatedUser();
1 ✔
728
                if (user == null) {
1 ✔
729
                        throw new APIException("no.authenticated.user.found", (Object[]) null);
×
730
                }
731
                user.getUserProperties().clear();
1 ✔
732
                for (Map.Entry<String, String> entry : properties.entrySet()) {
1 ✔
733
                        user.setUserProperty(entry.getKey(), entry.getValue());
1 ✔
734
                }
1 ✔
735
                return daoSaveUser(user, null);
1 ✔
736
        }
737
        
738
        /**
739
         * @see UserService#changePassword(User, String, String)
740
         */
741
        @Override
742
        @Authorized(PrivilegeConstants.EDIT_USER_PASSWORDS)
743
        @Logging(ignoredArgumentIndexes = { 1, 2 })
744
        public void changePassword(User user, String oldPassword, String newPassword) throws APIException {
745
                if (user.getUserId() == null) {
1 ✔
746
                        throw new APIException("user.must.exist", (Object[]) null);
1 ✔
747
                }
748
                
749
                if (oldPassword == null) {
1 ✔
750
                        if (!Context.hasPrivilege(PrivilegeConstants.EDIT_USER_PASSWORDS)) {
1 ✔
751
                                throw new APIException("null.old.password.privilege.required", (Object[]) null);
×
752
                        }
753
                } else if (!dao.getLoginCredential(user).checkPassword(oldPassword)) {
1 ✔
754
                        throw new APIException("old.password.not.correct", (Object[]) null);
1 ✔
755
                        
756
                } else if (oldPassword.equals(newPassword)) {
1 ✔
757
                        throw new APIException("new.password.equal.to.old", (Object[]) null);
×
758
                }
759
                
760
                if (("admin".equals(user.getSystemId()) || "admin".equals(user.getUsername())) && Boolean.parseBoolean(
1 ✔
761
                        Context.getRuntimeProperties().getProperty(ADMIN_PASSWORD_LOCKED_PROPERTY, "false"))) {
1 ✔
762
                        throw new APIException("admin.password.is.locked");
1 ✔
763
                }
764
                
765
                updatePassword(user, newPassword);
1 ✔
766
        }
1 ✔
767
        
768
        @Override
769
        @Logging(ignoredArgumentIndexes = { 1 })
770
        public void changePassword(User user, String newPassword) {
771
                Context.getUserService().changePassword(user, null, newPassword);
1 ✔
772
        }
1 ✔
773
        
774
        @Override
775
        @Logging(ignoredArgumentIndexes = { 1, 2 })
776
        public void changePasswordUsingSecretAnswer(String secretAnswer, String pw) throws APIException {
777
                User user = Context.getAuthenticatedUser();
1 ✔
778
                
779
                if (!isSecretAnswer(user, secretAnswer)) {
1 ✔
780
                        throw new APIException("secret.answer.not.correct", (Object[]) null);
1 ✔
781
                }
782
                
783
                updatePassword(user, pw);
1 ✔
784
        }
1 ✔
785

786
        private void updatePassword(User user, String newPassword) {
787
                OpenmrsUtil.validatePassword(user.getUsername(), newPassword, user.getSystemId());
1 ✔
788
                daoChangePassword(user, newPassword);
1 ✔
789
        }
1 ✔
790
        
791
        @Override
792
        public String getSecretQuestion(User user) throws APIException {
793
                if (user.getUserId() != null) {
×
794
                        LoginCredential loginCredential = dao.getLoginCredential(user);
×
795
                        return loginCredential.getSecretQuestion();
×
796
                } else {
797
                        return null;
×
798
                }
799
        }
800
        
801
        /**
802
         * @see org.openmrs.api.UserService#getUserByUsernameOrEmail(java.lang.String)
803
         */
804
        @Override
805
        @Transactional(readOnly = true)
806
        public User getUserByUsernameOrEmail(String usernameOrEmail) {
807
                if (StringUtils.isNotBlank(usernameOrEmail)) {
1 ✔
808
                        User user = dao.getUserByEmail(usernameOrEmail);
1 ✔
809
                        if (user == null) {
1 ✔
810
                                return getUserByUsername(usernameOrEmail);
1 ✔
811
                        }
812
                        return user;
1 ✔
813
                }
814
                throw new APIException("error.usernameOrEmail.notNullOrBlank", (Object[]) null);
1 ✔
815
        }
816
        
817
        /**
818
         * @see org.openmrs.api.UserService#getUserByActivationKey(java.lang.String)
819
         */
820
        @Override
821
        @Transactional(readOnly = true)
822
        public User getUserByActivationKey(String activationKey) {
823
                LoginCredential loginCred = dao.getLoginCredentialByActivationKey(activationKey);
1 ✔
824
                if (loginCred != null) {
1 ✔
825
                        String[] credTokens = loginCred.getActivationKey().split(":");
1 ✔
826
                        if (System.currentTimeMillis() <= Long.parseLong(credTokens[1])) {
1 ✔
827
                                return getUser(loginCred.getUserId());
1 ✔
828
                        }
829
                }
830
                return null;
1 ✔
831
        }
832
        
833
        /**
834
         * @throws APIException
835
         * @throws MessageException
836
         * @see org.openmrs.api.UserService#setUserActivationKey(org.openmrs.User)
837
         */
838
        @Override
839
        public User setUserActivationKey(User user) throws MessageException {
840
                String token = RandomStringUtils.randomAlphanumeric(20);
1 ✔
841
                long time = System.currentTimeMillis() + getValidTime();
1 ✔
842
                String hashedKey = Security.encodeString(token);
1 ✔
843
                String activationKey = hashedKey + ":" + time;
1 ✔
844
                LoginCredential credentials = dao.getLoginCredential(user);
1 ✔
845
                credentials.setActivationKey(activationKey);
1 ✔
846
                dao.setUserActivationKey(credentials);
1 ✔
847
                
848
                MessageSourceService messages = Context.getMessageSourceService();
1 ✔
849
                AdministrationService adminService = Context.getAdministrationService();
1 ✔
850
                Locale locale = getDefaultLocaleForUser(user);
1 ✔
851
                
852
                //                Delete this method call when removing {@link OpenmrsConstants#GP_HOST_URL}
853
                copyHostURLGlobalPropertyToPasswordResetGlobalProperty(adminService);
1 ✔
854
                
855
                String link = adminService.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_URL)
1 ✔
856
                        .replace("{activationKey}", token);
1 ✔
857
                
858
                Properties mailProperties = Context.getMailProperties();
1 ✔
859
                
860
                String sender = mailProperties.getProperty("mail.from");
1 ✔
861
                
862
                String subject = messages.getMessage("mail.passwordreset.subject", null, locale);
1 ✔
863
                
864
                String body = messages.getMessage("mail.passwordreset.content", null, locale).replace("{name}", user.getUsername())
1 ✔
865
                        .replace("{time}", String.valueOf(getValidTime() / 60000)).replace("{link}", "");
1 ✔
866
                
867
                String msg;
868
                if (mailProperties.getProperty("mail.default_content_type", "text/plain").startsWith("text/html")) {
1 ✔
869
                        String escapedLink = link.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"",
1 ✔
870
                            "&quot;");
871
                        msg = body + "<br/><br/><a href=\"" + escapedLink + "\">" + escapedLink + "</a>";
1 ✔
872
                } else {
1 ✔
873
                        msg = body + "\n\n" + link + "\n";
1 ✔
874
                }
875
                
876
                Context.getMessageService().sendMessage(user.getEmail(), sender, subject, msg);
1 ✔
877
                
878
                return user;
1 ✔
879
        }
880
        
881
        /**
882
         * Delete this method when deleting {@link OpenmrsConstants#GP_HOST_URL}
883
         */
884
        private void copyHostURLGlobalPropertyToPasswordResetGlobalProperty(AdministrationService adminService) {
885
                String hostURLGP = adminService.getGlobalProperty(OpenmrsConstants.GP_HOST_URL);
1 ✔
886
                String passwordResetGP = adminService.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_URL);
1 ✔
887
                if (StringUtils.isNotBlank(hostURLGP) && StringUtils.isBlank(passwordResetGP)) {
1 ✔
UNCOV
888
                        adminService.setGlobalProperty(OpenmrsConstants.GP_PASSWORD_RESET_URL, hostURLGP);
×
889
                }
890
        }
1 ✔
891
        
892
        /**
893
         * @see UserService#getDefaultLocaleForUser(User)
894
         */
895
        @Override
896
        public Locale getDefaultLocaleForUser(User user) {
897
                Locale locale = null;
1 ✔
898
                if (user != null) {
1 ✔
899
                        try {
900
                                String preferredLocale = user.getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCALE);
1 ✔
901
                                if (StringUtils.isNotBlank(preferredLocale)) {
1 ✔
902
                                        locale = LocaleUtility.fromSpecification(preferredLocale);
1 ✔
903
                                }
904
                        }
UNCOV
905
                        catch (Exception e) {
×
UNCOV
906
                                log.warn("Unable to parse user locale into a Locale", e);
×
907
                        }
1 ✔
908
                }
909
                if (locale == null) {
1 ✔
910
                        locale = Context.getLocale();
1 ✔
911
                }
912
                return locale;
1 ✔
913
        }
914
        
915
        /**
916
         * @see org.openmrs.api.UserService#changePasswordUsingActivationKey(String, String);
917
         */
918
        @Override
919
        public void changePasswordUsingActivationKey(String activationKey, String newPassword) {
920
                User user = getUserByActivationKey(activationKey);
1 ✔
921
                if (user == null) {
1 ✔
922
                        throw new InvalidActivationKeyException("activation.key.not.correct");
1 ✔
923
                }
924
                
925
                LoginCredential credentials = dao.getLoginCredentialForUpdate(user);
1 ✔
926
                String storedKey = credentials.getActivationKey();
1 ✔
927
                if (storedKey == null || !storedKey.startsWith(Security.encodeString(activationKey) + ":")) {
1 ✔
UNCOV
928
                        throw new InvalidActivationKeyException("activation.key.not.correct");
×
929
                }
930
                
931
                updatePassword(user, newPassword);
1 ✔
932
        }
1 ✔
933

934
        /**
935
         * @see org.openmrs.api.UserService#getLastLoginTime(User)
936
         */
937
        public String getLastLoginTime(User user) {
938
                return dao.getLastLoginTime(user);
1 ✔
939
        }
940
}
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