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 *
016 *      Nelson Silva
017 */
018
019package org.nuxeo.ecm.liveconnect.google.drive.credential;
020
021import com.google.api.client.auth.oauth2.Credential;
022import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
023import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
024import com.google.api.client.http.HttpTransport;
025import com.google.api.client.json.JsonFactory;
026import com.google.api.client.json.jackson2.JacksonFactory;
027import com.google.api.services.drive.DriveScopes;
028
029import java.io.File;
030import java.io.IOException;
031import java.security.GeneralSecurityException;
032import java.util.Collections;
033
034/**
035 * Credential factory for Service Accounts.
036 *
037 * @since 7.3
038 */
039public class ServiceAccountCredentialFactory implements CredentialFactory {
040
041    private final String accountId;
042
043    private final File p12File;
044
045    public ServiceAccountCredentialFactory(String accountId, File p12File) {
046        this.accountId = accountId;
047        this.p12File = p12File;
048    }
049
050    @Override
051    public Credential build(String user) throws IOException {
052        try {
053            return new GoogleCredential.Builder() //
054                .setTransport(getHttpTransport()) //
055                .setJsonFactory(getJsonFactory()) //
056                .setServiceAccountId(accountId) //
057                .setServiceAccountPrivateKeyFromP12File(p12File) //
058                .setServiceAccountScopes(Collections.singleton(DriveScopes.DRIVE)) //
059                .setServiceAccountUser(user).build();
060        } catch (GeneralSecurityException e) {
061            throw new IOException(e);
062        }
063    }
064
065    protected static JsonFactory getJsonFactory() {
066        return JacksonFactory.getDefaultInstance();
067    }
068
069    protected static HttpTransport getHttpTransport() throws IOException {
070        try {
071            return GoogleNetHttpTransport.newTrustedTransport();
072        } catch (GeneralSecurityException e) {
073            throw new IOException(e);
074        }
075    }
076}