-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudflare-worker-configured.js
More file actions
107 lines (93 loc) · 2.85 KB
/
cloudflare-worker-configured.js
File metadata and controls
107 lines (93 loc) · 2.85 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
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
// Cloudflare Worker for GitHub OAuth Authentication
// Deploy this on Cloudflare Workers: https://workers.cloudflare.com/
// CONFIGURATION - Your credentials are already configured!
const GITHUB_CLIENT_ID = 'Ov23licjO6ph0IxnBL8Y';
const GITHUB_CLIENT_SECRET = '5b62adff184f9d0372e730bf941221637a8769c8';
const ALLOWED_ORIGIN = 'https://Tejakrishna-b.github.io';
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
// CORS headers
const corsHeaders = {
'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
}
// Handle CORS preflight requests
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: corsHeaders
})
}
// Handle GitHub OAuth callback
if (request.method === 'POST' && url.pathname === '/auth/github') {
try {
const { code } = await request.json()
if (!code) {
return new Response(JSON.stringify({ error: 'Code is required' }), {
status: 400,
headers: {
'Content-Type': 'application/json',
...corsHeaders
}
})
}
// Exchange authorization code for access token
const tokenResponse = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
client_id: GITHUB_CLIENT_ID,
client_secret: GITHUB_CLIENT_SECRET,
code: code
})
})
const data = await tokenResponse.json()
if (data.error) {
return new Response(JSON.stringify({ error: data.error_description || 'Authentication failed' }), {
status: 400,
headers: {
'Content-Type': 'application/json',
...corsHeaders
}
})
}
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
...corsHeaders
}
})
} catch (error) {
return new Response(JSON.stringify({
error: 'Authentication failed',
details: error.message
}), {
status: 500,
headers: {
'Content-Type': 'application/json',
...corsHeaders
}
})
}
}
// Health check endpoint
if (request.method === 'GET' && url.pathname === '/health') {
return new Response(JSON.stringify({
status: 'ok',
service: 'GitHub OAuth Proxy',
timestamp: new Date().toISOString()
}), {
headers: {
'Content-Type': 'application/json',
...corsHeaders
}
})
}
return new Response('Not Found', { status: 404 })
}