-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathgithub-oauth-login.js
63 lines (56 loc) · 1.59 KB
/
github-oauth-login.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
addEventListener("fetch", (event) => {
event.respondWith(handle(event.request));
});
// use secrets
const client_id = CLIENT_ID;
const client_secret = CLIENT_SECRET;
async function handle(request) {
// handle CORS pre-flight request
if (request.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
},
});
}
// redirect GET requests to the OAuth login page on github.com
if (request.method === "GET") {
return Response.redirect(
`https://github.com/login/oauth/authorize?client_id=${client_id}`,
302
);
}
try {
const { code } = await request.json();
const response = await fetch(
"https://github.com/login/oauth/access_token",
{
method: "POST",
headers: {
"content-type": "application/json",
"user-agent": "cloudflare-worker-github-oauth-login-demo",
accept: "application/json",
},
body: JSON.stringify({ client_id, client_secret, code }),
}
);
const result = await response.json();
const headers = {
"Access-Control-Allow-Origin": "*",
};
if (result.error) {
return new Response(JSON.stringify(result), { status: 401, headers });
}
return new Response(JSON.stringify({ token: result.access_token }), {
status: 201,
headers,
});
} catch (error) {
console.error(error);
return new Response(error.message, {
status: 500,
});
}
}