xonecas.io
4436
Sl

sesame-labs-coding-assignment / files

sesame-labs-coding-assignment / api / src / discord / index.ts

3.9 KB
1import Router from "koa-router";
2import Koa from "koa";
3import axios, { AxiosError } from "axios";
4import { stringify } from "querystring";
5import { StatusCodes } from "http-status-codes";
6import { getCouponCode } from "../quest/util";
7
8const router = new Router({ prefix: "/discord" });
9
10router.get(
11  "/callback",
12  async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
13    const code = ctx.request.query.code;
14    const state = Number(ctx.request.query.state);
15
16    if (!code) {
17      ctx.status = StatusCodes.UNAUTHORIZED;
18      return await next();
19    }
20
21    try {
22      const response = await axios.post(
23        "https://discord.com/api/v10/oauth2/token",
24        stringify({
25          client_id: process.env.DISCORD_CLIENT_ID,
26          client_secret: process.env.DISCORD_CLIENT_SECRET,
27          grant_type: "authorization_code",
28          code: code,
29          redirect_uri: process.env.DISCORD_REDIRECT_URL,
30        }),
31        {
32          headers: { "Content-Type": "application/x-www-form-urlencoded" },
33        }
34      );
35
36      const discordToken = await ctx.prisma.discordToken.create({
37        data: {
38          accessToken: response.data.access_token,
39          expiresIn: response.data.expires_in,
40          refreshToken: response.data.refresh_token,
41          scope: response.data.scope,
42          tokenType: response.data.token_type,
43        },
44      });
45
46      await ctx.prisma.user.update({
47        where: { id: state },
48        data: { discordTokenId: discordToken.id },
49      });
50
51      ctx.status = StatusCodes.CREATED;
52      ctx.redirect("/discord/join");
53
54      await next();
55    } catch (e) {
56      console.error(e);
57      throw e;
58    }
59  }
60);
61
62router.get("/join", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
63  if (!ctx.session) {
64    ctx.status = StatusCodes.FORBIDDEN;
65    return await next();
66  }
67
68  const user = await ctx.prisma.user.findUnique({
69    where: { walletAddress: ctx.session.user.walletAddress },
70    include: { discordToken: true },
71  });
72
73  if (!user.discordToken) {
74    const authorize_url =
75      "https://discord.com/api/oauth2/authorize" +
76      `?client_id=${process.env.DISCORD_CLIENT_ID}` +
77      `&redirect_uri=${encodeURI(process.env.DISCORD_REDIRECT_URL || "")}` +
78      `&response_type=code` +
79      `&scope=identify bot guilds guilds.members.read` +
80      `&state=${user.id}`;
81
82    ctx.redirect(authorize_url);
83    return await next();
84  }
85
86  try {
87    const inviteCode = await axios
88      .post(
89        `https://discord.com/api/v10/channels/${process.env.QUEST_CHANNEL_ID}/invites`,
90        {},
91        {
92          headers: {
93            Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
94            "Content-Type": "application/json",
95          },
96        }
97      )
98      .then((response) => response.data.code);
99
100    ctx.session.user = user;
101    ctx.redirect(`http://discord.gg/${inviteCode}`);
102
103    await next();
104  } catch (e) {
105    console.error(e);
106    throw e;
107  }
108});
109
110router.get("/verify", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
111  if (!ctx.session) {
112    ctx.status = StatusCodes.FORBIDDEN;
113    return await next();
114  }
115
116  const guildId = process.env.QUEST_GUILD_ID;
117  // Use the token acquired to get the user and it's joined guilds
118  const authorizationHeader = {
119    Authorization: `Bearer ${ctx.session.user.discordToken.accessToken}`,
120    "Content-Type": "application/x-www-form-urlencoded",
121  };
122
123  try {
124    await axios.get(
125      `https://discord.com/api/v10/users/@me/guilds/${guildId}/member`,
126      {
127        headers: authorizationHeader,
128      }
129    );
130  } catch (e) {
131    console.error(e);
132    throw e;
133  }
134
135  // 10 random characters alphanumeric string
136  const coupon = getCouponCode();
137
138  ctx.body = ctx.session.user = await ctx.prisma.user.update({
139    where: { walletAddress: ctx.session.user.walletAddress },
140    include: { discordToken: true },
141    data: { verified: true, coupon },
142  });
143  ctx.status = StatusCodes.OK;
144
145  await next();
146});
147
148export default router;