/
google_auth.js
executable file
·78 lines (63 loc) · 2.13 KB
/
google_auth.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
75
76
77
78
const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const Config = require('./src/backend/Config.js')
// https://developers.google.com/tasks/quickstart/nodejs
const SCOPES = [
'https://www.googleapis.com/auth/tasks',
'https://www.googleapis.com/auth/calendar.events.readonly'
];
const ENV_PATH = path.join(__dirname, '.env');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
const config = new Config(console)
async function loadSavedCredentialsIfExist() {
console.log('loading existing settings')
try {
await config.load()
const clientId = config.getProp('google.clientId')
const clientSecret = config.getProp('google.clientSecret')
const clientToken = config.getProp('google.clientToken')
if(!clientId || !clientSecret || !clientToken) return null
return google.auth.fromJSON({
type: "authorized_user",
client_id: clientId.substring(22),
client_secret: clientSecret.substring(26),
refresh_token: clientToken.substring(25)
});
} catch (err) {
return null;
}
}
async function saveCredentials(client) {
console.log('updating settings')
const content = await fs.readFile(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const clientId = key.client_id
const clientSecret = key.client_secret
const token = client.credentials.refresh_token
await config.load()
config.setProp('google.clientId', clientId)
config.setProp('google.clientSecret', clientSecret)
config.setProp('google.clientToken', token)
await config.save()
}
async function authorize() {
console.log('Authorization...')
let client = await loadSavedCredentialsIfExist();
if (client) {
console.log('Already authorized')
return client;
}
client = await authenticate({
scopes: SCOPES,
keyfilePath: CREDENTIALS_PATH,
});
if (client.credentials) {
await saveCredentials(client);
}
return client;
}
authorize().then(() => console.log('done')).catch(console.error);