This repository has been archived by the owner on Oct 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.ts
197 lines (184 loc) · 6.56 KB
/
util.ts
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import { OAuth2Client, generateCodeVerifier } from "@badgateway/oauth2-client";
import { nodes, state, root } from "membrane";
type Method = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
export async function api(
method: Method,
domain: string,
path: string,
query?: any,
body?: string
) {
if (query) {
Object.keys(query).forEach((key) =>
query[key] === undefined ? delete query[key] : {}
);
}
const querystr =
query && Object.keys(query).length ? `?${new URLSearchParams(query)}` : "";
// The HTTP node to use. Either Membrane's authenticated HTTP node or the regular one we have an access token.
let req = {
method,
url: `https://${domain}/${path}${querystr}`,
body,
headers: {},
};
if (state.accessToken) {
if (await state.oauth2Client.isExpired(state.accessToken)) {
console.log("Refreshing access token...");
state.accessToken = await state.oauth2Client.refreshToken(
state.accessToken
);
}
// Sign the request with the access token
req.headers["Authorization"] = `Bearer ${state.accessToken.accessToken}`;
}
return await fetch(req.url, { ...req, http: httpNode() });
}
export function usingUserApiKey() {
return state.clientId && state.clientSecret;
}
export async function authStatus() {
if (usingUserApiKey()) {
if (state.accessToken) {
return `Ready`;
} else {
return `Client ID/Secret configured. [Sign In](${await endpointUrl()}).`;
}
} else {
if (await authenticatedNode().hasAuthenticated) {
return `Ready`;
} else {
return `[Sign In](${await endpointUrl()})`;
}
}
}
// The HTTP node to use, depends on whether we have a user-provided API key or not
function httpNode(): http.Root | http.Authenticated {
if (usingUserApiKey()) {
return nodes.http;
} else {
return authenticatedNode();
}
}
function authenticatedNode(): http.Authenticated {
return nodes.http.authenticated({
api: "google-docs",
authId: root.authId,
});
}
export async function endpoint({ path, query, headers, body }) {
const link = await nodes.http
.authenticated({ api: "google-docs", authId: root.authId })
.createLink();
switch (path) {
case "/": {
return html(indexHtml(link, "auth"));
}
case "/auth":
case "/auth/": {
if (!state.clientId || !state.clientSecret) {
return JSON.stringify({ status: 303, headers: { location: "/" } });
}
await createAuthClient();
const codeVerifier = await generateCodeVerifier();
state.codeVerifier = codeVerifier;
const url = await state.oauth2Client.authorizationCode.getAuthorizeUri({
redirectUri: `${await endpointUrl()}/auth/callback`,
scope: [
"https://www.googleapis.com/auth/documents",
"https://www.googleapis.com/auth/drive.readonly",
],
codeVerifier,
});
return JSON.stringify({ status: 303, headers: { location: url } });
}
case "/auth/callback": {
const token =
await state.oauth2Client.authorizationCode.getTokenFromCodeRedirect(
`${path}?${query}`,
{
redirectUri: `${await endpointUrl()}/auth/callback`,
codeVerifier: state.codeVerifier,
}
);
state.accessToken = token;
if (token.accessToken) {
return html(`Driver configured!`);
}
return html(
`There was an issue acquiring the access token. Check the logs.`
);
}
default:
return JSON.stringify({ status: 404, body: "Not found" });
}
}
// Helper function to produce nicer HTML
function html(body: string) {
// <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/bootstrap-reboot.css">
return `
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>Google Docs Driver for Membrane</title>
<link rel="stylesheet" href="https://www.membrane.io/light.css"></script>
</head>
<body>
<div style="position: absolute; inset: 0px; display: flex; flex-direction: row; justify-content: center; align-items: center;">
<div style="display: flex; flex-direction: column; align-items: center; max-width: 800px;">
${body}
</div>
</div>
</body>
`;
}
// Offer the option to use the user's own API key/secret or use Membrane's authentication
function indexHtml(membraneAuthUrl: string, customAuthUrl: string) {
return html(`
<div style="display: flex; flex-direction: row; justify-content: space-around; align-items: center; margin-bottom: 18px;">
<img style="width: 40px; height: 40px; margin-right: 10px;" src="https://lh3.googleusercontent.com/1DECuhPQ1y2ppuL6tdEqNSuObIm_PW64w0mNhm3KGafi40acOJkc4nvsZnThoDKTH8gWyxAnipJmvCiszX8R6UAUu1UyXPfF13d7"/>
<h1>Google Docs Driver for Membrane</h1>
</div>
<div style="display: flex; flex-direction: row; justify-content: space-around; align-items: center;">
<section style="flex: 1; justify-content: space-between; align-items: center;">
<h2>Membrane authentication</h2>
<p>Use Membrane's Google Docs integration to sign-in. This is the recommended method.</p>
<a class="button" href="${membraneAuthUrl}">Sign in with Google</a>
<p> </p>
</section>
Or
<section style="flex: 1; justify-content: center; align-items: center;">
<h2>Bring your own Key</h2>
<p>Alternatively, use your own Google Client ID and Secret. This is more complicated but useful if you already have a Google Cloud account or want to use this API beyond Membrane's limits.</p>
${
state.clientId && state.clientSecret
? "<p>✅ Client ID and Secret configured</p>" +
(state.accessToken
? "<p>✅ User signed-in</p>"
: "<p>❌ User <b>not signed-in</b></p>") +
`<p><a class="button" href=${customAuthUrl}/>Sign in with Google</a></p>`
: "<p>Client ID and Secret <b>not configured</b>.</p> <p>Invoke <code>:configure</code> with your Google Docs API Key and Secret to authenticate</p>"
}
</section>
</div>
`);
}
export async function createAuthClient() {
const { clientId, clientSecret } = state;
if (clientId && clientSecret) {
state.oauth2Client = new OAuth2Client({
clientId,
clientSecret,
server: "https://accounts.google.com",
tokenEndpoint: "https://oauth2.googleapis.com/token",
authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
});
}
}
// Cached endpoint URL since it's immutable
export async function endpointUrl() {
if (!state.endpointUrl) {
state.endpointUrl = await nodes.process.endpointUrl;
}
return state.endpointUrl;
}