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

openmrs / openmrs-core / 43502855768

13 Nov 2026 08:33PM UTC coverage: 67.328% (+0.4%) from 66.969%
43502855768

push

github

ibacher
TRUNK-6616: Count obs version history statements without the privilege check

getObsVersionHistory_shouldLoadTheWholeChainInTwoQueries counted the
statements of the service call, which include its privilege check. When
test setup has cleared the role privilege cache in the same transaction,
that check reads roles from the database, so the count depended on test
order. Measure the DAO call instead.

26896 of 39948 relevant lines covered (67.33%)

0.67 hits per line

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

87.55
/api/src/main/java/org/openmrs/api/context/UserContext.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.context;
11

12
import org.apache.commons.lang3.StringUtils;
13
import org.openmrs.Location;
14
import org.openmrs.PrivilegeListener;
15
import org.openmrs.Role;
16
import org.openmrs.User;
17
import org.openmrs.UserSessionListener;
18
import org.openmrs.UserSessionListener.Event;
19
import org.openmrs.UserSessionListener.Status;
20
import org.openmrs.api.APIAuthenticationException;
21
import org.openmrs.api.LocationService;
22
import org.openmrs.api.cache.RolePrivilegeCache;
23
import org.openmrs.api.cache.RolePrivileges;
24
import org.openmrs.util.LocaleUtility;
25
import org.openmrs.util.OpenmrsConstants;
26
import org.openmrs.util.PrivilegeConstants;
27
import org.openmrs.util.RoleConstants;
28
import org.slf4j.Logger;
29
import org.slf4j.LoggerFactory;
30

31
import java.io.Serializable;
32
import java.util.ArrayList;
33
import java.util.Arrays;
34
import java.util.Collections;
35
import java.util.HashSet;
36
import java.util.List;
37
import java.util.Locale;
38
import java.util.Objects;
39
import java.util.Set;
40
import java.util.concurrent.atomic.AtomicBoolean;
41
import java.util.stream.Collectors;
42

43
/**
44
 * Represents an OpenMRS <code>User Context</code> which stores the current user information. Only
45
 * one <code>User</code> may be authenticated within a UserContext at any given time. The
46
 * UserContext should not be accessed directly, but rather used through the <code>Context</code>.
47
 * This class should be kept light-weight. There is one instance of this class per user that is
48
 * logged into the system.
49
 *
50
 * @see org.openmrs.api.context.Context
51
 */
52
public class UserContext implements Serializable {
53
        
54
        private static final long serialVersionUID = -806631231941890648L;
55
        
56
        /**
57
         * Logger - shared by entire class
58
         */
59
        private static final Logger log = LoggerFactory.getLogger(UserContext.class);
1 ✔
60
        
61
        /**
62
         * Guards the one-time warning emitted when the role privilege cache component cannot be obtained
63
         * outside of a context refresh. Static so the warning is emitted once across all user contexts
64
         * rather than once per session.
65
         */
66
        private static final AtomicBoolean rolePrivilegeCacheUnavailableWarned = new AtomicBoolean(false);
1 ✔
67

68
        /**
69
         * The authenticated user, with the id and roles read from the database when they were loaded.
70
         * Privilege checks, role checks and refreshes use these recorded values, never the user object,
71
         * which any caller can change in memory. Replaced as a whole, so a check never mixes one user's id
72
         * with another's roles. Null in a session serialized before this field existed, which is treated as
73
         * logged out.
74
         */
75
        private volatile Principal principal = Principal.NONE;
1 ✔
76

77
        /**
78
         * User's permission proxies
79
         */
80
        private final List<String> proxies = Collections.synchronizedList(new ArrayList<>());
1 ✔
81
        
82
        /**
83
         * User's locale
84
         */
85
        private Locale locale = null;
1 ✔
86
        
87
        /**
88
         * Cached Role given to all authenticated users
89
         */
90
        private Role authenticatedRole = null;
1 ✔
91
        
92
        /**
93
         * Cache Role given to all users
94
         */
95
        private Role anonymousRole = null;
1 ✔
96
        
97
        /**
98
         * User's defined location
99
         */
100
        private Integer locationId;
101
        
102
        /**
103
         * The authentication scheme for this user
104
         */
105
        private final AuthenticationScheme authenticationScheme;
106
        
107
        /**
108
         * Creates a user context based on the provided auth. scheme.
109
         *
110
         * @param authenticationScheme The auth. scheme that applies for this user context.
111
         * @since 2.3.0
112
         */
113
        public UserContext(AuthenticationScheme authenticationScheme) {
1 ✔
114
                this.authenticationScheme = authenticationScheme;
1 ✔
115
        }
1 ✔
116
        
117
        /**
118
         * Authenticate user with the provided credentials. The authentication scheme must be Spring wired, see {@link Context#getAuthenticationScheme()}.
119
         *
120
         * @param credentials The credentials to use to authenticate
121
         * @return The authenticated client information
122
         * @throws ContextAuthenticationException if authentication fails
123
         * @since 2.3.0
124
         */
125
        public Authenticated authenticate(Credentials credentials)
126
                throws ContextAuthenticationException {
127
                
128
                log.debug("Authenticating client '{}' with scheme '{}'", credentials.getClientName(),
1 ✔
129
                        credentials.getAuthenticationScheme());
1 ✔
130
                
131
                Authenticated authenticated = null;
1 ✔
132
                try {
133
                        authenticated = authenticationScheme.authenticate(credentials);
1 ✔
134
                        setUser(authenticated.getUser());
1 ✔
135
                        notifyUserSessionListener(getAuthenticatedUser(), Event.LOGIN, Status.SUCCESS);
1 ✔
136
                } catch (ContextAuthenticationException e) {
1 ✔
137
                        User loggingInUser = new User();
1 ✔
138
                        loggingInUser.setUsername(credentials.getClientName());
1 ✔
139
                        notifyUserSessionListener(loggingInUser, Event.LOGIN, Status.FAIL);
1 ✔
140
                        throw e;
1 ✔
141
                }
1 ✔
142
                
143
                setUserLocation(true);
1 ✔
144
                setUserLocale(true);
1 ✔
145

146
                log.debug("Authenticated as: {}", getAuthenticatedUser());
1 ✔
147

148
                return authenticated;
1 ✔
149
        }
150
        
151
        /**
152
         * Refresh the authenticated user object in this UserContext. This should be used when updating
153
         * information in the database about the current user and it needs to be reflecting in the
154
         * (cached) {@link #getAuthenticatedUser()} User object.
155
         *
156
         * @since 1.5
157
         */
158
        public void refreshAuthenticatedUser() {
159
                log.debug("Refreshing authenticated user");
1 ✔
160

161
                if (isAuthenticated()) {
1 ✔
162
                        // by the id recorded when the user was loaded, never the user object's, which any caller can
163
                        // change in memory; read through ContextDAO rather than UserService: the user may lack Get Users
164
                        Integer userId = getPrincipal().userId;
1 ✔
165
                        User user = userId == null ? null : hydrate(Context.getContextDAO().getUserById(userId));
1 ✔
166
                        principal = Principal.of(user, userId);
1 ✔
167
                        //update the stored location in the user's session
168
                        setUserLocation(false);
1 ✔
169
                        setUserLocale(false);
1 ✔
170
                }
171
        }
1 ✔
172
        
173
        /**
174
         * Makes the given user the authenticated one, or logs out if null. Package-private for tests; see
175
         * {@link Principal#of(User)} for how the user's roles are recorded.
176
         */
177
        void setUser(User newUser) {
178
                principal = Principal.of(newUser);
1 ✔
179
        }
1 ✔
180

181
        private Principal getPrincipal() {
182
                Principal current = principal;
1 ✔
183
                return current == null ? Principal.NONE : current;
1 ✔
184
        }
185

186
        /**
187
         * Initializes the user's lazy state, since the user is kept beyond the Hibernate session it was
188
         * loaded in.
189
         */
190
        private static User hydrate(User user) {
191
                if (user != null) {
1 ✔
192
                        user.getAllRoles().size();
1 ✔
193
                        user.getUserProperties().size();
1 ✔
194
                        user.getPrivileges().size();
1 ✔
195
                }
196
                return user;
1 ✔
197
        }
198

199
        /**
200
         * Change current authentication to become another user. (You can only do this if you're already
201
         * authenticated as a superuser.)
202
         *
203
         * @param systemId
204
         * @return The new user that this context has been set to. (null means no change was made)
205
         * @throws ContextAuthenticationException
206
         */
207
        public User becomeUser(String systemId) throws ContextAuthenticationException {
208
                if (!Daemon.isDaemonThread() && !hasRole(RoleConstants.SUPERUSER)) {
1 ✔
209
                        throw new APIAuthenticationException("You must be a superuser to assume another user's identity");
1 ✔
210
                }
211
                
212
                log.debug("Turning the authenticated user into user with systemId: {}", systemId);
1 ✔
213
                
214
                User userToBecome = Context.getUserService().getUserByUsername(systemId);
1 ✔
215
                
216
                if (userToBecome == null) {
1 ✔
217
                        throw new ContextAuthenticationException("User not found with systemId: " + systemId);
×
218
                }
219
                
220
                // hydrate the user object
221
                if (userToBecome.getAllRoles() != null) {
1 ✔
222
                        userToBecome.getAllRoles().size();
1 ✔
223
                }
224
                
225
                if (userToBecome.getUserProperties() != null) {
1 ✔
226
                        userToBecome.getUserProperties().size();
1 ✔
227
                }
228
                
229
                if (userToBecome.getPrivileges() != null) {
1 ✔
230
                        userToBecome.getPrivileges().size();
1 ✔
231
                }
232

233
                setUser(userToBecome);
1 ✔
234

235
                //update the user's location and locale
236
                setUserLocation(false);
1 ✔
237
                setUserLocale(false);
1 ✔
238

239
                log.debug("Becoming user: {}", userToBecome);
1 ✔
240

241
                return userToBecome;
1 ✔
242
        }
243
        
244
        /**
245
         * @return "active" user who has been authenticated, otherwise <code>null</code>
246
         */
247
        public User getAuthenticatedUser() {
248
                return getPrincipal().user;
1 ✔
249
        }
250

251
        /**
252
         * @return the id the authenticated user had when they were loaded, which, unlike the id on
253
         *         {@link #getAuthenticatedUser()}, can't be changed in memory; the daemon user's id on a
254
         *         daemon thread; or null if no stored user is authenticated
255
         * @since 2.8.11
256
         */
257
        public Integer getAuthenticatedUserId() {
258
                if (Daemon.isDaemonThread()) {
1 ✔
259
                        User daemonUser = Daemon.getDaemonThreadUser();
1 ✔
260
                        return daemonUser == null ? null : daemonUser.getUserId();
1 ✔
261
                }
262

263
                return getPrincipal().userId;
1 ✔
264
        }
265
        
266
        /**
267
         * @return true if user has been authenticated in this UserContext
268
         */
269
        public boolean isAuthenticated() {
270
                return getAuthenticatedUser() != null;
1 ✔
271
        }
272
        
273
        /**
274
         * logs out the "active" (authenticated) user within this UserContext
275
         *
276
         * @see #authenticate
277
         */
278
        public void logout() {
279
                log.debug("setting user to null on logout");
1 ✔
280
                notifyUserSessionListener(getAuthenticatedUser(), Event.LOGOUT, Status.SUCCESS);
1 ✔
281
                setUser(null);
1 ✔
282
                locationId = null;
1 ✔
283
                locale = null;
1 ✔
284
                proxies.clear();
1 ✔
285
        }
1 ✔
286
        
287
        /**
288
         * Gives the given privilege to all calls to hasPrivilege. This method was visualized as being
289
         * used as follows (try/finally is important):
290
         *
291
         * <pre>
292
         * try {
293
         *   Context.addProxyPrivilege(&quot;AAA&quot;);
294
         *   Context.get*Service().methodRequiringAAAPrivilege();
295
         * }
296
         * finally {
297
         *   Context.removeProxyPrivilege(&quot;AAA&quot;);
298
         * }
299
         * </pre>
300
         *
301
         * @param privilege to give to users
302
         */
303
        public void addProxyPrivilege(String privilege) {
304
                if (privilege == null) {
1 ✔
305
                        throw new IllegalArgumentException("UserContext.addProxyPrivilege does not accept null privileges");
1 ✔
306
                }
307

308
                log.debug("Adding proxy privilege: {}", privilege);
1 ✔
309
                proxies.add(privilege);
1 ✔
310
        }
1 ✔
311
        
312
        /**
313
         * Will remove one instance of privilege from the privileges that are currently proxied
314
         *
315
         * @param privilege Privilege to remove in string form
316
         */
317
        public void removeProxyPrivilege(String privilege) {
318
                if (privilege == null) {
1 ✔
319
                        return;
1 ✔
320
                }
321

322
                log.debug("Removing privilege: {}", privilege);
1 ✔
323
                proxies.remove(privilege);
1 ✔
324
        }
1 ✔
325
        
326
        /**
327
         * Adds one or more privileges to the list of privileges that that {@link #hasPrivilege(String)} will
328
         * regard as available regardless of whether the user would otherwise have the privilege.
329
         * <p/>
330
         * This is useful for situations where a system process may need access to some piece of data that the
331
         * user would not otherwise have access to, like a GlobalProperty. <strong>This facility should not be
332
         * used to return data to the user that they otherwise would be unable to see.</strong>
333
         * <p/>
334
         * The expected usage is:
335
         * <p/>
336
         * <pre>{@code
337
         * try {
338
         *   Context.addProxyPrivilege(&quot;AAA&quot;);
339
         *   Context.get*Service().methodRequiringAAAPrivilege();
340
         * }
341
         * finally {
342
         *   Context.removeProxyPrivilege(&quot;AAA&quot;);
343
         * }}
344
         * </pre>
345
         * <p/>
346
         *
347
         * @param privileges privileges to add in string form
348
         * @see #hasPrivilege(String)
349
         * @see #removeProxyPrivilege(String...)
350
         */
351
        public void addProxyPrivilege(String... privileges) {
352
                if (privileges == null || Arrays.stream(privileges).anyMatch(Objects::isNull)) {
1 ✔
353
                        throw new IllegalArgumentException("UserContext.addProxyPrivilege does not accept null privileges");
1 ✔
354
                }
355
                
356
                for (String privilege : privileges) {
1 ✔
357
                        addProxyPrivilege(privilege);
1 ✔
358
                }
359
        }
1 ✔
360
        
361
        /**
362
         * Removes one or more privileges to the list of privileges that that {@link #hasPrivilege(String)} will
363
         * regard as available regardless of whether the user would otherwise have the privilege.
364
         * <p/>
365
         * This is the compliment for {@link #addProxyPrivilege(String...)} to clean-up the context.
366
         * <p/>
367
         *
368
         * @param privileges privileges to remove in string form
369
         * @see #hasPrivilege(String)
370
         * @see #addProxyPrivilege(String...)
371
         */
372
        public void removeProxyPrivilege(String... privileges) {
373
                if (privileges == null || Arrays.stream(privileges).allMatch(Objects::isNull)) {
1 ✔
374
                        return;
1 ✔
375
                }
376
                
377
                for (String privilege : privileges) {
1 ✔
378
                        if (privilege != null) {
1 ✔
379
                                removeProxyPrivilege(privilege);
1 ✔
380
                        }
381
                }
382
        }
1 ✔
383

384
        /**
385
         * @return true if there are any proxy privileges
386
         * @since 2.9.0
387
         */
388
        public boolean hasProxyPrivileges() {
389
                return !proxies.isEmpty();
1 ✔
390
        }
391
        
392
        /**
393
         * @param locale new locale for this context
394
         */
395
        public void setLocale(Locale locale) {
396
                this.locale = locale;
1 ✔
397
        }
1 ✔
398
        
399
        /**
400
         * @return current locale for this context
401
         */
402
        public Locale getLocale() {
403
                if (locale == null) {
1 ✔
404
                        // don't cache default locale - allows recognition of changed default at login page
405
                        return LocaleUtility.getDefaultLocale();
1 ✔
406
                }
407
                
408
                return locale;
1 ✔
409
        }
410
        
411
        /**
412
         * Gets all the roles for the (un)authenticated user. Anonymous and Authenticated roles are
413
         * appended if necessary
414
         *
415
         * @return all expanded roles for a user
416
         * @throws Exception
417
         */
418
        public Set<Role> getAllRoles() throws Exception {
419
                return getAllRoles(getAuthenticatedUser());
1 ✔
420
        }
421
        
422
        /**
423
         * Gets all the roles for a user. Anonymous and Authenticated roles are appended if necessary
424
         *
425
         * @param user
426
         * @return all expanded roles for a user
427
         * <strong>Should</strong> not fail with null user
428
         * <strong>Should</strong> add anonymous role to all users
429
         * <strong>Should</strong> add authenticated role to all authenticated users
430
         * <strong>Should</strong> return same roles as user getAllRoles method
431
         */
432
        public Set<Role> getAllRoles(User user) throws Exception {
433
                Set<Role> roles = new HashSet<>();
1 ✔
434
                
435
                // add the Anonymous Role
436
                roles.add(getAnonymousRole());
1 ✔
437
                
438
                // add the Authenticated role
439
                if (getAuthenticatedUser() != null && getAuthenticatedUser().equals(user)) {
1 ✔
440
                        roles.addAll(user.getAllRoles());
1 ✔
441
                        roles.add(getAuthenticatedRole());
1 ✔
442
                }
443
                
444
                return roles;
1 ✔
445
        }
446
        
447
        /**
448
         * Unlike {@link #getAllRoles()}, which reads the authenticated user's roles in memory, this gives
449
         * the roles privilege checks use.
450
         *
451
         * @return the names of the roles the authenticated user held when loaded, plus
452
         *         {@link RoleConstants#AUTHENTICATED} if a user is authenticated, and
453
         *         {@link RoleConstants#ANONYMOUS}; not including the roles those inherit
454
         * @since 2.8.11
455
         */
456
        public Set<String> getAssignedRoleNames() {
457
                Set<String> names = new HashSet<>();
×
458
                Principal current = getPrincipal();
×
459
                if (current.isAuthenticated()) {
×
460
                        names.addAll(current.roleNames);
×
461
                        names.add(RoleConstants.AUTHENTICATED);
×
462
                }
463
                names.add(RoleConstants.ANONYMOUS);
×
464
                return names;
×
465
        }
466

467
        /**
468
         * Tests whether the authenticated user holds a role, directly or by inheritance, as stored when
469
         * they were loaded. Like {@link User#hasRole(String)}, a superuser holds every role, and names are
470
         * compared case-insensitively.
471
         *
472
         * @param role the name of the role
473
         * @return true if the authenticated user holds the role
474
         * @since 2.8.11
475
         */
476
        public boolean hasRole(String role) {
477
                Principal current = getPrincipal();
1 ✔
478
                if (!current.isAuthenticated()) {
1 ✔
479
                        return false;
×
480
                }
481
                RolePrivilegeCache cache = getRolePrivilegeCache();
1 ✔
482
                for (String roleName : current.roleNames) {
1 ✔
483
                        if (roleName.equalsIgnoreCase(role)) {
1 ✔
484
                                return true;
1 ✔
485
                        }
486
                }
1 ✔
487
                for (String roleName : current.roleNames) {
1 ✔
488
                        RolePrivileges rolePrivileges = resolveRole(cache, roleName);
1 ✔
489
                        if (rolePrivileges.grantsSuperuser() || rolePrivileges.includesRole(role)) {
1 ✔
490
                                return true;
1 ✔
491
                        }
492
                }
1 ✔
493
                return false;
1 ✔
494
        }
495

496
        /**
497
         * Tests whether the currently authenticated user has a particular privilege
498
         *
499
         * @param privilege The privilege to check if it's available
500
         * @return true if authenticated user has given privilege
501
         * <strong>Should</strong> authorize if authenticated user has specified privilege
502
         * <strong>Should</strong> authorize if authenticated role has specified privilege
503
         * <strong>Should</strong> authorize if proxied user has specified privilege
504
         * <strong>Should</strong> authorize if anonymous user has specified privilege
505
         * <strong>Should</strong> not authorize if authenticated user does not have specified privilege
506
         * <strong>Should</strong> not authorize if authenticated role does not have specified privilege
507
         * <strong>Should</strong> not authorize if proxied user does not have specified privilege
508
         * <strong>Should</strong> not authorize if anonymous user does not have specified privilege
509
         */
510
        public boolean hasPrivilege(String privilege) {
511
                return hasPrivilege(privilege, true);
1 ✔
512
        }
513

514
        /**
515
         * Tests whether the current user has a particular privilege, optionally excluding proxy privileges.
516
         * <p>
517
         * Passing <code>false</code> resolves the privilege only from the user's roles (and the anonymous
518
         * and authenticated roles), ignoring any {@link #addProxyPrivilege(String...) proxy privileges}.
519
         * This is intended for per-resource access checks that must reflect the user's actual granted roles
520
         * and must not be satisfied by a proxy privilege added merely to invoke the surrounding service
521
         * method. Role privileges are still resolved authoritatively (from the role privilege cache),
522
         * unlike {@link User#hasPrivilege(String)} which reads a potentially stale in-memory role graph.
523
         *
524
         * @param privilege The privilege to check if it's available
525
         * @param includeProxyPrivileges whether proxy privileges may satisfy the check
526
         * @return true if the current user has the given privilege
527
         * @since 3.0.0, 2.9.0, 2.8.9
528
         */
529
        public boolean hasPrivilege(String privilege, boolean includeProxyPrivileges) {
530
                if (includeProxyPrivileges) {
1 ✔
531
                        log.debug("Checking '{}' against proxies: {}", privilege, proxies);
1 ✔
532
                        // check proxied privileges; ArrayList so we have a consistent view
533
                        for (String s : new ArrayList<>(proxies)) {
1 ✔
534
                                if (s.equals(privilege)) {
1 ✔
535
                                        notifyPrivilegeListeners(getAuthenticatedUser(), privilege, true);
1 ✔
536
                                        return true;
1 ✔
537
                                }
538
                        }
1 ✔
539
                }
540

541
                boolean hasPrivilege = resolvePrivilege(privilege);
1 ✔
542
                notifyPrivilegeListeners(getAuthenticatedUser(), privilege, hasPrivilege);
1 ✔
543
                return hasPrivilege;
1 ✔
544
        }
545

546
        /**
547
         * Resolves whether the current user (authenticated or anonymous) holds the given privilege by
548
         * consulting the per-role privilege cache instead of recursively re-expanding the role graph on
549
         * every call. Proxy privileges are handled separately by {@link #hasPrivilege(String)}.
550
         *
551
         * @param privilege the privilege to check
552
         * @return true if the privilege is granted
553
         */
554
        private boolean resolvePrivilege(String privilege) {
555
                RolePrivilegeCache cache = getRolePrivilegeCache();
1 ✔
556

557
                // if a user has logged in, check their privileges
558
                Principal current = getPrincipal();
1 ✔
559
                if (current.isAuthenticated()) {
1 ✔
560
                        // All authenticated users have the "" (empty) privilege, matching User.hasPrivilege.
561
                        if (StringUtils.isEmpty(privilege)) {
1 ✔
562
                                return true;
1 ✔
563
                        }
564

565
                        for (String roleName : current.roleNames) {
1 ✔
566
                                if (roleGrants(cache, roleName, privilege)) {
1 ✔
567
                                        return true;
1 ✔
568
                                }
569
                        }
1 ✔
570

571
                        // by name, never the cached Role instance, which getAllRoles hands to callers
572
                        if (roleGrants(cache, RoleConstants.AUTHENTICATED, privilege)) {
1 ✔
573
                                return true;
1 ✔
574
                        }
575
                }
576

577
                return roleGrants(cache, RoleConstants.ANONYMOUS, privilege);
1 ✔
578
        }
579

580
        /**
581
         * Tests whether a single role (and its inherited closure) grants the given privilege.
582
         *
583
         * @param cache the role privilege cache, or <code>null</code> if unavailable
584
         * @param roleName the name of the directly assigned role to test
585
         * @param privilege the privilege to check
586
         * @return true if the role grants superuser status or contains the privilege
587
         */
588
        private boolean roleGrants(RolePrivilegeCache cache, String roleName, String privilege) {
589
                RolePrivileges rolePrivileges = resolveRole(cache, roleName);
1 ✔
590
                return rolePrivileges.grantsSuperuser() || rolePrivileges.containsPrivilege(privilege);
1 ✔
591
        }
592

593
        /**
594
         * Resolves a role as stored, through the cache when it is available. Without it, as while the
595
         * application context refreshes, the role is read from the database on every call, and grants
596
         * nothing if that read fails.
597
         *
598
         * @param cache the role privilege cache, or <code>null</code> if unavailable
599
         * @param roleName the name of the role
600
         * @return the role's flattened privileges
601
         */
602
        private static RolePrivileges resolveRole(RolePrivilegeCache cache, String roleName) {
603
                if (cache != null) {
1 ✔
604
                        return cache.getRolePrivileges(roleName);
1 ✔
605
                }
606
                try {
607
                        return RolePrivilegeCache.resolve(roleName, Context.getContextDAO()::getStoredRole);
×
608
                } catch (RuntimeException e) {
×
609
                        log.error("Could not read role {} without the role privilege cache; it grants nothing", roleName, e);
×
610
                        return new RolePrivileges(Collections.emptySet(), false);
×
611
                }
612
        }
613

614
        /**
615
         * Looks up the {@link RolePrivilegeCache} component, or returns <code>null</code> so callers fall
616
         * back to direct computation. Absence during a context refresh is expected (logged at debug);
617
         * absence otherwise is a misconfiguration that silently drops every check to the uncached path, so
618
         * it is warned once.
619
         *
620
         * @return the cache component, or <code>null</code> if unavailable
621
         */
622
        private RolePrivilegeCache getRolePrivilegeCache() {
623
                try {
624
                        return Context.getRegisteredComponent("rolePrivilegeCache", RolePrivilegeCache.class);
1 ✔
625
                } catch (Exception e) {
×
626
                        if (Context.isRefreshingContext()) {
×
627
                                log.debug("Role privilege cache is unavailable while the context is refreshing; "
×
628
                                        + "computing role privileges directly",
629
                                    e);
630
                        } else if (rolePrivilegeCacheUnavailableWarned.compareAndSet(false, true)) {
×
631
                                log.warn("Could not obtain the rolePrivilegeCache component; privilege checks will recompute role "
×
632
                                        + "privileges on every call until this is resolved",
633
                                    e);
634
                        }
635
                        return null;
×
636
                }
637
        }
638
        
639
        /**
640
         * Convenience method to get the Role in the system designed to be given to all users
641
         *
642
         * @return Role
643
         * <strong>Should</strong> fail if database doesn't contain anonymous role
644
         */
645
        private Role getAnonymousRole() {
646
                if (anonymousRole != null) {
1 ✔
647
                        return anonymousRole;
×
648
                }
649
                
650
                anonymousRole = readImplicitRole(RoleConstants.ANONYMOUS);
1 ✔
651
                if (anonymousRole == null) {
1 ✔
652
                        throw new RuntimeException(
×
653
                                "Database out of sync with code: " + RoleConstants.ANONYMOUS + " role does not exist");
654
                }
655
                
656
                return anonymousRole;
1 ✔
657
        }
658
        
659
        /**
660
         * Convenience method to get the Role in the system designed to be given to all users that have
661
         * authenticated in some manner
662
         *
663
         * @return Role
664
         * <strong>Should</strong> fail if database doesn't contain authenticated role
665
         */
666
        private Role getAuthenticatedRole() {
667
                if (authenticatedRole != null) {
1 ✔
668
                        return authenticatedRole;
×
669
                }
670
                
671
                authenticatedRole = readImplicitRole(RoleConstants.AUTHENTICATED);
1 ✔
672
                if (authenticatedRole == null) {
1 ✔
673
                        throw new RuntimeException("Database out of sync with code: " + RoleConstants.AUTHENTICATED
×
674
                                + " role does not exist");
675
                }
676
                
677
                return authenticatedRole;
1 ✔
678
        }
679
        
680
        /**
681
         * Holds the proxy privilege around the read because {@code getRole} is itself privilege-checked;
682
         * without it, resolving any privilege recurses.
683
         */
684
        private Role readImplicitRole(String roleName) {
685
                Context.addProxyPrivilege(PrivilegeConstants.GET_ROLES);
1 ✔
686
                try {
687
                        return Context.getUserService().getRole(roleName);
1 ✔
688
                } finally {
689
                        Context.removeProxyPrivilege(PrivilegeConstants.GET_ROLES);
1 ✔
690
                }
691
        }
692
        
693
        /**
694
         * @return locationId for this user context if any is set
695
         * @since 1.10
696
         */
697
        public Integer getLocationId() {
698
                return locationId;
×
699
        }
700
        
701
        /**
702
         * @param locationId locationId to set
703
         * @since 1.10
704
         */
705
        public void setLocationId(Integer locationId) {
706
                this.locationId = locationId;
1 ✔
707
        }
1 ✔
708
        
709
        /**
710
         * @return current location for this user context if any is set
711
         * @since 1.9
712
         */
713
        public Location getLocation() {
714
                if (locationId == null) {
1 ✔
715
                        return null;
1 ✔
716
                }
717
                return Context.getLocationService().getLocation(locationId);
1 ✔
718
        }
719
        
720
        /**
721
         * @param location the location to set to
722
         * @since 1.9
723
         */
724
        public void setLocation(Location location) {
725
                if (location != null) {
1 ✔
726
                        this.locationId = location.getLocationId();
1 ✔
727
                }
728
        }
1 ✔
729
        
730
        /**
731
         * Convenience method that sets the default location of the currently authenticated user using
732
         * the value of the user's default location property
733
         */
734
        private void setUserLocation(boolean useDefault) {
735
                // location should be null if no user is logged in
736
                User user = getAuthenticatedUser();
1 ✔
737
                if (user == null) {
1 ✔
738
                        this.locationId = null;
×
739
                        return;
×
740
                }
741
                
742
                // intended to be when the user initially authenticates
743
                if (this.locationId == null && useDefault) {
1 ✔
744
                        this.locationId = getDefaultLocationId(user);
1 ✔
745
                }
746
        }
1 ✔
747

748
        /**
749
         * Convenience method that sets the default locale used by the currently authenticated user, using
750
         * the value of the user's default local property
751
         */
752
        private void setUserLocale(boolean useDefault) {
753
                // local should be null if no user is logged in
754
                User user = getAuthenticatedUser();
1 ✔
755
                if (user == null) {
1 ✔
756
                        this.locale = null;
×
757
                        return;
×
758
                }
759

760
                // intended to be when the user initially authenticates
761
                if (user.getUserProperties().containsKey("defaultLocale")) {
1 ✔
762
                        String localeString = user.getUserProperty("defaultLocale");
1 ✔
763
                        locale = LocaleUtility.fromSpecification(localeString);
1 ✔
764
                }
765

766
                if (locale == null && useDefault) {
1 ✔
767
                        locale = LocaleUtility.getDefaultLocale();
1 ✔
768
                }
769

770
        }
1 ✔
771
        
772
        protected Integer getDefaultLocationId(User user) {
773
                String defaultLocation = user.getUserProperty(OpenmrsConstants.USER_PROPERTY_DEFAULT_LOCATION);
1 ✔
774
                if (StringUtils.isNotBlank(defaultLocation)) {
1 ✔
775
                        LocationService ls = Context.getLocationService();
1 ✔
776
                        //only go ahead if it has actually changed OR if wasn't set before
777
                        try {
778
                                int defaultId = Integer.parseInt(defaultLocation);
1 ✔
779
                                if (this.locationId == null || this.locationId != defaultId) {
1 ✔
780
                                        // validate that the id is a valid id
781
                                        if (ls.getLocation(defaultId) != null) {
1 ✔
782
                                                return defaultId;
1 ✔
783
                                        }
784
                                }
785
                        }
786
                        catch (NumberFormatException ignored) {
1 ✔
787
                        }
1 ✔
788

789
                        Location possibleLocation = ls.getLocationByUuid(defaultLocation);
1 ✔
790

791
                        if (possibleLocation != null && (this.locationId == null || !this.locationId.equals(possibleLocation.getId()))) {
1 ✔
792
                                return possibleLocation.getId();
1 ✔
793
                        }
794

795
                        log.warn("The default location for user '{}' is set to '{}', which is not a valid location",
1 ✔
796
                                user.getUsername(), defaultLocation);
1 ✔
797
                }
798
                
799
                return null;
1 ✔
800
        }
801
        
802
        /**
803
         * Notifies privilege listener beans about any privilege check.
804
         * <p>
805
         * It is called by {@link UserContext#hasPrivilege(java.lang.String)}.
806
         *
807
         * @param user         the authenticated user or <code>null</code> if not authenticated
808
         * @param privilege    the checked privilege
809
         * @param hasPrivilege <code>true</code> if the authenticated user has the required privilege or
810
         *                     if it is a proxy privilege
811
         * @see PrivilegeListener
812
         * @since 1.8.4, 1.9.1, 1.10
813
         */
814
        private void notifyPrivilegeListeners(User user, String privilege, boolean hasPrivilege) {
815
                for (PrivilegeListener privilegeListener : Context.getRegisteredComponents(PrivilegeListener.class)) {
1 ✔
816
                        try {
817
                                privilegeListener.privilegeChecked(user, privilege, hasPrivilege);
1 ✔
818
                        }
819
                        catch (Exception e) {
×
820
                                log.error("Privilege listener has failed", e);
×
821
                        }
1 ✔
822
                }
1 ✔
823
        }
1 ✔
824
        
825
        private void notifyUserSessionListener(User user, Event event, Status status) {
826
                for (UserSessionListener userSessionListener : Context.getRegisteredComponents(UserSessionListener.class)) {
1 ✔
827
                        userSessionListener.loggedInOrOut(user, event, status);
1 ✔
828
                }
1 ✔
829
        }
1 ✔
830

831
        /**
832
         * The authenticated user's identity and roles as read from the database when they were loaded.
833
         */
834
        private static final class Principal implements Serializable {
835

836
                private static final long serialVersionUID = 1L;
837

838
                private static final Principal NONE = new Principal(null, null, Collections.emptySet());
1 ✔
839

840
                /** The user object this was recorded for */
841
                private final User user;
842

843
                private final Integer userId;
844

845
                /** Names of the roles the user holds directly */
846
                private final Set<String> roleNames;
847

848
                private Principal(User user, Integer userId, Set<String> roleNames) {
1 ✔
849
                        this.user = user;
1 ✔
850
                        this.userId = userId;
1 ✔
851
                        this.roleNames = Collections.unmodifiableSet(new HashSet<>(roleNames));
1 ✔
852
                }
1 ✔
853

854
                private boolean isAuthenticated() {
855
                        return user != null;
1 ✔
856
                }
857

858
                /**
859
                 * Records a stored user's roles as read from the database. A user that isn't stored, as in tests or
860
                 * authentication schemes that don't persist users, keeps its in-memory roles.
861
                 */
862
                private static Principal of(User user) {
863
                        return user == null ? NONE : of(user, user.getUserId());
1 ✔
864
                }
865

866
                /**
867
                 * As {@link #of(User)}, but for a user already known to be stored under {@code userId}, such as one
868
                 * reloaded by that id, whose own id may have been changed in memory.
869
                 */
870
                private static Principal of(User user, Integer userId) {
871
                        if (user == null) {
1 ✔
872
                                return NONE;
×
873
                        }
874
                        Set<String> roleNames;
875
                        if (userId != null) {
1 ✔
876
                                roleNames = Context.getContextDAO().getStoredRoleNames(userId);
1 ✔
877
                        } else {
878
                                roleNames = user.getRoles() == null ? Collections.emptySet()
1 ✔
879
                                        : user.getRoles().stream().filter(Objects::nonNull).map(Role::getRole).filter(Objects::nonNull)
1 ✔
880
                                                .collect(Collectors.toSet());
1 ✔
881
                        }
882
                        return new Principal(user, userId, roleNames);
1 ✔
883
                }
884
        }
885
}
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