]> git.argeo.org Git - lgpl/argeo-commons.git/blob - security/plugins/org.argeo.security.ui/src/main/java/org/argeo/security/ui/internal/CurrentUser.java
Merge fix of regression introduced by https://www.argeo.org/bugzilla/show_bug.cgi...
[lgpl/argeo-commons.git] / security / plugins / org.argeo.security.ui / src / main / java / org / argeo / security / ui / internal / CurrentUser.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.security.ui.internal;
17
18 import java.security.AccessController;
19 import java.security.Principal;
20 import java.util.Collections;
21 import java.util.HashSet;
22 import java.util.Set;
23
24 import javax.security.auth.Subject;
25
26 import org.argeo.ArgeoException;
27 import org.springframework.security.Authentication;
28 import org.springframework.security.GrantedAuthority;
29
30 /**
31 * Retrieves information about the current user. Not an API, can change without
32 * notice.
33 */
34 public class CurrentUser {
35 public final static String getUsername() {
36 Subject subject = getSubject();
37 if (subject == null)
38 return null;
39 Principal principal = subject.getPrincipals().iterator().next();
40 return principal.getName();
41
42 }
43
44 public final static Set<String> roles() {
45 Set<String> roles = Collections.synchronizedSet(new HashSet<String>());
46 Authentication authentication = getAuthentication();
47 for (GrantedAuthority ga : authentication.getAuthorities()) {
48 roles.add(ga.getAuthority());
49 }
50 return Collections.unmodifiableSet(roles);
51 }
52
53 public final static Authentication getAuthentication() {
54 Set<Authentication> authens = getSubject().getPrincipals(
55 Authentication.class);
56 if (authens != null && !authens.isEmpty()) {
57 Principal principal = authens.iterator().next();
58 Authentication authentication = (Authentication) principal;
59 return authentication;
60 }
61 throw new ArgeoException("No authentication found");
62 }
63
64 public final static Subject getSubject() {
65 Subject subject = Subject.getSubject(AccessController.getContext());
66 if (subject == null)
67 throw new ArgeoException("Not authenticated.");
68 return subject;
69 }
70 }