xonecas.io
4436
Sl

sesame-labs-coding-assignment / commit 64b4bcd

Adds finished discord join flow

Sean2023-01-15 64b4bcd51f63c32fd21ae92834cfab636ec8db67 parent 918248c

21 files changed

.gitignore+2−1
@@ -1,3 +1,4 @@
11 .vscode
22 .keys
3-node_modules
3+node_modules
4+.env
api/.env.example+28−0
@@ -0,0 +1,28 @@
1+# Api server values:
2+ENVIRONMENT=dev
3+PORT=3001
4+CLIENT_URL="http://localhost:3000/"
5+
6+# Discord related values:
7+DISCORD_APPLICATION_ID=000000000000000000
8+DISCORD_CLIENT_ID=000000000000000000
9+DISCORD_CLIENT_SECRET=000000000000000000-000000
10+DISCORD_REDIRECT_URL='http://localhost:3001/discord/callback'
11+DISCORD_BOT_TOKEN=000000000000000000000000000000000000000000000000000000000000000000000000
12+
13+# Quest related values:
14+# In Discord terms guild is a server
15+QUEST_TITLE='Join Seans server'
16+QUEST_DESCRIPTION='Come game with Sean'
17+QUEST_COVER_IMG='http://localhost:3000/public/quest-image.png'
18+QUEST_GUILD_ID=000000000000000000
19+QUEST_GUILD_NAME='Seans server'
20+
21+# This was inserted by `prisma init`:
22+# Environment variables declared in this file are automatically made available to Prisma.
23+# See the documentation for more detail: https://pris.ly/d/prisma-schema#accessing-environment-variables-from-the-schema
24+
25+# Prisma supports the native connection string format for PostgreSQL, MySQL, SQLite, SQL Server, MongoDB and CockroachDB.
26+# See the documentation for all the connection string options: https://pris.ly/d/connection-strings
27+
28+DATABASE_URL="file:./dev.db"
api/dist/authentication/index.js+7−3
@@ -19,12 +19,13 @@ router.post("/authenticate", (ctx, next) => __awaiter(void 0, void 0, void 0, fu
1919 let user = null;
2020 // Check for an existing user:
2121 user = yield ctx.prisma.user.findUnique({
22- where: { wallet_address: data.wallet_address },
22+ where: { walletAddress: data.walletAddress },
23+ include: { discordToken: true },
2324 });
2425 // New user:
2526 if (!user) {
2627 user = yield ctx.prisma.user.create({
27- data: { wallet_address: data.wallet_address },
28+ data: { walletAddress: data.walletAddress },
2829 });
2930 ctx.status = 201;
3031 }
@@ -44,7 +45,10 @@ router.post("/deauthenticate", (ctx, next) => __awaiter(void 0, void 0, void 0,
4445 router.get("/authenticated_user", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
4546 var _a;
4647 if ((_a = ctx.session) === null || _a === void 0 ? void 0 : _a.user) {
47- ctx.body = ctx.session.user;
48+ ctx.body = ctx.session.user = yield ctx.prisma.user.findUnique({
49+ include: { discordToken: true },
50+ where: { walletAddress: ctx.session.user.walletAddress },
51+ });
4852 ctx.status = 200;
4953 }
5054 yield next();
api/dist/discord/index.js+88−12
@@ -13,37 +13,113 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
1313 };
1414 Object.defineProperty(exports, "__esModule", { value: true });
1515 const koa_router_1 = __importDefault(require("koa-router"));
16+const axios_1 = __importDefault(require("axios"));
17+const querystring_1 = require("querystring");
1618 const router = new koa_router_1.default({ prefix: "/discord" });
17-// TODO: Consider using something `disco-oauth2`
18-router.get("/join", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
19+router.get("/authorize", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
20+ var _a;
21+ if (!ctx.session) {
22+ ctx.status = 403;
23+ return yield next();
24+ }
1925 // Front end will send the user here, and then from here into the authorization flow:
20- //https://discord.com/api/oauth2/authorize?client_id=1064167640148476004&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fdiscord%2Fcallback&response_type=code&scope=guilds.join%20guilds.members.read
21- // TODO: Add `state` url param for extra security
26+ // https://discord.com/api/oauth2/authorize?
27+ // client_id=1064167640148476004&
28+ // redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fdiscord%2Fcallback&
29+ // response_type=code&
30+ // scope=guilds.join%20guilds.members.read
2231 const authorize_url = "https://discord.com/api/oauth2/authorize" +
2332 `?client_id=${process.env.DISCORD_CLIENT_ID}` +
2433 `&redirect_uri=${encodeURI(process.env.DISCORD_REDIRECT_URL || "")}` +
2534 `&response_type=code` +
26- `&scope=guilds.join guilds.members.read`;
35+ `&scope=identify guilds guilds.join guilds.members.read` +
36+ `&state=${(_a = ctx.session) === null || _a === void 0 ? void 0 : _a.user.id}`;
2737 ctx.redirect(authorize_url);
2838 yield next();
2939 }));
3040 router.get("/callback", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
31- // OAuth callback
32- // TODO: use the token to get the user ID and join the server.
33- // https://discordapp.com/api/guilds/${SERVER_ID}/members/${userID}
34- var _a;
35- const code = (_a = ctx.request.query) === null || _a === void 0 ? void 0 : _a.code;
41+ const code = ctx.request.query.code;
42+ const state = Number(ctx.request.query.state);
3643 if (code) {
3744 // Success, we should exchange the code for a token:
3845 // https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-exchange-example
46+ const response = yield axios_1.default.post("https://discord.com/api/v10/oauth2/token", (0, querystring_1.stringify)({
47+ client_id: process.env.DISCORD_CLIENT_ID,
48+ client_secret: process.env.DISCORD_CLIENT_SECRET,
49+ grant_type: "authorization_code",
50+ code: code,
51+ redirect_uri: process.env.DISCORD_REDIRECT_URL,
52+ }), {
53+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
54+ });
55+ const discordToken = yield ctx.prisma.discordToken.create({
56+ data: {
57+ accessToken: response.data.access_token,
58+ expiresIn: response.data.expires_in,
59+ refreshToken: response.data.refresh_token,
60+ scope: response.data.scope,
61+ tokenType: response.data.token_type,
62+ },
63+ });
64+ yield ctx.prisma.user.update({
65+ where: { id: state },
66+ data: { discordTokenId: discordToken.id },
67+ });
68+ ctx.status = 201;
69+ }
70+ ctx.redirect(process.env.CLIENT_URL || "");
71+ yield next();
72+}));
73+router.post("/join", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
74+ if (!ctx.session) {
75+ ctx.status = 403;
76+ return yield next();
3977 }
40- else {
41- // error?
78+ // Use the token acquired to join the server
79+ const accessToken = ctx.session.user.discordToken.accessToken;
80+ const discordUserResponse = yield axios_1.default.get("https://discord.com/api/v10/users/@me", {
81+ headers: {
82+ Authorization: `Bearer ${ctx.session.user.discordToken.accessToken}`,
83+ "Content-Type": "application/x-www-form-urlencoded",
84+ },
85+ });
86+ const discordGuildAddResponse = yield axios_1.default.put(`https://discord.com/api/v10/guilds/${process.env.QUEST_GUILD_ID}/members/${discordUserResponse === null || discordUserResponse === void 0 ? void 0 : discordUserResponse.data.id}`, {
87+ access_token: accessToken,
88+ }, {
89+ headers: {
90+ Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
91+ "Content-Type": "application/json",
92+ },
93+ });
94+ if ((discordGuildAddResponse === null || discordGuildAddResponse === void 0 ? void 0 : discordGuildAddResponse.status) === 201) {
95+ // user added successfully
96+ console.log("added");
97+ }
98+ else if ((discordGuildAddResponse === null || discordGuildAddResponse === void 0 ? void 0 : discordGuildAddResponse.status) === 204) {
99+ // user already in guild
100+ console.log("existing");
42101 }
102+ ctx.status = 200;
43103 yield next();
44104 }));
45105 router.get("/verify", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
106+ if (!ctx.session) {
107+ ctx.status = 403;
108+ return yield next();
109+ }
46110 // use the discord api to see the list of members and check if user is in the list
47111 // Needs to use the token generated in the callback route
112+ const guildId = process.env.QUEST_GUILD_ID;
113+ // Use the token acquired to get the user and it's joined guilds
114+ const authorizationHeader = {
115+ Authorization: `Bearer ${ctx.session.user.discordToken.accessToken}`,
116+ "Content-Type": "application/x-www-form-urlencoded",
117+ };
118+ const discordUserResponse = yield axios_1.default.get(`https://discord.com/api/v10/users/@me/guilds/${guildId}/member`, {
119+ headers: authorizationHeader,
120+ });
121+ ctx.body = discordUserResponse.data;
122+ ctx.status = 200;
123+ yield next();
48124 }));
49125 exports.default = router;
api/package-lock.json+72−0
@@ -12,6 +12,7 @@
1212 "@koa/cors": "^4.0.0",
1313 "@prisma/client": "^4.8.1",
1414 "@types/koa-session": "^5.10.6",
15+ "axios": "^1.2.2",
1516 "dotenv": "^16.0.3",
1617 "koa": "2.14.1",
1718 "koa-bodyparser": "4.3.0",
@@ -312,6 +313,21 @@
312313 "node": ">= 8"
313314 }
314315 },
316+ "node_modules/asynckit": {
317+ "version": "0.4.0",
318+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
319+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
320+ },
321+ "node_modules/axios": {
322+ "version": "1.2.2",
323+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.2.2.tgz",
324+ "integrity": "sha512-bz/J4gS2S3I7mpN/YZfGFTqhXTYzRho8Ay38w2otuuDR322KzFIWm/4W2K6gIwvWaws5n+mnb7D1lN9uD+QH6Q==",
325+ "dependencies": {
326+ "follow-redirects": "^1.15.0",
327+ "form-data": "^4.0.0",
328+ "proxy-from-env": "^1.1.0"
329+ }
330+ },
315331 "node_modules/balanced-match": {
316332 "version": "1.0.2",
317333 "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -496,6 +512,17 @@
496512 "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
497513 "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw=="
498514 },
515+ "node_modules/combined-stream": {
516+ "version": "1.0.8",
517+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
518+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
519+ "dependencies": {
520+ "delayed-stream": "~1.0.0"
521+ },
522+ "engines": {
523+ "node": ">= 0.8"
524+ }
525+ },
499526 "node_modules/concat-map": {
500527 "version": "0.0.1",
501528 "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -572,6 +599,14 @@
572599 "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz",
573600 "integrity": "sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw=="
574601 },
602+ "node_modules/delayed-stream": {
603+ "version": "1.0.0",
604+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
605+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
606+ "engines": {
607+ "node": ">=0.4.0"
608+ }
609+ },
575610 "node_modules/delegates": {
576611 "version": "1.0.0",
577612 "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
@@ -640,6 +675,38 @@
640675 "node": ">=8"
641676 }
642677 },
678+ "node_modules/follow-redirects": {
679+ "version": "1.15.2",
680+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",
681+ "integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==",
682+ "funding": [
683+ {
684+ "type": "individual",
685+ "url": "https://github.com/sponsors/RubenVerborgh"
686+ }
687+ ],
688+ "engines": {
689+ "node": ">=4.0"
690+ },
691+ "peerDependenciesMeta": {
692+ "debug": {
693+ "optional": true
694+ }
695+ }
696+ },
697+ "node_modules/form-data": {
698+ "version": "4.0.0",
699+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
700+ "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
701+ "dependencies": {
702+ "asynckit": "^0.4.0",
703+ "combined-stream": "^1.0.8",
704+ "mime-types": "^2.1.12"
705+ },
706+ "engines": {
707+ "node": ">= 6"
708+ }
709+ },
643710 "node_modules/fresh": {
644711 "version": "0.5.2",
645712 "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
@@ -1260,6 +1327,11 @@
12601327 "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
12611328 "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
12621329 },
1330+ "node_modules/proxy-from-env": {
1331+ "version": "1.1.0",
1332+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
1333+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
1334+ },
12631335 "node_modules/pstree.remy": {
12641336 "version": "1.1.8",
12651337 "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
api/package.json+1−0
@@ -26,6 +26,7 @@
2626 "@koa/cors": "^4.0.0",
2727 "@prisma/client": "^4.8.1",
2828 "@types/koa-session": "^5.10.6",
29+ "axios": "^1.2.2",
2930 "dotenv": "^16.0.3",
3031 "koa": "2.14.1",
3132 "koa-bodyparser": "4.3.0",
api/prisma/migrations/20230115165336_add_discord_token_table/migration.sql+24−0
@@ -0,0 +1,24 @@
1+-- CreateTable
2+CREATE TABLE "DiscordToken" (
3+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
4+ "access_token" TEXT NOT NULL,
5+ "expires_in" INTEGER NOT NULL,
6+ "refresh_toke" TEXT NOT NULL,
7+ "scope" TEXT NOT NULL,
8+ "token_type" TEXT NOT NULL
9+);
10+
11+-- RedefineTables
12+PRAGMA foreign_keys=OFF;
13+CREATE TABLE "new_User" (
14+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
15+ "wallet_address" TEXT,
16+ "discordTokenId" INTEGER,
17+ CONSTRAINT "User_discordTokenId_fkey" FOREIGN KEY ("discordTokenId") REFERENCES "DiscordToken" ("id") ON DELETE SET NULL ON UPDATE CASCADE
18+);
19+INSERT INTO "new_User" ("id", "wallet_address") SELECT "id", "wallet_address" FROM "User";
20+DROP TABLE "User";
21+ALTER TABLE "new_User" RENAME TO "User";
22+CREATE UNIQUE INDEX "User_wallet_address_key" ON "User"("wallet_address");
23+PRAGMA foreign_key_check;
24+PRAGMA foreign_keys=ON;
api/prisma/migrations/20230115171256_fix_type_in_discord_table/migration.sql+22−0
@@ -0,0 +1,22 @@
1+/*
2+ Warnings:
3+
4+ - You are about to drop the column `refresh_toke` on the `DiscordToken` table. All the data in the column will be lost.
5+ - Added the required column `refresh_token` to the `DiscordToken` table without a default value. This is not possible if the table is not empty.
6+
7+*/
8+-- RedefineTables
9+PRAGMA foreign_keys=OFF;
10+CREATE TABLE "new_DiscordToken" (
11+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
12+ "access_token" TEXT NOT NULL,
13+ "expires_in" INTEGER NOT NULL,
14+ "refresh_token" TEXT NOT NULL,
15+ "scope" TEXT NOT NULL,
16+ "token_type" TEXT NOT NULL
17+);
18+INSERT INTO "new_DiscordToken" ("access_token", "expires_in", "id", "scope", "token_type") SELECT "access_token", "expires_in", "id", "scope", "token_type" FROM "DiscordToken";
19+DROP TABLE "DiscordToken";
20+ALTER TABLE "new_DiscordToken" RENAME TO "DiscordToken";
21+PRAGMA foreign_key_check;
22+PRAGMA foreign_keys=ON;
api/prisma/migrations/20230115183143_standardize_casing/migration.sql+39−0
@@ -0,0 +1,39 @@
1+/*
2+ Warnings:
3+
4+ - You are about to drop the column `access_token` on the `DiscordToken` table. All the data in the column will be lost.
5+ - You are about to drop the column `expires_in` on the `DiscordToken` table. All the data in the column will be lost.
6+ - You are about to drop the column `refresh_token` on the `DiscordToken` table. All the data in the column will be lost.
7+ - You are about to drop the column `token_type` on the `DiscordToken` table. All the data in the column will be lost.
8+ - You are about to drop the column `wallet_address` on the `User` table. All the data in the column will be lost.
9+ - Added the required column `accessToken` to the `DiscordToken` table without a default value. This is not possible if the table is not empty.
10+ - Added the required column `expiresIn` to the `DiscordToken` table without a default value. This is not possible if the table is not empty.
11+ - Added the required column `refreshToken` to the `DiscordToken` table without a default value. This is not possible if the table is not empty.
12+ - Added the required column `tokenType` to the `DiscordToken` table without a default value. This is not possible if the table is not empty.
13+
14+*/
15+-- RedefineTables
16+PRAGMA foreign_keys=OFF;
17+CREATE TABLE "new_DiscordToken" (
18+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
19+ "accessToken" TEXT NOT NULL,
20+ "expiresIn" INTEGER NOT NULL,
21+ "refreshToken" TEXT NOT NULL,
22+ "scope" TEXT NOT NULL,
23+ "tokenType" TEXT NOT NULL
24+);
25+INSERT INTO "new_DiscordToken" ("id", "scope") SELECT "id", "scope" FROM "DiscordToken";
26+DROP TABLE "DiscordToken";
27+ALTER TABLE "new_DiscordToken" RENAME TO "DiscordToken";
28+CREATE TABLE "new_User" (
29+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
30+ "walletAddress" TEXT,
31+ "discordTokenId" INTEGER,
32+ CONSTRAINT "User_discordTokenId_fkey" FOREIGN KEY ("discordTokenId") REFERENCES "DiscordToken" ("id") ON DELETE SET NULL ON UPDATE CASCADE
33+);
34+INSERT INTO "new_User" ("discordTokenId", "id") SELECT "discordTokenId", "id" FROM "User";
35+DROP TABLE "User";
36+ALTER TABLE "new_User" RENAME TO "User";
37+CREATE UNIQUE INDEX "User_walletAddress_key" ON "User"("walletAddress");
38+PRAGMA foreign_key_check;
39+PRAGMA foreign_keys=ON;
api/prisma/schema.prisma+14−2
@@ -12,6 +12,18 @@ datasource db {
1212
1313 // @TODO: Define the user model once the login is setup so we know what to store.
1414 model User {
15- id Int @id @default(autoincrement())
16- wallet_address String? @unique
15+ id Int @id @default(autoincrement())
16+ walletAddress String? @unique
17+ discordToken DiscordToken? @relation(fields: [discordTokenId], references: [id])
18+ discordTokenId Int?
19+}
20+
21+model DiscordToken {
22+ id Int @id @default(autoincrement())
23+ accessToken String
24+ expiresIn Int
25+ refreshToken String
26+ scope String
27+ tokenType String
28+ user User[]
1729 }
api/src/authentication/index.ts+8−3
@@ -11,13 +11,14 @@ router.post(
1111
1212 // Check for an existing user:
1313 user = await ctx.prisma.user.findUnique({
14- where: { wallet_address: data.wallet_address },
14+ where: { walletAddress: data.walletAddress },
15+ include: { discordToken: true },
1516 });
1617
1718 // New user:
1819 if (!user) {
1920 user = await ctx.prisma.user.create({
20- data: { wallet_address: data.wallet_address },
21+ data: { walletAddress: data.walletAddress },
2122 });
2223 ctx.status = 201;
2324 } else {
@@ -45,7 +46,11 @@ router.get(
4546 "/authenticated_user",
4647 async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
4748 if (ctx.session?.user) {
48- ctx.body = ctx.session.user;
49+ ctx.body = ctx.session.user = await ctx.prisma.user.findUnique({
50+ include: { discordToken: true },
51+ where: { walletAddress: ctx.session.user.walletAddress },
52+ });
53+
4954 ctx.status = 200;
5055 }
5156
api/src/discord/index.ts+124−22
@@ -1,49 +1,151 @@
11 import Router from "koa-router";
22 import Koa from "koa";
3+import axios from "axios";
4+import { stringify } from "querystring";
35
46 const router = new Router({ prefix: "/discord" });
57
6-// TODO: Consider using something `disco-oauth2`
8+router.get(
9+ "/authorize",
10+ async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
11+ if (!ctx.session) {
12+ ctx.status = 403;
13+ return await next();
14+ }
715
8-router.get("/join", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
9- // Front end will send the user here, and then from here into the authorization flow:
10- //https://discord.com/api/oauth2/authorize?client_id=1064167640148476004&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fdiscord%2Fcallback&response_type=code&scope=guilds.join%20guilds.members.read
11- // TODO: Add `state` url param for extra security
12- const authorize_url =
13- "https://discord.com/api/oauth2/authorize" +
14- `?client_id=${process.env.DISCORD_CLIENT_ID}` +
15- `&redirect_uri=${encodeURI(process.env.DISCORD_REDIRECT_URL || "")}` +
16- `&response_type=code` +
17- `&scope=guilds.join guilds.members.read`;
16+ // Front end will send the user here, and then from here into the authorization flow:
17+ // https://discord.com/api/oauth2/authorize?
18+ // client_id=1064167640148476004&
19+ // redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fdiscord%2Fcallback&
20+ // response_type=code&
21+ // scope=guilds.join%20guilds.members.read
1822
19- ctx.redirect(authorize_url);
23+ const authorize_url =
24+ "https://discord.com/api/oauth2/authorize" +
25+ `?client_id=${process.env.DISCORD_CLIENT_ID}` +
26+ `&redirect_uri=${encodeURI(process.env.DISCORD_REDIRECT_URL || "")}` +
27+ `&response_type=code` +
28+ `&scope=identify guilds guilds.join guilds.members.read` +
29+ `&state=${ctx.session?.user.id}`;
30+ ctx.redirect(authorize_url);
2031
21- await next();
22-});
32+ await next();
33+ }
34+);
2335
2436 router.get(
2537 "/callback",
2638 async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
27- // OAuth callback
28- // TODO: use the token to get the user ID and join the server.
29- // https://discordapp.com/api/guilds/${SERVER_ID}/members/${userID}
30-
31- const code = ctx.request.query?.code;
39+ const code = ctx.request.query.code;
40+ const state = Number(ctx.request.query.state);
3241
3342 if (code) {
3443 // Success, we should exchange the code for a token:
3544 // https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-exchange-example
36- } else {
37- // error?
38- }
45+ const response = await axios.post(
46+ "https://discord.com/api/v10/oauth2/token",
47+ stringify({
48+ client_id: process.env.DISCORD_CLIENT_ID,
49+ client_secret: process.env.DISCORD_CLIENT_SECRET,
50+ grant_type: "authorization_code",
51+ code: code,
52+ redirect_uri: process.env.DISCORD_REDIRECT_URL,
53+ }),
54+ {
55+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
56+ }
57+ );
58+
59+ const discordToken = await ctx.prisma.discordToken.create({
60+ data: {
61+ accessToken: response.data.access_token,
62+ expiresIn: response.data.expires_in,
63+ refreshToken: response.data.refresh_token,
64+ scope: response.data.scope,
65+ tokenType: response.data.token_type,
66+ },
67+ });
68+
69+ await ctx.prisma.user.update({
70+ where: { id: state },
71+ data: { discordTokenId: discordToken.id },
72+ });
3973
74+ ctx.status = 201;
75+ }
76+ ctx.redirect(process.env.CLIENT_URL || "");
4077 await next();
4178 }
4279 );
4380
81+router.post("/join", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
82+ if (!ctx.session) {
83+ ctx.status = 403;
84+ return await next();
85+ }
86+
87+ // Use the token acquired to join the server
88+ const accessToken = ctx.session.user.discordToken.accessToken;
89+ const discordUserResponse = await axios.get(
90+ "https://discord.com/api/v10/users/@me",
91+ {
92+ headers: {
93+ Authorization: `Bearer ${ctx.session.user.discordToken.accessToken}`,
94+ "Content-Type": "application/x-www-form-urlencoded",
95+ },
96+ }
97+ );
98+ const discordGuildAddResponse = await axios.put(
99+ `https://discord.com/api/v10/guilds/${process.env.QUEST_GUILD_ID}/members/${discordUserResponse?.data.id}`,
100+ {
101+ access_token: accessToken,
102+ },
103+ {
104+ headers: {
105+ Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
106+ "Content-Type": "application/json",
107+ },
108+ }
109+ );
110+
111+ if (discordGuildAddResponse?.status === 201) {
112+ // user added successfully
113+ console.log("added");
114+ } else if (discordGuildAddResponse?.status === 204) {
115+ // user already in guild
116+ console.log("existing");
117+ }
118+
119+ ctx.status = 200;
120+
121+ await next();
122+});
123+
44124 router.get("/verify", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
125+ if (!ctx.session) {
126+ ctx.status = 403;
127+ return await next();
128+ }
129+
45130 // use the discord api to see the list of members and check if user is in the list
46131 // Needs to use the token generated in the callback route
132+ const guildId = process.env.QUEST_GUILD_ID;
133+
134+ // Use the token acquired to get the user and it's joined guilds
135+ const authorizationHeader = {
136+ Authorization: `Bearer ${ctx.session.user.discordToken.accessToken}`,
137+ "Content-Type": "application/x-www-form-urlencoded",
138+ };
139+ const discordUserResponse = await axios.get(
140+ `https://discord.com/api/v10/users/@me/guilds/${guildId}/member`,
141+ {
142+ headers: authorizationHeader,
143+ }
144+ );
145+
146+ ctx.body = discordUserResponse.data;
147+ ctx.status = 200;
148+ await next();
47149 });
48150
49151 export default router;
ui/src/components/AuthenticationForm/index.tsx+21−32
@@ -1,24 +1,24 @@
1-import React, { useState, useContext } from "react";
21 import axios from "axios";
3-import styled from "styled-components";
2+import React, { useContext, useState } from "react";
43 import { useNavigate } from "react-router-dom";
4+import { StyledButton } from "../../theme/button";
5+import { UserType } from "../../types";
56 import { PageContext } from "../Page";
67
7-export async function AuthenticationLoader() {
8- let user = null;
9- await axios
10- .get("/authenticated_user")
11- .then((response) => {
12- user = response.data;
13- })
14- .catch((e) => {
15- if (e?.response?.status !== 404) {
16- // TODO: handle network error
17- console.log(e);
18- }
19- });
20-
21- return user;
8+export async function AuthenticationLoader(): Promise<UserType> {
9+ return (
10+ (await axios
11+ .get("/authenticated_user")
12+ .then((response) => {
13+ return response.data;
14+ })
15+ .catch((e) => {
16+ if (e.response.status !== 404) {
17+ console.log(e);
18+ throw e;
19+ }
20+ })) || null
21+ );
2222 }
2323
2424 export function AuthenticationForm() {
@@ -31,23 +31,21 @@ export function AuthenticationForm() {
3131 e.preventDefault();
3232 setIsLoading(true);
3333
34- // TODO: How to extend the window's type
35- // Write a hook that defines the return type?
34+ // tried to use @metamask/detect-providers but currently has an issue where the type
35+ // we need here is not exported.
36+ // TODO: Link to issue
3637 const provider = (window as any)?.ethereum;
3738 if (provider) {
3839 const accounts = await provider.request({
3940 method: "eth_requestAccounts",
4041 });
4142
42- // TODO: Handle many accounts
43- console.log(accounts);
4443 await axios
45- .post("/authenticate", { wallet_address: accounts[0] })
44+ .post("/authenticate", { walletAddress: accounts[0] })
4645 .then(() => {
4746 navigate("/");
4847 })
4948 .catch((error) => {
50- // TODO: Handle network error
5149 console.log(error);
5250 });
5351 } else {
@@ -65,7 +63,6 @@ export function AuthenticationForm() {
6563 navigate("/sign-in");
6664 })
6765 .catch((error) => {
68- // TODO: Handle network error
6966 console.log(error);
7067 });
7168
@@ -90,11 +87,3 @@ export function AuthenticationForm() {
9087 </div>
9188 );
9289 }
93-
94-const StyledButton = styled.button`
95- padding: 0.5em 1em;
96- background: ${(props) => props.theme.colors.background};
97- color: ${(props) => props.theme.colors.foreground};
98- border: 2px solid ${(props) => props.theme.colors.highlight};
99- border-radius: 4px;
100-`;
ui/src/components/Header/index.tsx+7−13
@@ -3,20 +3,13 @@ import styled from "styled-components";
33
44 import { AuthenticationForm } from "../AuthenticationForm";
55
6-export default function Header({ children }: { children?: React.ReactNode }) {
6+export default function Header() {
77 return (
88 <StyledHeader>
9- {children ? (
10- children
11- ) : (
12- <>
13- <h1>Sesame Labs Coding Assignment</h1>
14- <div>{/* TODO: navigation links go here */}</div>
15- <div>
16- <AuthenticationForm />
17- </div>
18- </>
19- )}
9+ <h1>Sesame Labs Coding Assignment</h1>
10+ <div>
11+ <AuthenticationForm />
12+ </div>
2013 </StyledHeader>
2114 );
2215 }
@@ -25,7 +18,8 @@ const StyledHeader = styled.div`
2518 width: 100%;
2619 height: 60px;
2720 display: grid;
28- grid-template-columns: 600px 1fr 200px;
21+ grid-template-columns: 1fr 200px;
22+ column-gap: auto;
2923
3024 > * {
3125 padding: 0.5em 1em;
ui/src/components/JoinDiscordServer/index.tsx+57−0
@@ -0,0 +1,57 @@
1+import React, { useContext, useState } from "react";
2+import { StyledButton } from "../../theme/button";
3+import { StyledLink } from "../../theme/link";
4+import { PageContext } from "../Page";
5+import styled from "styled-components";
6+import axios from "axios";
7+
8+export default function JoinDiscordGuild() {
9+ const context = useContext(PageContext);
10+ const [isLoading, setIsLoading] = useState(false);
11+
12+ const handleJoinClick = async (e: React.MouseEvent) => {
13+ // Join via the api endpoint
14+ e.preventDefault();
15+ setIsLoading(true);
16+ await axios.post("/discord/join").catch((e) => {
17+ console.log(e);
18+ });
19+ setIsLoading(false);
20+ };
21+
22+ const handleVerifyClick = async (e: React.MouseEvent) => {
23+ // call the verify endpoint
24+ e.preventDefault();
25+ setIsLoading(true);
26+ const response = await axios.get("/discord/verify").catch((e) => {
27+ console.log(e);
28+ });
29+
30+ console.log(response);
31+
32+ setIsLoading(false);
33+ };
34+
35+ return isLoading ? (
36+ <p>Loading...</p>
37+ ) : (
38+ <p>
39+ {context?.user?.discordTokenId ? (
40+ <ActionsContainer>
41+ <StyledButton onClick={handleJoinClick}>Join</StyledButton>
42+ <StyledButton onClick={handleVerifyClick}>verify</StyledButton>
43+ </ActionsContainer>
44+ ) : (
45+ <StyledLink href="http://localhost:3001/discord/authorize">
46+ Connect with discord
47+ </StyledLink>
48+ )}
49+ </p>
50+ );
51+}
52+
53+const ActionsContainer = styled.div`
54+ display: grid;
55+ grid-template-columns: 1fr 1fr;
56+ column-gap: 40px;
57+`;
ui/src/components/Page/index.tsx+3−3
@@ -1,8 +1,8 @@
11 import React, { createContext, useEffect } from "react";
2+import { useLoaderData, useNavigate } from "react-router-dom";
23 import styled, { ThemeProvider } from "styled-components";
3-import { useNavigate, useLoaderData } from "react-router-dom";
44 import theme from "../../theme";
5-import { PageContextType } from "../../types";
5+import { PageContextType, UserType } from "../../types";
66
77 export const PageContext = createContext<PageContextType | null>(null);
88
@@ -16,7 +16,7 @@ export default function Page({
1616 children: React.ReactNode;
1717 }) {
1818 const navigate = useNavigate();
19- const user = useLoaderData();
19+ const user = useLoaderData() as UserType;
2020
2121 // Protect authenticated routes:
2222 useEffect(() => {
ui/src/index.tsx+2−4
@@ -9,6 +9,7 @@ import {
99 } from "./components/AuthenticationForm";
1010 import axios from "axios";
1111 import Header from "./components/Header";
12+import JoinDiscordGuild from "./components/JoinDiscordServer";
1213
1314 axios.defaults.baseURL = "http://localhost:3001/";
1415 axios.defaults.headers["Content-Type"] = "application/json";
@@ -21,10 +22,7 @@ const router = createBrowserRouter([
2122 <Page requiresAuthentication={true} redirectTarget="/sign-in">
2223 <>
2324 <Header />
24- <p>
25- Click this link to join discord server:{" "}
26- <a href="http://localhost:3001/discord/join">Authorize</a>
27- </p>
25+ <JoinDiscordGuild />
2826 </>
2927 </Page>
3028 ),
ui/src/theme/button.tsx+15−0
@@ -0,0 +1,15 @@
1+import styled from "styled-components";
2+
3+export const StyledButton = styled.button`
4+ min-width: 100px;
5+ padding: 0.5em 1em;
6+ background: ${(props) => props.theme.colors.background};
7+ color: ${(props) => props.theme.colors.foreground};
8+ border: 2px solid ${(props) => props.theme.colors.highlight};
9+ border-radius: 4px;
10+
11+ &:hover {
12+ border-color: ${(props) => props.theme.colors.altHighlight};
13+ cursor: pointer;
14+ }
15+`;
ui/src/theme/index.ts+2−1
@@ -1,10 +1,11 @@
1-import { ThemeType } from "./types";
1+import { ThemeType } from "../types";
22
33 const theme: ThemeType = {
44 colors: {
55 background: "#02020a",
66 foreground: "#e1e2ef",
77 highlight: "#3066be",
8+ altHighlight: "#3d87ff",
89 },
910 };
1011
ui/src/theme/link.tsx+14−0
@@ -0,0 +1,14 @@
1+import styled from "styled-components";
2+
3+export const StyledLink = styled.a`
4+ &,
5+ &:visited,
6+ &:active {
7+ color: ${(props) => props.theme.colors.highlight};
8+ text-decoration: none;
9+ }
10+
11+ &:hover {
12+ color: ${(props) => props.theme.colors.altHighlight};
13+ }
14+`;
ui/src/types.ts+9−3
@@ -1,12 +1,18 @@
11 export interface UserType {
22 id?: number;
3- wallet_address: string;
3+ walletAddress: string;
4+ discordTokenId?: number;
45 }
56
67 export interface PageContextType {
7- user: UserType | unknown;
8+ user: UserType | null;
89 }
910
1011 export interface ThemeType {
11- colors: { background: string; foreground: string; highlight: string };
12+ colors: {
13+ background: string;
14+ foreground: string;
15+ highlight: string;
16+ altHighlight: string;
17+ };
1218 }