Skip to content

Instantly share code, notes, and snippets.

@Lohann
Created April 26, 2023 23:12
Show Gist options
  • Save Lohann/406e5d80d9080c5ba2c0d7485f09b9dd to your computer and use it in GitHub Desktop.
Save Lohann/406e5d80d9080c5ba2c0d7485f09b9dd to your computer and use it in GitHub Desktop.
// "dependencies": {
// "axios": "^1.3.6"
// }
const axios = require('axios');
const CLIENT_ID = '<client_id_aqui>';
async function run(token) {
console.log(token);
}
async function main() {
const {
device_code,
user_code,
verification_uri,
expires_in,
interval,
} = (await axios.post(
'https://github.com/login/device/code',
{
client_id: CLIENT_ID,
scope: 'public_repo user:email',
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
},
)).data;
const expireDate = Date.now() + (expires_in * 1000);
// Informar usuario
console.log('Acesse essa url: ' + verification_uri);
console.log('E informe o código: ' + user_code);
const intervalHandler = setInterval(async () => {
const currentDate = Date.now();
if (currentDate >= expireDate) {
clearInterval(intervalHandler);
console.error('Authentication expired');
return;
}
const { data } = await axios.post(
'https://github.com/login/oauth/access_token',
{
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
client_id: CLIENT_ID,
device_code: device_code,
},
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
},
);
if (data.error) {
switch (data.error) {
case 'authorization_pending':
console.log('Waiting for authorization...');
break;
case 'expired_token':
clearInterval(intervalHandler);
console.error('Authentication expired');
break;
default:
clearInterval(intervalHandler);
console.error('Unknown error', data);
break;
}
} else {
clearInterval(intervalHandler);
run(data);
}
}, interval * 2000);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment