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.config;
020
021import org.apache.shiro.mgt.DefaultSecurityManager;
022import org.apache.shiro.mgt.RealmSecurityManager;
023import org.apache.shiro.mgt.SecurityManager;
024import org.apache.shiro.realm.Realm;
025import org.apache.shiro.realm.RealmFactory;
026import org.apache.shiro.realm.text.IniRealm;
027import org.apache.shiro.util.CollectionUtils;
028import org.apache.shiro.util.Factory;
029import org.apache.shiro.util.LifecycleUtils;
030import org.apache.shiro.util.Nameable;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033
034import java.util.ArrayList;
035import java.util.Collection;
036import java.util.Collections;
037import java.util.LinkedHashMap;
038import java.util.List;
039import java.util.Map;
040
041/**
042 * A {@link Factory} that creates {@link SecurityManager} instances based on {@link Ini} configuration.
043 *
044 * @since 1.0
045 */
046public class IniSecurityManagerFactory extends IniFactorySupport<SecurityManager> {
047
048    public static final String MAIN_SECTION_NAME = "main";
049
050    public static final String SECURITY_MANAGER_NAME = "securityManager";
051    public static final String INI_REALM_NAME = "iniRealm";
052
053    private static transient final Logger log = LoggerFactory.getLogger(IniSecurityManagerFactory.class);
054
055    private ReflectionBuilder builder;
056
057    /**
058     * Creates a new instance.  See the {@link #getInstance()} JavaDoc for detailed explanation of how an INI
059     * source will be resolved to use to build the instance.
060     */
061    public IniSecurityManagerFactory() {
062    }
063
064    public IniSecurityManagerFactory(Ini config) {
065        setIni(config);
066    }
067
068    public IniSecurityManagerFactory(String iniResourcePath) {
069        this(Ini.fromResourcePath(iniResourcePath));
070    }
071
072    public Map<String, ?> getBeans() {
073        return this.builder != null ? Collections.unmodifiableMap(builder.getObjects()) : null;
074    }
075
076    public void destroy() {
077        if(this.builder != null) {
078            builder.destroy();
079        }
080    }
081
082    private SecurityManager getSecurityManagerBean() {
083        return builder.getBean(SECURITY_MANAGER_NAME, SecurityManager.class);
084    }
085
086    protected SecurityManager createDefaultInstance() {
087        return new DefaultSecurityManager();
088    }
089
090    protected SecurityManager createInstance(Ini ini) {
091        if (CollectionUtils.isEmpty(ini)) {
092            throw new NullPointerException("Ini argument cannot be null or empty.");
093        }
094        SecurityManager securityManager = createSecurityManager(ini);
095        if (securityManager == null) {
096            String msg = SecurityManager.class + " instance cannot be null.";
097            throw new ConfigurationException(msg);
098        }
099        return securityManager;
100    }
101
102    private SecurityManager createSecurityManager(Ini ini) {
103        Ini.Section mainSection = ini.getSection(MAIN_SECTION_NAME);
104        if (CollectionUtils.isEmpty(mainSection)) {
105            //try the default:
106            mainSection = ini.getSection(Ini.DEFAULT_SECTION_NAME);
107        }
108        return createSecurityManager(ini, mainSection);
109    }
110
111    protected boolean isAutoApplyRealms(SecurityManager securityManager) {
112        boolean autoApply = true;
113        if (securityManager instanceof RealmSecurityManager) {
114            //only apply realms if they haven't been explicitly set by the user:
115            RealmSecurityManager realmSecurityManager = (RealmSecurityManager) securityManager;
116            Collection<Realm> realms = realmSecurityManager.getRealms();
117            if (!CollectionUtils.isEmpty(realms)) {
118                log.info("Realms have been explicitly set on the SecurityManager instance - auto-setting of " +
119                        "realms will not occur.");
120                autoApply = false;
121            }
122        }
123        return autoApply;
124    }
125
126    @SuppressWarnings({"unchecked"})
127    private SecurityManager createSecurityManager(Ini ini, Ini.Section mainSection) {
128
129        Map<String, ?> defaults = createDefaults(ini, mainSection);
130        Map<String, ?> objects = buildInstances(mainSection, defaults);
131
132        SecurityManager securityManager = getSecurityManagerBean();
133
134        boolean autoApplyRealms = isAutoApplyRealms(securityManager);
135
136        if (autoApplyRealms) {
137            //realms and realm factory might have been created - pull them out first so we can
138            //initialize the securityManager:
139            Collection<Realm> realms = getRealms(objects);
140            //set them on the SecurityManager
141            if (!CollectionUtils.isEmpty(realms)) {
142                applyRealmsToSecurityManager(realms, securityManager);
143            }
144        }
145
146        return securityManager;
147    }
148
149    protected Map<String, ?> createDefaults(Ini ini, Ini.Section mainSection) {
150        Map<String, Object> defaults = new LinkedHashMap<String, Object>();
151
152        SecurityManager securityManager = createDefaultInstance();
153        defaults.put(SECURITY_MANAGER_NAME, securityManager);
154
155        if (shouldImplicitlyCreateRealm(ini)) {
156            Realm realm = createRealm(ini);
157            if (realm != null) {
158                defaults.put(INI_REALM_NAME, realm);
159            }
160        }
161
162        return defaults;
163    }
164
165    private Map<String, ?> buildInstances(Ini.Section section, Map<String, ?> defaults) {
166        this.builder = new ReflectionBuilder(defaults);
167        return this.builder.buildObjects(section);
168    }
169
170    private void addToRealms(Collection<Realm> realms, RealmFactory factory) {
171        LifecycleUtils.init(factory);
172        Collection<Realm> factoryRealms = factory.getRealms();
173        //SHIRO-238: check factoryRealms (was 'realms'):
174        if (!CollectionUtils.isEmpty(factoryRealms)) {
175            realms.addAll(factoryRealms);
176        }
177    }
178
179    private Collection<Realm> getRealms(Map<String, ?> instances) {
180
181        //realms and realm factory might have been created - pull them out first so we can
182        //initialize the securityManager:
183        List<Realm> realms = new ArrayList<Realm>();
184
185        //iterate over the map entries to pull out the realm factory(s):
186        for (Map.Entry<String, ?> entry : instances.entrySet()) {
187
188            String name = entry.getKey();
189            Object value = entry.getValue();
190
191            if (value instanceof RealmFactory) {
192                addToRealms(realms, (RealmFactory) value);
193            } else if (value instanceof Realm) {
194                Realm realm = (Realm) value;
195                //set the name if null:
196                String existingName = realm.getName();
197                if (existingName == null || existingName.startsWith(realm.getClass().getName())) {
198                    if (realm instanceof Nameable) {
199                        ((Nameable) realm).setName(name);
200                        log.debug("Applied name '{}' to Nameable realm instance {}", name, realm);
201                    } else {
202                        log.info("Realm does not implement the {} interface.  Configured name will not be applied.",
203                                Nameable.class.getName());
204                    }
205                }
206                realms.add(realm);
207            }
208        }
209
210        return realms;
211    }
212
213    private void assertRealmSecurityManager(SecurityManager securityManager) {
214        if (securityManager == null) {
215            throw new NullPointerException("securityManager instance cannot be null");
216        }
217        if (!(securityManager instanceof RealmSecurityManager)) {
218            String msg = "securityManager instance is not a " + RealmSecurityManager.class.getName() +
219                    " instance.  This is required to access or configure realms on the instance.";
220            throw new ConfigurationException(msg);
221        }
222    }
223
224    protected void applyRealmsToSecurityManager(Collection<Realm> realms, SecurityManager securityManager) {
225        assertRealmSecurityManager(securityManager);
226        ((RealmSecurityManager) securityManager).setRealms(realms);
227    }
228
229    /**
230     * Returns {@code true} if the Ini contains account data and a {@code Realm} should be implicitly
231     * {@link #createRealm(Ini) created} to reflect the account data, {@code false} if no realm should be implicitly
232     * created.
233     *
234     * @param ini the Ini instance to inspect for account data resulting in an implicitly created realm.
235     * @return {@code true} if the Ini contains account data and a {@code Realm} should be implicitly
236     *         {@link #createRealm(Ini) created} to reflect the account data, {@code false} if no realm should be
237     *         implicitly created.
238     */
239    protected boolean shouldImplicitlyCreateRealm(Ini ini) {
240        return !CollectionUtils.isEmpty(ini) &&
241                (!CollectionUtils.isEmpty(ini.getSection(IniRealm.ROLES_SECTION_NAME)) ||
242                        !CollectionUtils.isEmpty(ini.getSection(IniRealm.USERS_SECTION_NAME)));
243    }
244
245    /**
246     * Creates a {@code Realm} from the Ini instance containing account data.
247     *
248     * @param ini the Ini instance from which to acquire the account data.
249     * @return a new Realm instance reflecting the account data discovered in the {@code Ini}.
250     */
251    protected Realm createRealm(Ini ini) {
252        //IniRealm realm = new IniRealm(ini); changed to support SHIRO-322
253        IniRealm realm = new IniRealm();
254        realm.setName(INI_REALM_NAME);
255        realm.setIni(ini); //added for SHIRO-322
256        return realm;
257    }
258}