Repository navigation
Expand file tree
/
Copy pathauth.js
More file actions
80 lines (68 loc) · 2.3 KB
/
Copy pathauth.js
File metadata and controls
80 lines (68 loc) · 2.3 KB
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
79
80
/**
* auth.js — Run ONCE to authorize Google Calendar access.
* Generates token.json which the bot uses for all future requests.
*
* Usage: node auth.js
*/
import { createRequire } from "module";
import fs from "fs";
import readline from "readline";
import { google } from "googleapis";
const require = createRequire(import.meta.url);
const SCOPES = [
"https://www.googleapis.com/auth/calendar.events",
"https://www.googleapis.com/auth/calendar.readonly",
];
const CREDENTIALS_PATH = "./credentials/credentials.json";
const TOKEN_PATH = "./credentials/token.json";
async function main() {
if (!fs.existsSync(CREDENTIALS_PATH)) {
console.error(`❌ credentials.json not found at ${CREDENTIALS_PATH}`);
process.exit(1);
}
const raw = fs.readFileSync(CREDENTIALS_PATH, "utf-8");
const creds = JSON.parse(raw);
// Support both flat and nested (installed/web) credential formats
const { client_id, client_secret, redirect_uris } =
creds.installed || creds.web || creds;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0],
);
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
prompt: "consent", // force refresh_token to be returned
});
console.log("\n🔐 Google Calendar OAuth2 Authorization\n");
console.log("1. Open this URL in your browser:\n");
console.log(" " + authUrl);
console.log(
"\n2. Sign in, allow access, then copy the code from the address bar.",
);
console.log(
" (It appears after ?code= and ends before &scope or similar)\n",
);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question("3. Paste the code here and press Enter: ", async (code) => {
rl.close();
try {
const { tokens } = await oAuth2Client.getToken(code.trim());
fs.writeFileSync(TOKEN_PATH, JSON.stringify(tokens, null, 2));
console.log(`\n✅ token.json saved! The bot can now manage your calendar.\n`);
} catch (err) {
console.error("\n❌ Failed to get token:", err.message);
if (err.message.includes("redirect_uri_mismatch")) {
console.error(
" → In Google Console, add this redirect URI: http://localhost",
);
}
}
process.exit(0);
});
}
main();