in-the-database-2/src/auth.ts

40 lines
1.2 KiB
TypeScript

const API_ENDPOINT = 'https://discord.com/api/v6';
const axios = require('axios').default;
export function run(app) {
app.get('/discordauth', async (req, res) => {
const code = req.query.code;
if (code) {
try {
const data = new URLSearchParams({
client_id: process.env.DISCORD_OAUTH_CLIENTID,
client_secret: process.env.DISCORD_OAUTH_CLIENTSECRET,
grant_type: 'authorization_code',
code: code,
redirect_uri: 'http://localhost:8080/discordauth',
scope: 'identify'
});
const postRes = await axios.post(`${API_ENDPOINT}/oauth2/token`, data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const userInfo = await axios.get(`${API_ENDPOINT}/users/@me`, {
headers: {
authorization: `${postRes.data.token_type} ${postRes.data.access_token}`
}
});
res.send(`hi ${userInfo.data.username}#${userInfo.data.discriminator}`);
} catch(err) {
res.send(`whoooops<br>${err}`);
}
} else {
res.send('https://discord.com/api/oauth2/authorize?client_id=750952563079250012&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fdiscordauth&response_type=code&scope=identify');
}
});
}