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