Skip to content

Instantly share code, notes, and snippets.

@MuhammadKhizar7
Created May 3, 2022 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MuhammadKhizar7/f25207ea96c5c793eb0aff4ca7143a79 to your computer and use it in GitHub Desktop.
Save MuhammadKhizar7/f25207ea96c5c793eb0aff4ca7143a79 to your computer and use it in GitHub Desktop.
cloudflare worder function to auth github
addEventListener('fetch', (event) => {
event.respondWith(handle(event.request))
})
// use secrets
const client_id = CLIENT_ID
const client_secret = CLIENT_SECRET
const redirect_uri = 'https://url.workers.dev'
const scope = 'repo,user'
function getScript(mess, content) {
return `<!doctype html><html><body><script>
(function() {
function receiveMessage(e) {
console.log("receiveMessage %o", e)
window.opener.postMessage(
'authorization:github:${mess}:${JSON.stringify(content)}',
e.origin
)
window.removeEventListener("message",receiveMessage,false);
}
window.addEventListener("message", receiveMessage, false)
console.log("Sending message: %o", "github")
window.opener.postMessage("authorizing:github", "*")
})()
</script></body></html>`
}
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',
},
})
}
console.log(request.url)
const code = new URL(request.url).searchParams.get('code')
const state = crypto.getRandomValues(new Uint32Array(1)).toString('hex')
// redirect GET requests to the OAuth login page on github.com
if (request.method === 'GET' && code === null) {
return Response.redirect(
`https://github.com/login/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&scope=${scope}&state=${state}`,
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': 'authUserdemo1',
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(
getScript('success', { token: result.access_token, provider: 'github' }),
{
status: 201,
mode: 'cors',
headers: {
'content-type': 'text/html;charset=UTF-8',
'user-agent': 'authUserdemo1',
'Access-Control-Allow-Origin': '*',
},
}
)
} catch (error) {
console.error(error)
return new Response(error.message, {
status: 500,
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment