-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (72 loc) · 2.09 KB
/
index.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
79
80
81
82
// express
const express = require("express");
const app = express();
// dotenv
require("dotenv").config();
// body parser
const bodyParser = require("body-parser");
app.use(bodyParser.json());
//cors
const cors = require("cors");
app.use(cors());
const { google } = require("googleapis");
const oauth2Client = new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
"http://localhost:8080/handleGoogleRedirect" // server redirect url handler
);
app.post("/createAuthLink", cors(), (req, res) => {
const url = oauth2Client.generateAuthUrl({
access_type: "offline",
scope: [
"https://www.googleapis.com/auth/userinfo.email",
//calendar api scopes]
"https://www.googleapis.com/auth/calendar",
],
prompt: "consent",
});
res.send({ url });
});
app.get("/handleGoogleRedirect", async (req, res) => {
// get code from url
const code = req.query.code;
console.log("server 36 | code", code);
// get access token
oauth2Client.getToken(code, (err, tokens) => {
if (err) {
console.log("server 39 | error", err);
throw new Error(err.message);
}
const accessToken = tokens.access_token;
const refreshToken = tokens.refresh_token;
res.redirect(
`http://localhost:3000?accessToken=${accessToken}&refreshToken=${refreshToken}`
);
});
});
app.post("/getValidToken", async (req, res) => {
try {
const request = await fetch("https://www.googleapis.com/oauth2/v4/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
refresh_token: req.body.refreshToken,
grant_type: "refresh_token",
}),
});
const data = await request.json();
console.log("server 74 | data", data.access_token);
res.json({
accessToken: data.access_token,
});
} catch (error) {
res.json({ error: error.message });
}
});
app.listen(process.env.PORT || 8080, () => {
console.log("listening on port 8080");
});