callback.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { Request, Response, NextFunction } from "express";
  2. import request from "request-promise-native";
  3. import { Response as Res } from "request";
  4. import { botService } from "src/util/rpc_client";
  5. const API_ENDPOINT = "https://discordapp.com/api";
  6. export async function get(req : Request, res : Response, next: NextFunction) {
  7. if(!req.query.code)
  8. throw new Error("NoCodeProvided");
  9. let code = req.query.code;
  10. let response = await request("/oauth2/token", {
  11. method: "POST",
  12. baseUrl: API_ENDPOINT,
  13. qs: {
  14. grant_type: "authorization_code",
  15. code: code,
  16. redirect_uri: `${process.env.ADMIN_URL}/login/discord/callback`
  17. },
  18. auth: {
  19. user: process.env.BOT_CLIENT_ID,
  20. pass: process.env.BOT_CLIENT_SECRET
  21. },
  22. resolveWithFullResponse: true
  23. }) as Res;
  24. let authResponse: AuthResponse = JSON.parse(response.body);
  25. let userInfoResponse = await request("/users/@me", {
  26. method: "GET",
  27. baseUrl: API_ENDPOINT,
  28. auth: {
  29. bearer: authResponse.access_token
  30. },
  31. resolveWithFullResponse: true
  32. });
  33. let discordUser : DiscordUser = JSON.parse(userInfoResponse.body);
  34. try {
  35. let userInfo = await botService.getModeratorUserInfo({id: discordUser.id});
  36. req.session.user = userInfo;
  37. res.redirect(`${process.env.ADMIN_URL}/`);
  38. } catch(e) {
  39. console.log(`Failed to authorise user because: ${e}`);
  40. res.redirect(`${process.env.ADMIN_URL}/login/?error=invalid_user`);
  41. return;
  42. }
  43. };
  44. interface AuthResponse {
  45. access_token: string;
  46. token_type: string;
  47. expires_in: number;
  48. refresh_token?: string;
  49. scope: string;
  50. }
  51. interface DiscordUser {
  52. id: string;
  53. username: string;
  54. discriminator: string;
  55. avatar?: string;
  56. bot?: boolean;
  57. mfa_enabled?: boolean;
  58. locale?: string;
  59. verified?: boolean;
  60. email?: string;
  61. flags?: number;
  62. premium_type?: number;
  63. }