View Javadoc
1   /*
2    * Copyright (C) 2007-2012 Argeo GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.argeo.cms.auth;
17  
18  import java.security.AccessController;
19  import java.security.Principal;
20  import java.security.PrivilegedAction;
21  import java.security.PrivilegedActionException;
22  import java.security.PrivilegedExceptionAction;
23  import java.util.HashSet;
24  import java.util.Locale;
25  import java.util.Set;
26  import java.util.UUID;
27  
28  import javax.security.auth.Subject;
29  import javax.security.auth.x500.X500Principal;
30  
31  import org.argeo.api.NodeConstants;
32  import org.argeo.cms.CmsException;
33  import org.argeo.cms.internal.auth.CmsSessionImpl;
34  import org.argeo.cms.internal.auth.ImpliedByPrincipal;
35  import org.argeo.cms.internal.kernel.Activator;
36  import org.osgi.service.useradmin.Authorization;
37  
38  /**
39   * Programmatic access to the currently authenticated user, within a CMS
40   * context.
41   */
42  public final class CurrentUser {
43  	// private final static Log log = LogFactory.getLog(CurrentUser.class);
44  	// private final static BundleContext bc =
45  	// FrameworkUtil.getBundle(CurrentUser.class).getBundleContext();
46  	/*
47  	 * CURRENT USER API
48  	 */
49  
50  	/**
51  	 * Technical username of the currently authenticated user.
52  	 * 
53  	 * @return the authenticated username or null if not authenticated / anonymous
54  	 */
55  	public static String getUsername() {
56  		return getUsername(currentSubject());
57  	}
58  
59  	/**
60  	 * Human readable name of the currently authenticated user (typically first name
61  	 * and last name).
62  	 */
63  	public static String getDisplayName() {
64  		return getDisplayName(currentSubject());
65  	}
66  
67  	/** Whether a user is currently authenticated. */
68  	public static boolean isAnonymous() {
69  		return isAnonymous(currentSubject());
70  	}
71  
72  	/** Locale of the current user */
73  	public final static Locale locale() {
74  		return locale(currentSubject());
75  	}
76  
77  	/** Roles of the currently logged-in user */
78  	public final static Set<String> roles() {
79  		return roles(currentSubject());
80  	}
81  
82  	/** Returns true if the current user is in the specified role */
83  	public static boolean isInRole(String role) {
84  		Set<String> roles = roles();
85  		return roles.contains(role);
86  	}
87  
88  	/** Executes as the current user */
89  	public final static <T> T doAs(PrivilegedAction<T> action) {
90  		return Subject.doAs(currentSubject(), action);
91  	}
92  
93  	/** Executes as the current user */
94  	public final static <T> T tryAs(PrivilegedExceptionAction<T> action) throws PrivilegedActionException {
95  		return Subject.doAs(currentSubject(), action);
96  	}
97  
98  	/*
99  	 * WRAPPERS
100 	 */
101 
102 	public final static String getUsername(Subject subject) {
103 		if (subject == null)
104 			throw new CmsException("Subject cannot be null");
105 		if (subject.getPrincipals(X500Principal.class).size() != 1)
106 			return NodeConstants.ROLE_ANONYMOUS;
107 		Principal principal = subject.getPrincipals(X500Principal.class).iterator().next();
108 		return principal.getName();
109 	}
110 
111 	public final static String getDisplayName(Subject subject) {
112 		return getAuthorization(subject).toString();
113 	}
114 
115 	public final static Set<String> roles(Subject subject) {
116 		Set<String> roles = new HashSet<String>();
117 		roles.add(getUsername(subject));
118 		for (Principal group : subject.getPrincipals(ImpliedByPrincipal.class)) {
119 			roles.add(group.getName());
120 		}
121 		return roles;
122 	}
123 
124 	public final static Locale locale(Subject subject) {
125 		Set<Locale> locales = subject.getPublicCredentials(Locale.class);
126 		if (locales.isEmpty()) {
127 			Locale defaultLocale = Activator.getNodeState().getDefaultLocale();
128 			return defaultLocale;
129 		} else
130 			return locales.iterator().next();
131 	}
132 
133 	/** Whether this user is currently authenticated. */
134 	public static boolean isAnonymous(Subject subject) {
135 		if (subject == null)
136 			return true;
137 		String username = getUsername(subject);
138 		return username == null || username.equalsIgnoreCase(NodeConstants.ROLE_ANONYMOUS);
139 	}
140 
141 	public CmsSession getCmsSession() {
142 		Subject subject = currentSubject();
143 		CmsSessionId cmsSessionId = subject.getPrivateCredentials(CmsSessionId.class).iterator().next();
144 		return CmsSessionImpl.getByUuid(cmsSessionId.getUuid());
145 	}
146 
147 	/*
148 	 * HELPERS
149 	 */
150 	private static Subject currentSubject() {
151 		// CmsAuthenticated cmsView = getNodeAuthenticated();
152 		// if (cmsView != null)
153 		// return cmsView.getSubject();
154 		Subject subject = getAccessControllerSubject();
155 		if (subject != null)
156 			return subject;
157 		throw new CmsException("Cannot find related subject");
158 	}
159 
160 	private static Subject getAccessControllerSubject() {
161 		return Subject.getSubject(AccessController.getContext());
162 	}
163 
164 	// public static boolean isAuthenticated() {
165 	// return getAccessControllerSubject() != null;
166 	// }
167 
168 	/**
169 	 * The node authenticated component (typically a CMS view) related to this
170 	 * display, or null if none is available from this call. <b>Not API: Only for
171 	 * low-level access.</b>
172 	 */
173 	// private static CmsAuthenticated getNodeAuthenticated() {
174 	// return UiContext.getData(CmsAuthenticated.KEY);
175 	// }
176 
177 	private static Authorization getAuthorization(Subject subject) {
178 		return subject.getPrivateCredentials(Authorization.class).iterator().next();
179 	}
180 
181 	public static boolean logoutCmsSession(Subject subject) {
182 		UUID nodeSessionId;
183 		if (subject.getPrivateCredentials(CmsSessionId.class).size() == 1)
184 			nodeSessionId = subject.getPrivateCredentials(CmsSessionId.class).iterator().next().getUuid();
185 		else
186 			return false;
187 		CmsSessionImpl cmsSession = CmsSessionImpl.getByUuid(nodeSessionId.toString());
188 		cmsSession.close();
189 		// if (log.isDebugEnabled())
190 		// log.debug("Logged out CMS session " + cmsSession.getUuid());
191 		return true;
192 	}
193 
194 	private CurrentUser() {
195 	}
196 }