thomasatflexos-redirect.express.val.run
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
import { fetch } from "https://esm.town/v/std/fetch";
import process from "node:process";
/**
This is a handler for when Notion redirects during OAuth 2.0 workflow
**/
export let redirect = async (req: express.Request, res: express.Response) => {
let code = req.query.code;
if (!code) {
res.json({ status: 400, Reason: "Invalid access token" });
}
// Retrieve Notion access token given a temporary code
const postData = {
"code": code,
"grant_type": "authorization_code",
"redirect_uri": process.env.NOTION_SMALL_STEPS_REDIRECT_URL,
};
// This endpoint uses Basic Authentication which requires a 64-encoded token
const token = process.env.OAUTH_CLIENT_ID + ":" +
process.env.OAUTH_CLIENT_SECRET;
const response = await fetch("https://api.notion.com/v1/oauth/token", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Notion-Version": "2022-06-28",
Authorization: `Basic ${btoa(token)}`,
},
body: JSON.stringify(postData),
});
const notionAuthRes = await response.json();
// Retrieve access token and other properties to save to database
let accessToken = notionAuthRes.access_token;
let email = notionAuthRes.owner.user.person.email;
let bot_id = notionAuthRes.bot_id;
// Using supabase to store out information
const { createClient } = await import(
"https://esm.sh/@supabase/supabase-js@2"
);
const supabase = createClient(
process.env.supabaseURL,
process.env.supabaseKey,
);
const { data, error } = await supabase
.from("small_steps_user")
.insert({ email: email, notion_auth_token: accessToken, bot_id: bot_id });
if (error) {
throw error;
}
const botIdResponse = JSON.stringify({ bot_id: bot_id });
res.send(`
<!DOCTYPE html>
<html>
<body>
<script>
window.opener.parent.postMessage(${botIdResponse}, "*");
window.close();
</script>
</body>
</html>
`);
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023