域内的Google Drive API服务帐户

时间:2017-01-09 21:01:32

标签: node.js google-api google-drive-api google-oauth google-api-nodejs-client

我必须使用Node.js服务器从Drive上的文件夹下载/上传/删除文件。该文件夹位于公司的G Suite中,公司中只有少数人可以访问。

我必须使用服务帐户来执行此操作,问题是:是否可能?我怎么能这样做?

我已阅读https://developers.google.com/drive/v2/web/delegationhttps://developers.google.com/identity/protocols/OAuth2ServiceAccount 但我不知道是否可以授予服务帐户访问公司域内文件夹的权限,因为服务帐户是@ developer.gserviceaccount.com,公司的域名是其他的,所以当我尝试将该服务帐户添加到该文件夹​​时,我发现错误。

如果你可以指导我,我会非常感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将oAuth令牌与权限范围一起使用:

const path = require('path');

module.exports = (app) => {
    const factory = {};
    factory.connect = (done) => {
        const fs = require('fs');
        const google = require('googleapis');
        const googleAuth = require('google-auth-library');

        const SCOPES = [
            'https://www.googleapis.com/auth/drive.metadata.readonly'
        ];
        const TOKEN_DIR = path.resolve(app.root, 'server','config');
        const TOKEN_PATH = path.resolve(TOKEN_DIR,'token.json');

        const creds = require(path.resolve(app.root, 'server', 'config', 'google_oauth.json'));
        authorize(creds, (ret) => {
            done(null, ret);
        });

        /**
         * Create an OAuth2 client with the given credentials, and then execute the
         * given callback function.
         *
         * @param {Object} credentials The authorization client credentials.
         * @param {function} callback The callback to call with the authorized client.
         */
        function authorize(credentials, callback) {
            const clientSecret = credentials.installed.client_secret;
            const clientId = credentials.installed.client_id;
            const redirectUrl = credentials.installed.redirect_uris[0];
            const auth = new googleAuth();
            const oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

            // Check if we have previously stored a token.
            fs.readFile(TOKEN_PATH, function (err, token) {
                if (err) {
                    console.error('[ERROR] Unable to read token', err)
                    getNewToken(oauth2Client, callback);
                } else {
                    oauth2Client.credentials = JSON.parse(token);
                    callback(oauth2Client);
                }
            });
        }

        /**
         * Get and store new token after prompting for user authorization, and then
         * execute the given callback with the authorized OAuth2 client.
         *
         * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
         * @param {getEventsCallback} callback The callback to call with the authorized
         *     client.
         */
        function getNewToken(oauth2Client, callback) {
            const authUrl = oauth2Client.generateAuthUrl({
                access_type: 'offline',
                scope: SCOPES
            });
            console.log('Authorize this app by visiting this url: ', authUrl);
            const readline = require('readline');
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout
            });
            rl.question('Enter the code from that page here: ', function (code) {
                rl.close();
                oauth2Client.getToken(code, function (err, token) {
                    if (err) {
                        console.log('Error while trying to retrieve access token', err);
                        return;
                    }
                    oauth2Client.credentials = token;
                    storeToken(token);
                    callback(oauth2Client);
                });
            });
        }

        /**
         * Store token to disk be used in later program executions.
         *
         * @param {Object} token The token to store to disk.
         */
        function storeToken(token) {
            try {
                fs.mkdirSync(TOKEN_DIR);
            } catch (err) {
                if (err.code != 'EEXIST') {
                    throw err;
                }
            }
            fs.writeFile(TOKEN_PATH, JSON.stringify(token));
            console.log('Token stored to ' + TOKEN_PATH);
        }

    };
    return factory
};

然后factory.connect(done)done auth使用googleapis

                const google = require('googleapis');
                const service = google.drive('v3');
                service.files.list({
                    auth,
                    pageSize: 10,
                    fields: 'nextPageToken, files(id, name)'
                }, step);