discord.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { Request as ExpressRequest, Response as ExpressResponse } from "express";
  2. import { OAuth2 } from "src/utils/util";
  3. import { ENVIRONMENT } from "src/utils/environment";
  4. import { Option } from "@shared/common/async_utils";
  5. import { logger } from "src/utils/logging";
  6. export const get = async (req: ExpressRequest, res: ExpressResponse): Promise<void> => {
  7. res.redirect(OAuth2.getAuthUrl({
  8. client_id: ENVIRONMENT.clientId,
  9. redirect_url: ENVIRONMENT.redirectUrl,
  10. response_type: "code",
  11. scope: "identify",
  12. }));
  13. };
  14. type AuthResult = Option<unknown, {error: string}>;
  15. export const post = async (req: ExpressRequest, res: ExpressResponse):
  16. Promise<ExpressResponse<AuthResult>> => {
  17. if (!req.session) {
  18. logger.error("WEB: req.session is not set up correctly!");
  19. return res.json({
  20. ok: false,
  21. error: "No session is set up. This is a server error!",
  22. });
  23. }
  24. if (!req.session.authTokenCode) {
  25. logger.error("WEB: attempted to join with no authTokenCode set!");
  26. return res.json({
  27. ok: false,
  28. error: "Authentication token is missing. Please try logging in again.",
  29. });
  30. }
  31. const result = await OAuth2.getToken({
  32. client_id: ENVIRONMENT.clientId,
  33. client_secret: ENVIRONMENT.clientSecret,
  34. grant_type: "authorization_code",
  35. code: req.session.authTokenCode,
  36. scope: "identify",
  37. redirect_uri: ENVIRONMENT.redirectUrl,
  38. });
  39. if (!result.ok) {
  40. return res.json(result);
  41. }
  42. req.sessionOptions.maxAge = result.expires_in;
  43. return res.json({
  44. ok: true,
  45. });
  46. };