Вы можете использовать маркер 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);
Методика заключается в использовании прав у вас есть учетная запись службы для олицетворения (любой) учетной записи пользователя в домене компании. В примере кода, к которому вы привязались, это переменная userEmail, которую вы будете использовать. –
@PeterHerrmann и все? так что все, что мне нужно, это учетная запись службы с доменной делегацией, и я могу получить доступ к файлам всех пользователей в компании? – MartinGian
Да. Пожалуйста, обновите свой вопрос, чтобы он включал конкретные вопросы, на которые вы хотели бы ответить. –