2 * Copyright (C) 2007-2012 Argeo GmbH
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.argeo
.cms
.auth
;
18 import java
.security
.AccessController
;
19 import java
.security
.Principal
;
20 import java
.security
.acl
.Group
;
21 import java
.util
.HashSet
;
24 import javax
.security
.auth
.Subject
;
25 import javax
.security
.auth
.x500
.X500Principal
;
27 import org
.argeo
.cms
.CmsException
;
28 import org
.argeo
.cms
.CmsView
;
29 import org
.argeo
.cms
.util
.CmsUtils
;
30 import org
.osgi
.service
.useradmin
.Authorization
;
32 /** Static utilities */
33 public final class CurrentUser
{
35 * @return the authenticated username or null if not authenticated /
38 public static String
getUsername() {
39 return getUsername(currentSubject());
42 public static String
getDisplayName() {
43 return getDisplayName(currentSubject());
46 public static boolean isAnonymous() {
47 return isAnonymous(currentSubject());
50 public static boolean isAnonymous(Subject subject
) {
51 String username
= getUsername(subject
);
52 return username
== null
53 || username
.equalsIgnoreCase(AuthConstants
.ROLE_ANONYMOUS
);
56 private static Subject
currentSubject() {
57 Subject subject
= Subject
.getSubject(AccessController
.getContext());
60 if (subject
== null) {
61 CmsView cmsView
= CmsUtils
.getCmsView();
63 return cmsView
.getSubject();
65 throw new CmsException("Cannot find related subject");
68 public final static String
getUsername(Subject subject
) {
69 // Subject subject = Subject.getSubject(AccessController.getContext());
70 // if (subject == null)
72 if (subject
.getPrincipals(X500Principal
.class).size() != 1)
74 Principal principal
= subject
.getPrincipals(X500Principal
.class)
76 return principal
.getName();
80 public final static String
getDisplayName(Subject subject
) {
81 return getAuthorization(subject
).toString();
84 private static Authorization
getAuthorization(Subject subject
) {
85 return subject
.getPrivateCredentials(Authorization
.class).iterator()
89 public final static Set
<String
> roles() {
90 return roles(currentSubject());
93 public final static Set
<String
> roles(Subject subject
) {
94 Set
<String
> roles
= new HashSet
<String
>();
95 X500Principal userPrincipal
= subject
96 .getPrincipals(X500Principal
.class).iterator().next();
97 roles
.add(userPrincipal
.getName());
98 for (Principal group
: subject
.getPrincipals(Group
.class)) {
99 roles
.add(group
.getName());
104 private CurrentUser() {