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    protected final UserManager userManager;
052
053    public AbstractUserMapper() {
054        userManager = Framework.getService(UserManager.class);
055    }
056
057    @Override
058    public NuxeoPrincipal getOrCreateAndUpdateNuxeoPrincipal(Object userObject) {
059        return getOrCreateAndUpdateNuxeoPrincipal(userObject, true, true, null);
060    }
061
062    @Override
063    public NuxeoPrincipal getOrCreateAndUpdateNuxeoPrincipal(Object userObject, boolean createIfNeeded, boolean update,
064            Map<String, Serializable> params) {
065
066        DocumentModel userModel = null;
067
068        Map<String, Serializable> searchAttributes = new HashMap<>();
069        Map<String, Serializable> userAttributes = new HashMap<>();
070        final Map<String, Serializable> profileAttributes = new HashMap<>();
071
072        if (params != null) {
073            searchAttributes.putAll(params);
074        }
075
076        resolveAttributes(userObject, searchAttributes, userAttributes, profileAttributes);
077
078        String userId = (String) searchAttributes.get(userManager.getUserIdField());
079
080        if (userId != null) {
081            userModel = userManager.getUserModel(userId);
082        }
083        if (userModel == null) {
084            if (searchAttributes.size() > 0) {
085                DocumentModelList userDocs = userManager.searchUsers(searchAttributes, Collections.<String> emptySet());
086                if (userDocs.size() > 1) {
087                    log.warn("Can not map user with filter " + searchAttributes.toString() + " : too many results");
088                }
089                if (userDocs.size() == 1) {
090                    userModel = userDocs.get(0);
091                }
092            }
093        }
094        if (userModel != null) {
095            if (update) {
096                updatePrincipal(userAttributes, userModel);
097            }
098        } else {
099            if (!createIfNeeded) {
100                return null;
101            }
102            for (String k : searchAttributes.keySet()) {
103                if (!userAttributes.containsKey(k)) {
104                    userAttributes.put(k, searchAttributes.get(k));
105                }
106            }
107            userModel = createPrincipal(userAttributes);
108        }
109
110        if (userModel != null && profileAttributes.size() > 0 && update) {
111            UserProfileService UPS = Framework.getService(UserProfileService.class);
112            if (UPS != null) {
113
114                final String login = (String) userModel.getPropertyValue(userManager.getUserIdField());
115
116                String repoName = Framework.getService(RepositoryManager.class).getDefaultRepositoryName();
117                new UnrestrictedSessionRunner(repoName) {
118                    @Override
119                    public void run() {
120                        DocumentModel profile = UPS.getUserProfileDocument(login, session);
121                        updateProfile(session, profileAttributes, profile);
122                    }
123                }.runUnrestricted();
124            }
125        }
126
127        if (userModel != null) {
128            userId = (String) userModel.getPropertyValue(userManager.getUserIdField());
129            return userManager.getPrincipal(userId);
130        }
131        return null;
132    }
133
134    protected void updatePrincipal(Map<String, Serializable> attributes, DocumentModel userModel) {
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
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}