-
Notifications
You must be signed in to change notification settings - Fork 8
/
sheetAuth.js
74 lines (69 loc) · 2.32 KB
/
sheetAuth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
let fs = require('fs');
let readline = require('readline');
let googleAuth = require('google-auth-library');
let SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_PATH = 'sheets.googleapis.com-cred.json';
class SheetAuth {
authenticate(){
return new Promise((resolve, reject)=>{
let credentials = this.getClientSecret();
let authorizePromise = this.authorize(credentials);
authorizePromise.then(resolve, reject);
});
}
getClientSecret(){
return require('./credentials.json');
}
authorize(credentials) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
return new Promise((resolve, reject)=>{
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) {
this.getNewToken(oauth2Client).then((oauth2ClientNew)=>{
resolve(oauth2ClientNew);
}, (err)=>{
reject(err);
});
} else {
oauth2Client.credentials = JSON.parse(token);
resolve(oauth2Client);
}
});
});
}
getNewToken(oauth2Client, callback) {
return new Promise((resolve, reject)=>{
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: \n ', authUrl);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('\n\nEnter the code from that page here: ', (code) => {
rl.close();
oauth2Client.getToken(code, (err, token) => {
if (err) {
console.log('Error while trying to retrieve access token', err);
reject();
}
oauth2Client.credentials = token;
this.storeToken(token);
resolve(oauth2Client);
});
});
});
}
storeToken(token) {
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
}
module.exports = new SheetAuth();