001/*
002 * (C) Copyright 2015-2016 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 *     Kevin Leturc
018 */
019package org.nuxeo.ecm.liveconnect.core;
020
021import java.io.Serializable;
022import java.util.HashMap;
023import java.util.List;
024import java.util.Map;
025
026import org.apache.commons.logging.Log;
027import org.apache.commons.logging.LogFactory;
028import org.nuxeo.ecm.core.api.DocumentModel;
029import org.nuxeo.ecm.platform.oauth2.providers.AbstractOAuth2UserEmailProvider;
030import org.nuxeo.ecm.platform.oauth2.providers.OAuth2ServiceProvider;
031import org.nuxeo.ecm.platform.oauth2.tokens.NuxeoOAuth2Token;
032
033/**
034 * Basic implementation of {@link OAuth2ServiceProvider} for live connect.
035 *
036 * @since 8.1
037 */
038public abstract class AbstractLiveConnectOAuth2ServiceProvider extends AbstractOAuth2UserEmailProvider {
039
040    private static final Log log = LogFactory.getLog(AbstractLiveConnectOAuth2ServiceProvider.class);
041
042    public final String getServiceUser(String username) {
043        Map<String, Serializable> filter = new HashMap<>();
044        filter.put("serviceName", serviceName);
045        filter.put(NuxeoOAuth2Token.KEY_NUXEO_LOGIN, username);
046        List<DocumentModel> entries = getCredentialDataStore().query(filter);
047        if (entries == null || entries.size() == 0) {
048            return null;
049        }
050        if (entries.size() > 1) {
051            log.error(String.format("Found multiple %s accounts for %s", serviceName, username));
052        }
053        return (String) entries.get(0).getProperty(NuxeoOAuth2Token.SCHEMA, NuxeoOAuth2Token.KEY_SERVICE_LOGIN);
054    }
055
056}