001/* 002 * (C) Copyright 2014-2017 Nuxeo (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 * Arnaud Kervern 018 */ 019package org.nuxeo.ecm.platform.oauth2.clients; 020 021import java.io.Serializable; 022import java.util.Collections; 023import java.util.Map; 024 025import org.nuxeo.ecm.core.api.DocumentModel; 026import org.nuxeo.ecm.core.api.DocumentModelList; 027import org.nuxeo.ecm.core.api.NuxeoException; 028import org.nuxeo.ecm.directory.Session; 029import org.nuxeo.ecm.directory.api.DirectoryService; 030import org.nuxeo.runtime.api.Framework; 031import org.nuxeo.runtime.model.DefaultComponent; 032 033/** 034 * OAuth2 Client service 035 * 036 * @since 9.2 037 */ 038public class OAuth2ClientServiceImpl extends DefaultComponent implements OAuth2ClientService { 039 040 @Override 041 public boolean hasClient(String clientId) { 042 OAuth2Client client = getClient(clientId); 043 return client != null && client.isEnabled(); 044 } 045 046 @Override 047 public boolean isValidClient(String clientId, String clientSecret) { 048 OAuth2Client client = getClient(clientId); 049 return client != null && client.isValidWith(clientId, clientSecret); 050 } 051 052 @Override 053 public OAuth2Client getClient(String clientId) { 054 DocumentModel doc = getClientModel(clientId); 055 if (doc == null) { 056 return null; 057 } 058 return OAuth2Client.fromDocumentModel(doc); 059 } 060 061 protected DocumentModel getClientModel(String clientId) { 062 DirectoryService service = Framework.getService(DirectoryService.class); 063 return Framework.doPrivileged(() -> { 064 try (Session session = service.open(OAUTH2CLIENT_DIRECTORY_NAME)) { 065 Map<String, Serializable> filter = Collections.singletonMap("clientId", clientId); 066 DocumentModelList docs = session.query(filter); 067 if (docs.size() == 1) { 068 return docs.get(0); 069 } else if (docs.size() > 1) { 070 throw new NuxeoException( 071 String.format("More than one client registered for the '%s' id", clientId)); 072 } 073 } 074 return null; 075 }); 076 } 077}