import { Request, Response, NextFunction } from "express"; import request from "request-promise-native"; import { Response as Res } from "request"; import { botService } from "src/util/rpc_client"; const API_ENDPOINT = "https://discordapp.com/api"; export async function get(req : Request, res : Response, next: NextFunction) { if(!req.query.code) throw new Error("NoCodeProvided"); let code = req.query.code; let response = await request("/oauth2/token", { method: "POST", baseUrl: API_ENDPOINT, qs: { grant_type: "authorization_code", code: code, redirect_uri: `${process.env.ADMIN_URL}/login/discord/callback` }, auth: { user: process.env.BOT_CLIENT_ID, pass: process.env.BOT_CLIENT_SECRET }, resolveWithFullResponse: true }) as Res; let authResponse: AuthResponse = JSON.parse(response.body); let userInfoResponse = await request("/users/@me", { method: "GET", baseUrl: API_ENDPOINT, auth: { bearer: authResponse.access_token }, resolveWithFullResponse: true }); let discordUser : DiscordUser = JSON.parse(userInfoResponse.body); try { let userInfo = await botService.getModeratorUserInfo({id: discordUser.id}); req.session.user = userInfo; res.redirect(`${process.env.ADMIN_URL}/`); } catch(e) { console.log(`Failed to authorise user because: ${e}`); res.redirect(`${process.env.ADMIN_URL}/login/?error=invalid_user`); return; } }; interface AuthResponse { access_token: string; token_type: string; expires_in: number; refresh_token?: string; scope: string; } interface DiscordUser { id: string; username: string; discriminator: string; avatar?: string; bot?: boolean; mfa_enabled?: boolean; locale?: string; verified?: boolean; email?: string; flags?: number; premium_type?: number; }