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