57 lines
2.0 KiB
JavaScript
57 lines
2.0 KiB
JavaScript
const app = require('express').Router();
|
|
const qs = require("qs");
|
|
const axios = require('axios');
|
|
const crypto = require("crypto");
|
|
const Account = require("../models/Account");
|
|
const Session = require("../models/Session");
|
|
|
|
app.post("/token", async (req, res) => {
|
|
// Check if code is valid
|
|
if (!req.body.code) return res.status(400).json({message: "You need to provide a code"});
|
|
|
|
try {
|
|
// Get access & refresh token
|
|
const tokens = await axios.post(DISCORD_TOKEN_ENDPOINT, qs.stringify({
|
|
"code": req.body.code, "grant_type": "authorization_code", "client_secret": process.env.CLIENT_SECRET,
|
|
"client_id": process.env.CLIENT_ID, "redirect_uri": process.env.REDIRECT_URI
|
|
}));
|
|
|
|
// Check if all scopes are provided
|
|
if (tokens.data.scope !== "identify email guilds") throw "Not all scopes were specified";
|
|
|
|
// Get user data
|
|
const {data} = await axios.get(DISCORD_USER_ENDPOINT, {
|
|
headers: {Authorization: "Bearer " + tokens.data.access_token}
|
|
});
|
|
|
|
//Check if account exists
|
|
const account = await Account.findAndCountAll({where: {client_id: data.id}});
|
|
|
|
// Define user data
|
|
userData = {client_id: data.id, username: data.username+"#"+data.discriminator,
|
|
email: data.email, locale: data.locale, avatar: data.avatar};
|
|
|
|
// Create/update account
|
|
if (account.count === 1)
|
|
await Account.update(userData,{where: {client_id: data.id}});
|
|
else await Account.create(userData);
|
|
|
|
// Generate random token
|
|
const token = crypto.randomBytes(48).toString('hex');
|
|
|
|
// Create session
|
|
await Session.create({
|
|
token: token, client_id: data.id, access_token: tokens.data.access_token, refresh_token: tokens.data.refresh_token,
|
|
user_agent: req.get("user-agent")
|
|
});
|
|
|
|
// Return token
|
|
res.status(200).json({token: token});
|
|
|
|
} catch (e) {
|
|
res.status(400).json({message: "Something went wrong"});
|
|
}
|
|
|
|
});
|
|
|
|
module.exports = app; |