2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.authentication.spring;
26 import org.collectionspace.authentication.AuthN;
27 import org.collectionspace.authentication.CSpaceTenant;
28 import org.collectionspace.authentication.CSpaceUser;
29 import org.collectionspace.authentication.spi.AuthNContext;
30 import org.springframework.security.core.Authentication;
31 import org.springframework.security.core.context.SecurityContextHolder;
34 * Utilities for accessing the Spring Security authentication context.
36 public class SpringAuthNContext implements AuthNContext {
39 * Returns the username of the authenticated user.
41 * @return the username
44 public String getUserId() {
45 Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
47 if (authToken == null) {
48 return AuthN.ANONYMOUS_USER;
51 return authToken.getName();
55 * Returns the authenticated CSpaceUser user.
60 public CSpaceUser getUser() {
61 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
62 Object principal = authentication.getPrincipal();
64 CSpaceUser user = null;
65 if (principal instanceof CSpaceUser ) {
66 user = (CSpaceUser) principal;
73 * Returns the id of the primary tenant associated with the authenticated user.
75 * @return the tenant id
78 public String getCurrentTenantId() {
81 CSpaceUser cspaceUser = getUser();
82 if (cspaceUser != null) {
83 result = getCurrentTenant().getId();
85 String username = getUserId();
86 if (username.equals(AuthN.ANONYMOUS_USER)) {
87 result = AuthN.ANONYMOUS_TENANT_ID;
88 } else if (username.equals(AuthN.SPRING_ADMIN_USER)) {
89 result = AuthN.ADMIN_TENANT_ID;
97 * Returns the name of the primary tenant associated with the authenticated user.
99 * @return the tenant name
102 public String getCurrentTenantName() {
103 if (getUserId().equals(AuthN.ANONYMOUS_USER)) {
104 return AuthN.ANONYMOUS_TENANT_NAME;
107 return getCurrentTenant().getName();
111 * Returns the primary tenant associated with the authenticated user.
116 public CSpaceTenant getCurrentTenant() {
117 return getUser().getPrimaryTenant();