001/*
002 * Licensed to DuraSpace under one or more contributor license agreements.
003 * See the NOTICE file distributed with this work for additional information
004 * regarding copyright ownership.
005 *
006 * DuraSpace licenses this file to you under the Apache License,
007 * Version 2.0 (the "License"); you may not use this file except in
008 * compliance with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.fcrepo.auth.common;
019
020import org.apache.http.auth.BasicUserPrincipal;
021import org.apache.shiro.subject.PrincipalCollection;
022import org.apache.shiro.subject.Subject;
023import org.modeshape.jcr.security.SecurityContext;
024
025/**
026 * Security context that is simply a thin wrapper around a Shiro Subject.
027 * 
028 * @author peichman
029 */
030public class ShiroSecurityContext implements SecurityContext {
031
032    private Subject user;
033
034    private String userName;
035
036    /**
037     * Create a new security context using the given Shiro subject. That subject will typically be the value returned
038     * by a call to {@code SecurityUtils.getSubject()}.
039     *
040     * @param user subject to create the security context for
041     */
042    public ShiroSecurityContext(final Subject user) {
043        if (user != null) {
044            this.user = user;
045            final PrincipalCollection principals = user.getPrincipals();
046            if (principals != null) {
047                final BasicUserPrincipal userPrincipal = principals.oneByType(BasicUserPrincipal.class);
048                if (userPrincipal != null) {
049                    this.userName = userPrincipal.getName();
050                } else {
051                    this.userName = null;
052                }
053            }
054        }
055    }
056
057    @Override
058    public boolean isAnonymous() {
059        return !user.isAuthenticated();
060    }
061
062    @Override
063    public String getUserName() {
064        return userName;
065    }
066
067    @Override
068    public boolean hasRole(final String roleName) {
069        // Under this custom PEP regime, all users have modeshape read and write
070        // roles.
071        if ("read".equals(roleName)) {
072            return true;
073        } else if ("write".equals(roleName)) {
074            return true;
075        } else {
076            return "admin".equals(roleName);
077        }
078    }
079
080    @Override
081    public void logout() {
082        // this method intentionally does nothing
083    }
084
085}