]> git.argeo.org Git - lgpl/argeo-commons.git/blob - CurrentUser.java
16ac638c107a943422e84a059b0a79414f68e54f
[lgpl/argeo-commons.git] / CurrentUser.java
1 package org.argeo.cms.auth;
2
3 import java.security.AccessController;
4 import java.security.Principal;
5 import java.security.PrivilegedAction;
6 import java.security.PrivilegedActionException;
7 import java.security.PrivilegedExceptionAction;
8 import java.util.HashSet;
9 import java.util.Iterator;
10 import java.util.Locale;
11 import java.util.Set;
12 import java.util.UUID;
13 import java.util.concurrent.Callable;
14 import java.util.concurrent.CompletionException;
15
16 import javax.security.auth.Subject;
17 import javax.security.auth.x500.X500Principal;
18
19 import org.argeo.api.cms.CmsConstants;
20 import org.argeo.api.cms.CmsSession;
21 import org.argeo.api.cms.CmsSessionId;
22 import org.argeo.cms.internal.auth.CmsSessionImpl;
23 import org.argeo.cms.internal.auth.ImpliedByPrincipal;
24 import org.argeo.cms.internal.runtime.CmsContextImpl;
25 import org.osgi.service.useradmin.Authorization;
26
27 /**
28 * Programmatic access to the currently authenticated user, within a CMS
29 * context.
30 */
31 public final class CurrentUser {
32 /*
33 * CURRENT USER API
34 */
35
36 /**
37 * Technical username of the currently authenticated user.
38 *
39 * @return the authenticated username or null if not authenticated / anonymous
40 */
41 public static String getUsername() {
42 return getUsername(currentSubject());
43 }
44
45 /**
46 * Human readable name of the currently authenticated user (typically first name
47 * and last name).
48 */
49 public static String getDisplayName() {
50 return getDisplayName(currentSubject());
51 }
52
53 /** Whether a user is currently authenticated. */
54 public static boolean isAnonymous() {
55 return isAnonymous(currentSubject());
56 }
57
58 /** Locale of the current user */
59 public final static Locale locale() {
60 return locale(currentSubject());
61 }
62
63 /** Roles of the currently logged-in user */
64 public final static Set<String> roles() {
65 return roles(currentSubject());
66 }
67
68 /** Returns true if the current user is in the specified role */
69 public static boolean isInRole(String role) {
70 Set<String> roles = roles();
71 return roles.contains(role);
72 }
73
74 /** Implies this {@link SystemRole} in this context. */
75 public final static boolean implies(SystemRole role, String context) {
76 return role.implied(currentSubject(), context);
77 }
78
79 /** Executes as the current user */
80 public final static <T> T doAs(PrivilegedAction<T> action) {
81 return Subject.doAs(currentSubject(), action);
82 }
83
84 /** Executes as the current user */
85 public final static <T> T tryAs(PrivilegedExceptionAction<T> action) throws PrivilegedActionException {
86 return Subject.doAs(currentSubject(), action);
87 }
88
89 /*
90 * WRAPPERS
91 */
92
93 public final static String getUsername(Subject subject) {
94 if (subject == null)
95 throw new IllegalArgumentException("Subject cannot be null");
96 if (subject.getPrincipals(X500Principal.class).size() != 1)
97 return CmsConstants.ROLE_ANONYMOUS;
98 Principal principal = subject.getPrincipals(X500Principal.class).iterator().next();
99 return principal.getName();
100 }
101
102 public final static String getDisplayName(Subject subject) {
103 return getAuthorization(subject).toString();
104 }
105
106 public final static Set<String> roles(Subject subject) {
107 Set<String> roles = new HashSet<String>();
108 roles.add(getUsername(subject));
109 for (Principal group : subject.getPrincipals(ImpliedByPrincipal.class)) {
110 roles.add(group.getName());
111 }
112 return roles;
113 }
114
115 public final static Locale locale(Subject subject) {
116 Set<Locale> locales = subject.getPublicCredentials(Locale.class);
117 if (locales.isEmpty()) {
118 Locale defaultLocale = CmsContextImpl.getCmsContext().getDefaultLocale();
119 return defaultLocale;
120 } else
121 return locales.iterator().next();
122 }
123
124 /** Whether this user is currently authenticated. */
125 public static boolean isAnonymous(Subject subject) {
126 if (subject == null)
127 return true;
128 String username = getUsername(subject);
129 return username == null || username.equalsIgnoreCase(CmsConstants.ROLE_ANONYMOUS);
130 }
131
132 public static CmsSession getCmsSession() {
133 Subject subject = currentSubject();
134 Iterator<CmsSessionId> it = subject.getPrivateCredentials(CmsSessionId.class).iterator();
135 if (!it.hasNext())
136 throw new IllegalStateException("No CMS session id available for " + subject);
137 CmsSessionId cmsSessionId = it.next();
138 if (it.hasNext())
139 throw new IllegalStateException("More than one CMS session id available for " + subject);
140 return CmsContextImpl.getCmsContext().getCmsSessionByUuid(cmsSessionId.getUuid());
141 }
142
143 /*
144 * HELPERS
145 */
146 private static Subject currentSubject() {
147 Subject subject = getAccessControllerSubject();
148 if (subject != null)
149 return subject;
150 throw new IllegalStateException("Cannot find related subject");
151 }
152
153 private static Subject getAccessControllerSubject() {
154 return Subject.getSubject(AccessController.getContext());
155 }
156
157 private static Authorization getAuthorization(Subject subject) {
158 return subject.getPrivateCredentials(Authorization.class).iterator().next();
159 }
160
161 public static boolean logoutCmsSession(Subject subject) {
162 UUID nodeSessionId;
163 if (subject.getPrivateCredentials(CmsSessionId.class).size() == 1)
164 nodeSessionId = subject.getPrivateCredentials(CmsSessionId.class).iterator().next().getUuid();
165 else
166 return false;
167 CmsSessionImpl cmsSession = CmsContextImpl.getCmsContext().getCmsSessionByUuid(nodeSessionId);
168
169 // FIXME logout all views
170 // TODO check why it is sometimes null
171 if (cmsSession != null)
172 cmsSession.close();
173 // if (log.isDebugEnabled())
174 // log.debug("Logged out CMS session " + cmsSession.getUuid());
175 return true;
176 }
177
178 /*
179 * PREPARE EVOLUTION OF JAVA APIs INTRODUCED IN JDK 18 The following static
180 * methods will be added to Subject
181 */
182 public Subject current() {
183 return currentSubject();
184 }
185
186 public static <T> T callAs(Subject subject, Callable<T> action) {
187 try {
188 return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {
189
190 @Override
191 public T run() throws Exception {
192 return action.call();
193 }
194
195 });
196 } catch (PrivilegedActionException e) {
197 throw new CompletionException("Failed to execute action for " + subject, e.getCause());
198 }
199 }
200
201 private CurrentUser() {
202 }
203 }