Skip to content

Instantly share code, notes, and snippets.

@EsteveSegura
Created August 12, 2020 20:45
Show Gist options
  • Save EsteveSegura/100725a81b1f56787131763a262df4b3 to your computer and use it in GitHub Desktop.
Save EsteveSegura/100725a81b1f56787131763a262df4b3 to your computer and use it in GitHub Desktop.
oauth discord
const express = require('express');
const btoa = require('btoa');
const fecth = require('node-fetch');
const app = express();
const idDiscord = 'xxxxxxxxxxxxxxxx';
const secretDiscord = 'xxxxxxxxxxxxxxxx';
const redirect = 'http://localhost:3000/callback';
app.get('/', (req,res)=>{
res.send("OK");
});
app.get('/login', (req,res)=>{
res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=${idDiscord}&redirect_uri=${redirect}&response_type=code&scope=guilds%20identify%20email`);
});
app.get('/login/:token', async(req,res)=>{
const response = await fecth(`https://discordapp.com/api/users/@me`,{
method: 'GET',
headers: {
Authorization : `Bearer ${req.params.token}`
}
});
let json = await response.json();
res.json(json);
})
app.get('/callback', async(req,res)=>{
if(!req.query.code){
console.log('fail');
}else{
const code = req.query.code;
const cred = btoa(`${idDiscord}:${secretDiscord}`);
const response = await fecth(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}&scope=guilds%20identify%20email`,{
method: 'POST',
headers: {
Authorization : `Basic ${cred}`
},
});
let json = await response.json();
res.redirect(`/login/${json.access_token}`);
}
});
app.listen(3000, ()=> {
console.log('running server');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment