001/*
002 * (C) Copyright 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
015package org.nuxeo.ecm.platform.oauth2.providers;
016
017import org.nuxeo.ecm.platform.oauth2.tokens.NuxeoOAuth2Token;
018
019import javax.servlet.http.HttpServletRequest;
020import java.io.IOException;
021import java.io.Serializable;
022import java.util.HashMap;
023import java.util.Map;
024
025/**
026 * {@link org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProvider} that relies on the user's email as key.
027 *
028 * @since 7.3
029 */
030public abstract class AbstractOAuth2UserEmailProvider extends NuxeoOAuth2ServiceProvider {
031
032    @Override
033    protected String getOrCreateServiceUser(HttpServletRequest request, String accessToken) throws IOException {
034        String email = getUserEmail(accessToken);
035        String userId = getServiceUserId(email);
036        if (userId == null) {
037            String nuxeoLogin = request.getUserPrincipal().getName();
038            Map<String, Object> fields = new HashMap<>();
039            fields.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);
040            userId = getServiceUserStore().store(nuxeoLogin, fields);
041        }
042        return userId;
043    }
044
045    @Override
046    protected String getServiceUserId(String email) {
047        Map<String, Serializable> filter = new HashMap<>();
048        filter.put(NuxeoOAuth2Token.KEY_SERVICE_LOGIN, email);
049        return getServiceUserStore().find(filter);
050    }
051
052    protected abstract String getUserEmail(String accessToken) throws IOException;
053}