]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/util/CurrentUserUtils.java
0ebac9dcc216536de5f1d1b830895193c89250c5
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / util / CurrentUserUtils.java
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.util;
17
18 import java.security.AccessController;
19 import java.security.Principal;
20 import java.security.acl.Group;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.Set;
24
25 import javax.security.auth.Subject;
26 import javax.security.auth.x500.X500Principal;
27
28 import org.argeo.ArgeoException;
29
30 /**
31 * Retrieves information about the current user. Not an API, can change without
32 * notice.
33 */
34 class CurrentUserUtils {
35 public final static String getUsername() {
36 Subject subject = getSubject();
37 if (subject == null)
38 return null;
39 Principal principal = subject.getPrincipals(X500Principal.class)
40 .iterator().next();
41 return principal.getName();
42
43 }
44
45 public final static Set<String> roles() {
46 Set<String> roles = Collections.synchronizedSet(new HashSet<String>());
47 // roles.add("ROLE_USER");
48 Subject subject = getSubject();
49 X500Principal userPrincipal = subject
50 .getPrincipals(X500Principal.class).iterator().next();
51 roles.add(userPrincipal.getName());
52 for (Principal group : subject.getPrincipals(Group.class)) {
53 roles.add(group.getName());
54 }
55 return roles;
56 }
57
58 public final static Subject getSubject() {
59 Subject subject = Subject.getSubject(AccessController.getContext());
60 if (subject == null) {
61 subject = CmsUtils.getCmsView().getSubject();
62 if (subject == null)
63 throw new ArgeoException("Not authenticated.");
64 }
65 return subject;
66 }
67 }