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 CmsView cmsView
= CmsUtils
.getCmsView();
59 return cmsView
.getSubject();
60 Subject subject
= Subject
.getSubject(AccessController
.getContext());
63 throw new CmsException("Cannot find related subject");
66 public final static String
getUsername(Subject subject
) {
67 // Subject subject = Subject.getSubject(AccessController.getContext());
68 // if (subject == null)
70 if (subject
.getPrincipals(X500Principal
.class).size() != 1)
72 Principal principal
= subject
.getPrincipals(X500Principal
.class)
74 return principal
.getName();
78 public final static String
getDisplayName(Subject subject
) {
79 return getAuthorization(subject
).toString();
82 private static Authorization
getAuthorization(Subject subject
) {
83 return subject
.getPrivateCredentials(Authorization
.class).iterator()
87 public final static Set
<String
> roles() {
88 return roles(currentSubject());
91 public final static Set
<String
> roles(Subject subject
) {
92 Set
<String
> roles
= new HashSet
<String
>();
93 X500Principal userPrincipal
= subject
94 .getPrincipals(X500Principal
.class).iterator().next();
95 roles
.add(userPrincipal
.getName());
96 for (Principal group
: subject
.getPrincipals(Group
.class)) {
97 roles
.add(group
.getName());
102 private CurrentUser() {