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

39 lines
1.3 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}<br><img src="https://media.discordapp.net/avatars/${userInfo.data.id}/${userInfo.data.avatar}.png">`);
} catch(err) {
res.send(`whoooops<br>${err}`);
}
} else {
res.send(`<a href="https://discord.com/api/oauth2/authorize?client_id=${process.env.DISCORD_OAUTH_CLIENTID}&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fdiscordauth&response_type=code&scope=identify">Click here!!</a>`);
}
});
}