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 * Contributors: 015 * Nelson Silva 016 */ 017package org.nuxeo.ecm.liveconnect.google.drive; 018 019import com.google.api.client.http.GenericUrl; 020import com.google.api.client.http.HttpRequestFactory; 021import com.google.api.client.http.HttpResponse; 022import com.google.api.client.json.GenericJson; 023import com.google.api.client.json.JsonObjectParser; 024import org.apache.commons.logging.Log; 025import org.apache.commons.logging.LogFactory; 026import org.nuxeo.ecm.core.api.DocumentModel; 027import org.nuxeo.ecm.platform.oauth2.providers.AbstractOAuth2UserEmailProvider; 028import org.nuxeo.ecm.platform.oauth2.tokens.NuxeoOAuth2Token; 029 030import java.io.IOException; 031import java.io.Serializable; 032import java.util.HashMap; 033import java.util.List; 034import java.util.Map; 035 036/** 037 * @since 7.3 038 */ 039public class GoogleOAuth2ServiceProvider extends AbstractOAuth2UserEmailProvider { 040 041 protected static final Log log = LogFactory.getLog(GoogleOAuth2ServiceProvider.class); 042 043 private static final String TOKEN_INFO_URL = "https://www.googleapis.com/oauth2/v1/tokeninfo"; 044 045 private static final HttpRequestFactory requestFactory = 046 HTTP_TRANSPORT.createRequestFactory(request -> request.setParser(new JsonObjectParser(JSON_FACTORY))); 047 048 protected String getUserEmail(String accessToken) throws IOException { 049 GenericUrl url = new GenericUrl(TOKEN_INFO_URL); 050 url.set("access_token", accessToken); 051 052 HttpResponse response = requestFactory.buildGetRequest(url).execute(); 053 GenericJson json = response.parseAs(GenericJson.class); 054 return (String) json.get("email"); 055 } 056 057 public String getServiceUser(String username) { 058 Map<String, Serializable> filter = new HashMap<>(); 059 filter.put("serviceName", serviceName); 060 filter.put(NuxeoOAuth2Token.KEY_NUXEO_LOGIN, username); 061 List<DocumentModel> entries = getCredentialDataStore().query(filter); 062 if (entries == null || entries.size() == 0) { 063 return null; 064 } 065 if (entries.size() > 1) { 066 log.error("Found multiple " + serviceName + " accounts for " + username); 067 } 068 return (String) entries.get(0).getProperty(NuxeoOAuth2Token.SCHEMA, NuxeoOAuth2Token.KEY_SERVICE_LOGIN); 069 } 070}