Skip to content

Instantly share code, notes, and snippets.

@BennyKok
Created August 27, 2023 16:38
Show Gist options
  • Save BennyKok/0c17b24bf7234555f59a0e31068c08b3 to your computer and use it in GitHub Desktop.
Save BennyKok/0c17b24bf7234555f59a0e31068c08b3 to your computer and use it in GitHub Desktop.
A nodejs cli function for getting user auth token using device flow.
async function handleGithubDeviceFlow(clientId) {
const a = await fetch("https://github.com/login/device/code", {
method: "POST",
body: JSON.stringify({
client_id: clientId,
scope: "user",
}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
}).then((x) => x.json())
// console.log(JSON.stringify(a))
console.log("Enter the user code: " + a.user_code)
if (!a.user_code) return
await open(a.verification_uri)
const device_code = a.device_code
await new Promise((resolve) => {
const pollToken = async () => {
setTimeout(async () => {
const a = await fetch("https://github.com/login/oauth/access_token", {
method: "POST",
body: JSON.stringify({
client_id: clientId,
device_code: device_code,
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
}).then((x) => x.json())
if (a.access_token) {
resolve(a.access_token)
} else {
pollToken()
}
}, a.interval * 1000)
}
pollToken()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment