-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.js
50 lines (45 loc) · 1.54 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
const fsp = require("fs").promises;
const { google } = require("googleapis");
const { authenticate } = require("@google-cloud/local-auth");
const path = require("path");
const HOST_TOKEN_PATH = "./host_token.json";
const DESTINATION_TOKEN_PATH = "./destination_token.json";
const SCOPES = ["https://www.googleapis.com/auth/drive"];
const APP_CREDENTIALS_PATH = path.join(__dirname, "credentials.json");
async function auth(isHost) {
let client = await loadSavedCredentialsIfExist(isHost);
if (client) return client;
client = await authenticate({
scopes: SCOPES,
keyfilePath: APP_CREDENTIALS_PATH,
});
if (client.credentials) {
await saveCredentials(client, isHost);
}
return client;
}
async function loadSavedCredentialsIfExist(isHost) {
try {
let content;
if (isHost) content = await fsp.readFile(HOST_TOKEN_PATH);
else content = await fsp.readFile(DESTINATION_TOKEN_PATH);
const credentials = JSON.parse(content);
return google.auth.fromJSON(credentials);
} catch (err) {
return null;
}
}
async function saveCredentials(client, isHost) {
const content = await fsp.readFile(APP_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,
});
if (isHost) await fsp.writeFile(HOST_TOKEN_PATH, payload);
else await fsp.writeFile(DESTINATION_TOKEN_PATH, payload);
}
module.exports = { auth };