001/*
002 * (C) Copyright 2015-2018 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 */
020
021package org.nuxeo.ecm.platform.auth.saml.user;
022
023import java.util.Map;
024
025import org.nuxeo.ecm.core.api.NuxeoPrincipal;
026import org.nuxeo.ecm.platform.auth.saml.SAMLCredential;
027import org.nuxeo.runtime.api.Framework;
028import org.nuxeo.usermapper.service.UserMapperService;
029
030/**
031 * UserResolver implementation that uses the {@link UserMapperService}
032 *
033 * @author tiry
034 * @since 7.4
035 */
036public class UserMapperBasedResolver implements UserResolver {
037
038    protected static final String USER_RESOLVER_MAPPING = "userResolverMapping";
039
040    protected static final String USER_RESOLVER_CREATE_IF_NEEDED = "userResolverCreateIfNeeded";
041
042    protected static final String USER_RESOLVER_UPDATE = "userResolverUpdate";
043
044    protected static final String DEFAULT_USER_MAPPER_CONFIG = "saml";
045
046    protected String mapperName = DEFAULT_USER_MAPPER_CONFIG;
047
048    protected boolean createIfNeeded = true;
049
050    protected boolean update = true;
051
052    @Override
053    public void init(Map<String, String> parameters) {
054        if (parameters.containsKey(USER_RESOLVER_MAPPING)) {
055            mapperName = parameters.get(USER_RESOLVER_MAPPING);
056        }
057        if (parameters.containsKey(USER_RESOLVER_CREATE_IF_NEEDED)) {
058            createIfNeeded = Boolean.parseBoolean(parameters.get(USER_RESOLVER_CREATE_IF_NEEDED));
059        }
060        if (parameters.containsKey(USER_RESOLVER_UPDATE)) {
061            update = Boolean.parseBoolean(parameters.get(USER_RESOLVER_UPDATE));
062        }
063    }
064
065    @Override
066    public String findOrCreateNuxeoUser(SAMLCredential userInfo) {
067        NuxeoPrincipal principal = Framework.getService(UserMapperService.class).getOrCreateAndUpdateNuxeoPrincipal(
068                mapperName, userInfo, createIfNeeded, update, null);
069
070        if (principal != null) {
071            return principal.getName();
072        }
073        return null;
074    }
075
076}