001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * 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,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.shiro.realm;
020
021import org.apache.shiro.authc.AuthenticationException;
022import org.apache.shiro.authc.AuthenticationInfo;
023import org.apache.shiro.authc.AuthenticationToken;
024import org.apache.shiro.authc.ExpiredCredentialsException;
025import org.apache.shiro.authc.LockedAccountException;
026import org.apache.shiro.authc.SimpleAccount;
027import org.apache.shiro.authc.UsernamePasswordToken;
028import org.apache.shiro.authz.AuthorizationInfo;
029import org.apache.shiro.authz.SimpleRole;
030import org.apache.shiro.subject.PrincipalCollection;
031import org.apache.shiro.util.CollectionUtils;
032
033import java.util.HashSet;
034import java.util.LinkedHashMap;
035import java.util.Map;
036import java.util.Set;
037import java.util.concurrent.locks.ReadWriteLock;
038import java.util.concurrent.locks.ReentrantReadWriteLock;
039
040/**
041 * A simple implementation of the {@link Realm Realm} interface that
042 * uses a set of configured user accounts and roles to support authentication and authorization.  Each account entry
043 * specifies the username, password, and roles for a user.  Roles can also be mapped
044 * to permissions and associated with users.
045 * <p/>
046 * User accounts and roles are stored in two {@code Map}s in memory, so it is expected that the total number of either
047 * is not sufficiently large.
048 *
049 * @since 0.1
050 */
051public class SimpleAccountRealm extends AuthorizingRealm {
052
053    //TODO - complete JavaDoc
054    protected final Map<String, SimpleAccount> users; //username-to-SimpleAccount
055    protected final Map<String, SimpleRole> roles; //roleName-to-SimpleRole
056    protected final ReadWriteLock USERS_LOCK;
057    protected final ReadWriteLock ROLES_LOCK;
058
059    public SimpleAccountRealm() {
060        this.users = new LinkedHashMap<String, SimpleAccount>();
061        this.roles = new LinkedHashMap<String, SimpleRole>();
062        USERS_LOCK = new ReentrantReadWriteLock();
063        ROLES_LOCK = new ReentrantReadWriteLock();
064        //SimpleAccountRealms are memory-only realms - no need for an additional cache mechanism since we're
065        //already as memory-efficient as we can be:
066        setCachingEnabled(false);
067    }
068
069    public SimpleAccountRealm(String name) {
070        this();
071        setName(name);
072    }
073
074    protected SimpleAccount getUser(String username) {
075        USERS_LOCK.readLock().lock();
076        try {
077            return this.users.get(username);
078        } finally {
079            USERS_LOCK.readLock().unlock();
080        }
081    }
082
083    public boolean accountExists(String username) {
084        return getUser(username) != null;
085    }
086
087    public void addAccount(String username, String password) {
088        addAccount(username, password, (String[]) null);
089    }
090
091    public void addAccount(String username, String password, String... roles) {
092        Set<String> roleNames = CollectionUtils.asSet(roles);
093        SimpleAccount account = new SimpleAccount(username, password, getName(), roleNames, null);
094        add(account);
095    }
096
097    protected String getUsername(SimpleAccount account) {
098        return getUsername(account.getPrincipals());
099    }
100
101    protected String getUsername(PrincipalCollection principals) {
102        return getAvailablePrincipal(principals).toString();
103    }
104
105    protected void add(SimpleAccount account) {
106        String username = getUsername(account);
107        USERS_LOCK.writeLock().lock();
108        try {
109            this.users.put(username, account);
110        } finally {
111            USERS_LOCK.writeLock().unlock();
112        }
113    }
114
115    protected SimpleRole getRole(String rolename) {
116        ROLES_LOCK.readLock().lock();
117        try {
118            return roles.get(rolename);
119        } finally {
120            ROLES_LOCK.readLock().unlock();
121        }
122    }
123
124    public boolean roleExists(String name) {
125        return getRole(name) != null;
126    }
127
128    public void addRole(String name) {
129        add(new SimpleRole(name));
130    }
131
132    protected void add(SimpleRole role) {
133        ROLES_LOCK.writeLock().lock();
134        try {
135            roles.put(role.getName(), role);
136        } finally {
137            ROLES_LOCK.writeLock().unlock();
138        }
139    }
140
141    protected static Set<String> toSet(String delimited, String delimiter) {
142        if (delimited == null || delimited.trim().equals("")) {
143            return null;
144        }
145
146        Set<String> values = new HashSet<String>();
147        String[] rolenamesArray = delimited.split(delimiter);
148        for (String s : rolenamesArray) {
149            String trimmed = s.trim();
150            if (trimmed.length() > 0) {
151                values.add(trimmed);
152            }
153        }
154
155        return values;
156    }
157
158    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
159        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
160        SimpleAccount account = getUser(upToken.getUsername());
161
162        if (account != null) {
163
164            if (account.isLocked()) {
165                throw new LockedAccountException("Account [" + account + "] is locked.");
166            }
167            if (account.isCredentialsExpired()) {
168                String msg = "The credentials for account [" + account + "] are expired";
169                throw new ExpiredCredentialsException(msg);
170            }
171
172        }
173
174        return account;
175    }
176
177    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
178        String username = getUsername(principals);
179        USERS_LOCK.readLock().lock();
180        try {
181            return this.users.get(username);
182        } finally {
183            USERS_LOCK.readLock().unlock();
184        }
185    }
186}