001/*
002 * (C) Copyright 2006-2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *
017 */
018
019package org.nuxeo.usermapper.extension;
020
021import java.io.Serializable;
022import java.util.Collections;
023import java.util.HashMap;
024import java.util.Map;
025
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.nuxeo.ecm.core.api.CoreSession;
029import org.nuxeo.ecm.core.api.DataModel;
030import org.nuxeo.ecm.core.api.DocumentModel;
031import org.nuxeo.ecm.core.api.DocumentModelList;
032import org.nuxeo.ecm.core.api.NuxeoPrincipal;
033import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
034import org.nuxeo.ecm.core.api.repository.RepositoryManager;
035import org.nuxeo.ecm.platform.usermanager.UserManager;
036import org.nuxeo.ecm.user.center.profile.UserProfileService;
037import org.nuxeo.runtime.api.Framework;
038
039/**
040 * Provide default implementation for interaction with the {@link UserManager}.
041 *
042 * @author tiry
043 * @since 7.4
044 */
045public abstract class AbstractUserMapper implements UserMapper {
046
047    protected static final Log log = LogFactory.getLog(AbstractUserMapper.class);
048
049    protected final UserManager userManager;
050
051    public AbstractUserMapper() {
052        userManager = Framework.getService(UserManager.class);
053    }
054
055    @Override
056    public NuxeoPrincipal getOrCreateAndUpdateNuxeoPrincipal(Object userObject) {
057        return getOrCreateAndUpdateNuxeoPrincipal(userObject, true, true, null);
058    }
059
060    @Override
061    public NuxeoPrincipal getOrCreateAndUpdateNuxeoPrincipal(Object userObject, boolean createIfNeeded, boolean update,
062            Map<String, Serializable> params) {
063
064        DocumentModel userModel = null;
065
066        Map<String, Serializable> searchAttributes = new HashMap<>();
067        Map<String, Serializable> userAttributes = new HashMap<>();
068        final Map<String, Serializable> profileAttributes = new HashMap<>();
069
070        if (params != null) {
071            searchAttributes.putAll(params);
072        }
073
074        resolveAttributes(userObject, searchAttributes, userAttributes, profileAttributes);
075
076        String userId = (String) searchAttributes.get(userManager.getUserIdField());
077
078        if (userId != null) {
079            userModel = userManager.getUserModel(userId);
080        }
081        if (userModel == null) {
082            if (searchAttributes.size() > 0) {
083                DocumentModelList userDocs = userManager.searchUsers(searchAttributes, Collections.<String> emptySet());
084                if (userDocs.size() > 1) {
085                    log.warn("Can not map user with filter " + searchAttributes.toString() + " : too many results");
086                }
087                if (userDocs.size() == 1) {
088                    userModel = userDocs.get(0);
089                }
090            }
091        }
092        if (userModel != null) {
093            if (update) {
094                updatePrincipal(userAttributes, userModel);
095            }
096        } else {
097            if (!createIfNeeded) {
098                return null;
099            }
100            for (String k : searchAttributes.keySet()) {
101                if (!userAttributes.containsKey(k)) {
102                    userAttributes.put(k, searchAttributes.get(k));
103                }
104            }
105            userModel = createPrincipal(userAttributes);
106        }
107
108        if (userModel != null && profileAttributes.size() > 0 && update) {
109            UserProfileService UPS = Framework.getService(UserProfileService.class);
110            if (UPS != null) {
111
112                final String login = (String) userModel.getPropertyValue(userManager.getUserIdField());
113
114                String repoName = Framework.getService(RepositoryManager.class).getDefaultRepositoryName();
115                new UnrestrictedSessionRunner(repoName) {
116                    @Override
117                    public void run() {
118                        DocumentModel profile = UPS.getUserProfileDocument(login, session);
119                        updateProfile(session, profileAttributes, profile);
120                    }
121                }.runUnrestricted();
122            }
123        }
124
125        if (userModel != null) {
126            userId = (String) userModel.getPropertyValue(userManager.getUserIdField());
127            return userManager.getPrincipal(userId);
128        }
129        return null;
130    }
131
132    protected void updatePrincipal(Map<String, Serializable> attributes, DocumentModel userModel) {
133        DataModel dm = userModel.getDataModel(userManager.getUserSchemaName());
134        for (String key : attributes.keySet()) {
135            dm.setValue(key, attributes.get(key));
136        }
137        userManager.updateUser(userModel);
138    }
139
140    protected void updateProfile(CoreSession session, Map<String, Serializable> attributes, DocumentModel userProfile) {
141        for (String key : attributes.keySet()) {
142            userProfile.setPropertyValue(key, attributes.get(key));
143        }
144        session.saveDocument(userProfile);
145    }
146
147    @SuppressWarnings({ "unchecked", "rawtypes" })
148    protected DocumentModel createPrincipal(Map<String, Serializable> attributes) {
149
150        DocumentModel userModel = userManager.getBareUserModel();
151        userModel.getDataModel(userManager.getUserSchemaName()).setMap((Map) attributes);
152        return userManager.createUser(userModel);
153    }
154
155    protected abstract void resolveAttributes(Object userObject, Map<String, Serializable> searchAttributes,
156            Map<String, Serializable> userAttributes, Map<String, Serializable> profileAttributes);
157
158}