001/*
002 * (C) Copyright 2006-2015 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.usermapper.extension;
022
023import java.io.Serializable;
024import java.util.Collections;
025import java.util.HashMap;
026import java.util.Map;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.core.api.CoreSession;
031import org.nuxeo.ecm.core.api.DataModel;
032import org.nuxeo.ecm.core.api.DocumentModel;
033import org.nuxeo.ecm.core.api.DocumentModelList;
034import org.nuxeo.ecm.core.api.NuxeoPrincipal;
035import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
036import org.nuxeo.ecm.core.api.repository.RepositoryManager;
037import org.nuxeo.ecm.platform.usermanager.UserManager;
038import org.nuxeo.ecm.user.center.profile.UserProfileService;
039import org.nuxeo.runtime.api.Framework;
040
041/**
042 * Provide default implementation for interaction with the {@link UserManager}.
043 *
044 * @author tiry
045 * @since 7.4
046 */
047public abstract class AbstractUserMapper implements UserMapper {
048
049    protected static final Log log = LogFactory.getLog(AbstractUserMapper.class);
050
051    public AbstractUserMapper() {
052    }
053
054    @Override
055    public NuxeoPrincipal getOrCreateAndUpdateNuxeoPrincipal(Object userObject) {
056        return getOrCreateAndUpdateNuxeoPrincipal(userObject, true, true, null);
057    }
058
059    @Override
060    public NuxeoPrincipal getOrCreateAndUpdateNuxeoPrincipal(Object userObject, boolean createIfNeeded, boolean update,
061            Map<String, Serializable> params) {
062
063        DocumentModel userModel = null;
064
065        Map<String, Serializable> searchAttributes = new HashMap<>();
066        Map<String, Serializable> userAttributes = new HashMap<>();
067        final Map<String, Serializable> profileAttributes = new HashMap<>();
068
069        if (params != null) {
070            searchAttributes.putAll(params);
071        }
072
073        resolveAttributes(userObject, searchAttributes, userAttributes, profileAttributes);
074
075        UserManager userManager = getUserManager();
076
077        String userId = (String) searchAttributes.get(userManager.getUserIdField());
078
079        if (userId != null) {
080            userModel = userManager.getUserModel(userId);
081        }
082        if (userModel == null) {
083            if (searchAttributes.size() > 0) {
084                DocumentModelList userDocs = userManager.searchUsers(searchAttributes, Collections.<String> emptySet());
085                if (userDocs.size() > 1) {
086                    log.warn("Can not map user with filter " + searchAttributes.toString() + " : too many results");
087                }
088                if (userDocs.size() == 1) {
089                    userModel = userDocs.get(0);
090                }
091            }
092        }
093        if (userModel != null) {
094            if (update) {
095                updatePrincipal(userAttributes, userModel);
096            }
097        } else {
098            if (!createIfNeeded) {
099                return null;
100            }
101            for (String k : searchAttributes.keySet()) {
102                if (!userAttributes.containsKey(k)) {
103                    userAttributes.put(k, searchAttributes.get(k));
104                }
105            }
106            userModel = createPrincipal(userAttributes);
107        }
108
109        if (userModel != null && profileAttributes.size() > 0 && update) {
110            UserProfileService UPS = Framework.getService(UserProfileService.class);
111            if (UPS != null) {
112
113                final String login = (String) userModel.getPropertyValue(userManager.getUserIdField());
114
115                String repoName = Framework.getService(RepositoryManager.class).getDefaultRepositoryName();
116                new UnrestrictedSessionRunner(repoName) {
117                    @Override
118                    public void run() {
119                        DocumentModel profile = UPS.getUserProfileDocument(login, session);
120                        updateProfile(session, profileAttributes, profile);
121                    }
122                }.runUnrestricted();
123            }
124        }
125
126        if (userModel != null) {
127            userId = (String) userModel.getPropertyValue(userManager.getUserIdField());
128            return userManager.getPrincipal(userId);
129        }
130        return null;
131    }
132
133    protected void updatePrincipal(Map<String, Serializable> attributes, DocumentModel userModel) {
134        UserManager userManager = getUserManager();
135        DataModel dm = userModel.getDataModel(userManager.getUserSchemaName());
136        for (String key : attributes.keySet()) {
137            dm.setValue(key, attributes.get(key));
138        }
139        userManager.updateUser(userModel);
140    }
141
142    protected void updateProfile(CoreSession session, Map<String, Serializable> attributes, DocumentModel userProfile) {
143        for (String key : attributes.keySet()) {
144            userProfile.setPropertyValue(key, attributes.get(key));
145        }
146        session.saveDocument(userProfile);
147    }
148
149    @SuppressWarnings({ "unchecked", "rawtypes" })
150    protected DocumentModel createPrincipal(Map<String, Serializable> attributes) {
151        UserManager userManager = getUserManager();
152        DocumentModel userModel = userManager.getBareUserModel();
153        userModel.getDataModel(userManager.getUserSchemaName()).setMap((Map) attributes);
154        return userManager.createUser(userModel);
155    }
156
157    protected abstract void resolveAttributes(Object userObject, Map<String, Serializable> searchAttributes,
158            Map<String, Serializable> userAttributes, Map<String, Serializable> profileAttributes);
159
160    public UserManager getUserManager() {
161        return Framework.getService(UserManager.class);
162    }
163}