-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
58 lines (50 loc) · 1.59 KB
/
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
const fsPromises = require('fs').promises;
const path = require('path');
const { google } = require('googleapis');
const { authenticate } = require('@google-cloud/local-auth');
const SCOPES = [
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/drive.metadata.readonly',
];
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
async function loadSavedCredentials() {
try {
const content = await fsPromises.readFile(TOKEN_PATH);
const credentials = JSON.parse(content);
return google.auth.fromJSON(credentials);
} catch (err) {
if (err.code !== 'ENOENT') {
console.error('Error loading saved credentials:', err);
}
return null;
}
}
async function saveCredentials(client) {
try {
const content = await fsPromises.readFile(CREDENTIALS_PATH);
const keys = JSON.parse(content);
const key = keys.installed || keys.web;
const payload = JSON.stringify({
type: 'authorized_user',
client_id: key.client_id,
client_secret: key.client_secret,
refresh_token: client.credentials.refresh_token,
});
await fsPromises.writeFile(TOKEN_PATH, payload);
} catch (err) {
console.error('Error saving credentials:', err);
}
}
async function authorize() {
let client = await loadSavedCredentials();
if (client) {
return client;
}
client = await authenticate({ scopes: SCOPES, keyfilePath: CREDENTIALS_PATH });
if (client.credentials) {
await saveCredentials(client);
}
return client;
}
module.exports = { authorize };