001/*
002 * (C) Copyright 2010 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
020package org.nuxeo.ecm.platform.oauth.providers;
021
022import java.io.Serializable;
023import java.security.SecureRandom;
024import java.util.ArrayList;
025import java.util.Collections;
026import java.util.HashMap;
027import java.util.HashSet;
028import java.util.List;
029import java.util.Map;
030import java.util.Random;
031import java.util.Set;
032
033import org.apache.commons.logging.Log;
034import org.apache.commons.logging.LogFactory;
035import org.nuxeo.ecm.core.api.DocumentModel;
036import org.nuxeo.ecm.core.api.DocumentModelList;
037import org.nuxeo.ecm.core.api.PropertyException;
038import org.nuxeo.ecm.directory.DirectoryException;
039import org.nuxeo.ecm.directory.Session;
040import org.nuxeo.ecm.directory.api.DirectoryService;
041import org.nuxeo.runtime.api.Framework;
042import org.nuxeo.runtime.model.DefaultComponent;
043
044/**
045 * Implementation of the {@link OAuthServiceProviderRegistry}. The main storage backend is a SQL Directory. Readonly
046 * providers (contributed directly at OpenSocialService level) are managed in memory.
047 *
048 * @author tiry
049 */
050public class OAuthServiceProviderRegistryImpl extends DefaultComponent implements OAuthServiceProviderRegistry {
051
052    protected static final Log log = LogFactory.getLog(OAuthServiceProviderRegistryImpl.class);
053
054    public static final String DIRECTORY_NAME = "oauthServiceProviders";
055
056    protected static final Random RANDOM = new SecureRandom();
057
058    protected Map<String, NuxeoOAuthServiceProvider> inMemoryProviders = new HashMap<String, NuxeoOAuthServiceProvider>();
059
060    @Override
061    public NuxeoOAuthServiceProvider getProvider(String gadgetUri, String serviceName) {
062        try {
063            NuxeoOAuthServiceProvider provider = getEntry(gadgetUri, serviceName, null);
064            return provider;
065        } catch (DirectoryException e) {
066            log.error("Unable to read provider from Directory backend", e);
067            return null;
068        }
069    }
070
071    protected String getBareGadgetUri(String gadgetUri) {
072        if (gadgetUri == null) {
073            return null;
074        }
075        String pattern = "http(s)?://(localhost|127.0.0.1)";
076        return gadgetUri.replaceFirst(pattern, "");
077    }
078
079    protected String preProcessServiceName(String serviceName) {
080        if (serviceName != null && serviceName.trim().isEmpty()) {
081            return null;
082        }
083        return serviceName;
084    }
085
086    protected DocumentModel getBestEntry(DocumentModelList entries, String gadgetUri, String serviceName)
087            throws PropertyException {
088        if (entries.size() > 1) {
089            log.warn("Found several entries for gadgetUri=" + gadgetUri + " and serviceName=" + serviceName);
090        }
091        if (serviceName == null || serviceName.trim().isEmpty()) {
092            for (DocumentModel entry : entries) {
093                if (entry.getPropertyValue("serviceName") == null
094                        || ((String) entry.getPropertyValue("serviceName")).trim().isEmpty()) {
095                    return entry;
096                }
097            }
098            return null;
099        } else if (gadgetUri == null || gadgetUri.trim().isEmpty()) {
100            for (DocumentModel entry : entries) {
101                if (entry.getPropertyValue("gadgetUrl") == null
102                        || ((String) entry.getPropertyValue("gadgetUrl")).trim().isEmpty()) {
103                    return entry;
104                }
105            }
106            return null;
107        }
108
109        // XXX do better than that !
110        return entries.get(0);
111    }
112
113    protected NuxeoOAuthServiceProvider getEntry(String gadgetUri, String serviceName, Set<String> ftFilter)
114            {
115
116        String id = mkStringIdx(gadgetUri, serviceName);
117        if (inMemoryProviders.containsKey(id)) {
118            return inMemoryProviders.get(id);
119        }
120
121        // normalize "enmpty" service name
122        serviceName = preProcessServiceName(serviceName);
123
124        if (gadgetUri == null && serviceName == null) {
125            log.warn("Can not find provider with null gadgetUri and null serviceName !");
126            return null;
127        }
128
129        DirectoryService ds = Framework.getService(DirectoryService.class);
130        NuxeoOAuthServiceProvider provider = null;
131        try (Session session = ds.open(DIRECTORY_NAME)) {
132            Map<String, Serializable> filter = new HashMap<String, Serializable>();
133            if (gadgetUri != null) {
134                filter.put("gadgetUrl", gadgetUri);
135            }
136            if (serviceName != null) {
137                filter.put("serviceName", serviceName);
138            }
139            DocumentModelList entries = session.query(filter, ftFilter);
140            if (entries == null || entries.size() == 0) {
141                String bareGadgetUrl = getBareGadgetUri(gadgetUri);
142                if (bareGadgetUrl != null && !bareGadgetUrl.equals(gadgetUri)) {
143                    Set<String> urlfilter = new HashSet<String>();
144                    urlfilter.add("gadgetUrl");
145                    return getEntry(bareGadgetUrl, serviceName, urlfilter);
146                }
147                if (serviceName != null) {
148                    if (bareGadgetUrl != null) {
149                        provider = getEntry(bareGadgetUrl, null, ftFilter);
150                        if (provider != null) {
151                            return provider;
152                        }
153                    }
154                    if (gadgetUri != null) {
155                        return getEntry(null, serviceName, ftFilter);
156                    }
157                }
158                return null;
159            }
160            DocumentModel entry = getBestEntry(entries, gadgetUri, serviceName);
161            if (entry == null) {
162                return null;
163            }
164            provider = NuxeoOAuthServiceProvider.createFromDirectoryEntry(entry);
165            return provider;
166        }
167    }
168
169    protected String mkStringIdx(String gadgetUri, String serviceName) {
170        return "k-" + gadgetUri + "-" + serviceName;
171    }
172
173    @Override
174    public NuxeoOAuthServiceProvider addReadOnlyProvider(String gadgetUri, String serviceName, String consumerKey,
175            String consumerSecret, String publicKey) {
176        String id = mkStringIdx(gadgetUri, serviceName);
177        long dummyId = RANDOM.nextLong();
178        NuxeoOAuthServiceProvider sp = new NuxeoOAuthServiceProvider(dummyId, gadgetUri, serviceName, consumerKey,
179                consumerSecret, publicKey);
180        inMemoryProviders.put(id, sp);
181        return sp;
182    }
183
184    @Override
185    public void deleteProvider(String gadgetUri, String serviceName) {
186
187        NuxeoOAuthServiceProvider provider = getProvider(gadgetUri, serviceName);
188        if (provider != null) {
189            deleteProvider(provider.id.toString());
190        }
191
192    }
193
194    @Override
195    public void deleteProvider(String providerId) {
196        try {
197            DirectoryService ds = Framework.getService(DirectoryService.class);
198            try (Session session = ds.open(DIRECTORY_NAME)) {
199                session.deleteEntry(providerId);
200            }
201        } catch (DirectoryException e) {
202            log.error("Unable to delete provider " + providerId, e);
203        }
204    }
205
206    @Override
207    public List<NuxeoOAuthServiceProvider> listProviders() {
208
209        List<NuxeoOAuthServiceProvider> result = new ArrayList<NuxeoOAuthServiceProvider>();
210        for (NuxeoOAuthServiceProvider provider : inMemoryProviders.values()) {
211            result.add(provider);
212        }
213        DirectoryService ds = Framework.getService(DirectoryService.class);
214        Framework.doPrivileged(() -> {
215            try (Session session = ds.open(DIRECTORY_NAME)) {
216                DocumentModelList entries = session.query(Collections.emptyMap());
217                for (DocumentModel entry : entries) {
218                    result.add(NuxeoOAuthServiceProvider.createFromDirectoryEntry(entry));
219                }
220            } catch (DirectoryException e) {
221                log.error("Error while fetching provider directory", e);
222            }
223        });
224        return result;
225    }
226}