xonecas.io
4436
Sl

sesame-labs-coding-assignment / commit 0d22a96

Refactor discord flow

- Remove react router since we don't need to over complicate
- Style the UI to the minimum acceptable
- Add error messaging

Sean2023-01-16 0d22a965d229771010742cc3310afe5aeae61ca8 parent 53553ea

31 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

api/.env.sample+1−0
@@ -14,6 +14,7 @@ DISCORD_BOT_TOKEN=00000000000000000000000000000000000000000000000000000000000000
1414 # In Discord terms guild is a server
1515 QUEST_TITLE='Join Seans server'
1616 QUEST_DESCRIPTION='Come game with Sean'
17+QUEST_CHANNEL_ID=0000000000000000000000
1718 QUEST_COVER_IMG='http://localhost:3000/public/quest-image.png'
1819 QUEST_GUILD_ID=000000000000000000
1920 QUEST_GUILD_NAME='Seans server'
api/dist/Quest/index.js+1−0
@@ -0,0 +1 @@
1+"use strict";
api/dist/authentication/index.js+1−0
@@ -35,6 +35,7 @@ router.post("/authenticate", (ctx, next) => __awaiter(void 0, void 0, void 0, fu
3535 if (ctx.session) {
3636 ctx.session.user = user;
3737 }
38+ ctx.body = user;
3839 yield next();
3940 }));
4041 router.post("/deauthenticate", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
api/dist/discord/index.js+47−49
@@ -16,34 +16,12 @@ const koa_router_1 = __importDefault(require("koa-router"));
1616 const axios_1 = __importDefault(require("axios"));
1717 const querystring_1 = require("querystring");
1818 const router = new koa_router_1.default({ prefix: "/discord" });
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- }
25- // Front end will send the user here, and then from here into the authorization flow:
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
31- const authorize_url = "https://discord.com/api/oauth2/authorize" +
32- `?client_id=${process.env.DISCORD_CLIENT_ID}` +
33- `&redirect_uri=${encodeURI(process.env.DISCORD_REDIRECT_URL || "")}` +
34- `&response_type=code` +
35- `&scope=identify guilds guilds.join guilds.members.read` +
36- `&state=${(_a = ctx.session) === null || _a === void 0 ? void 0 : _a.user.id}`;
37- ctx.redirect(authorize_url);
38- yield next();
39-}));
4019 router.get("/callback", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
4120 const code = ctx.request.query.code;
4221 const state = Number(ctx.request.query.state);
4322 if (code) {
44- // Success, we should exchange the code for a token:
45- // 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)({
23+ const response = yield axios_1.default
24+ .post("https://discord.com/api/v10/oauth2/token", (0, querystring_1.stringify)({
4725 client_id: process.env.DISCORD_CLIENT_ID,
4826 client_secret: process.env.DISCORD_CLIENT_SECRET,
4927 grant_type: "authorization_code",
@@ -51,6 +29,10 @@ router.get("/callback", (ctx, next) => __awaiter(void 0, void 0, void 0, functio
5129 redirect_uri: process.env.DISCORD_REDIRECT_URL,
5230 }), {
5331 headers: { "Content-Type": "application/x-www-form-urlencoded" },
32+ })
33+ .catch((e) => {
34+ console.log(e);
35+ throw e;
5436 });
5537 const discordToken = yield ctx.prisma.discordToken.create({
5638 data: {
@@ -67,39 +49,42 @@ router.get("/callback", (ctx, next) => __awaiter(void 0, void 0, void 0, functio
6749 });
6850 ctx.status = 201;
6951 }
70- ctx.redirect(process.env.CLIENT_URL || "");
52+ ctx.redirect("/discord/join");
7153 yield next();
7254 }));
73-router.post("/join", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
55+router.get("/join", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
7456 if (!ctx.session) {
7557 ctx.status = 403;
7658 return yield next();
7759 }
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- },
60+ const user = yield ctx.prisma.user.findUnique({
61+ where: { walletAddress: ctx.session.user.walletAddress },
62+ include: { discordToken: true },
8563 });
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- }, {
64+ if (!user.discordToken) {
65+ const authorize_url = "https://discord.com/api/oauth2/authorize" +
66+ `?client_id=${process.env.DISCORD_CLIENT_ID}` +
67+ `&redirect_uri=${encodeURI(process.env.DISCORD_REDIRECT_URL || "")}` +
68+ `&response_type=code` +
69+ `&scope=identify bot guilds guilds.members.read` +
70+ `&state=${user.id}`;
71+ ctx.redirect(authorize_url);
72+ return yield next();
73+ }
74+ const inviteCode = yield axios_1.default
75+ .post(`https://discord.com/api/v10/channels/${process.env.QUEST_CHANNEL_ID}/invites`, {}, {
8976 headers: {
9077 Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
9178 "Content-Type": "application/json",
9279 },
80+ })
81+ .then((response) => response.data.code)
82+ .catch((e) => {
83+ console.log(e);
84+ throw e;
9385 });
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");
101- }
102- ctx.status = 200;
86+ ctx.session.user = user;
87+ ctx.redirect(`http://discord.gg/${inviteCode}`);
10388 yield next();
10489 }));
10590 router.get("/verify", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
@@ -107,18 +92,31 @@ router.get("/verify", (ctx, next) => __awaiter(void 0, void 0, void 0, function*
10792 ctx.status = 403;
10893 return yield next();
10994 }
110- // use the discord api to see the list of members and check if user is in the list
111- // Needs to use the token generated in the callback route
11295 const guildId = process.env.QUEST_GUILD_ID;
11396 // Use the token acquired to get the user and it's joined guilds
11497 const authorizationHeader = {
11598 Authorization: `Bearer ${ctx.session.user.discordToken.accessToken}`,
11699 "Content-Type": "application/x-www-form-urlencoded",
117100 };
118- const discordUserResponse = yield axios_1.default.get(`https://discord.com/api/v10/users/@me/guilds/${guildId}/member`, {
101+ yield axios_1.default
102+ .get(`https://discord.com/api/v10/users/@me/guilds/${guildId}/member`, {
119103 headers: authorizationHeader,
104+ })
105+ .catch((e) => {
106+ console.log(e);
107+ throw e;
108+ });
109+ // 10 random characters alphanumeric string
110+ const coupon = Math.random()
111+ .toString(36)
112+ .substring(2, 12)
113+ .toLocaleUpperCase();
114+ console.log(coupon);
115+ ctx.body = ctx.session.user = yield ctx.prisma.user.update({
116+ where: { walletAddress: ctx.session.user.walletAddress },
117+ include: { discordToken: true },
118+ data: { verified: true, coupon },
120119 });
121- ctx.body = discordUserResponse.data;
122120 ctx.status = 200;
123121 yield next();
124122 }));
api/dist/index.js+1−1
@@ -36,7 +36,7 @@ function main() {
3636 .use((0, koa_json_1.default)())
3737 .use((0, koa_bodyparser_1.default)())
3838 .use((0, cors_1.default)({ credentials: true }))
39- .use((0, koa_session_1.default)({ secure: false, signed: false, sameSite: "none" }, app))
39+ .use((0, koa_session_1.default)({ secure: false, signed: false, sameSite: "lax" }, app))
4040 .use(routes_1.default.routes())
4141 .use(routes_1.default.allowedMethods());
4242 // Start the server:
api/dist/quest/index.js+27−0
@@ -0,0 +1,27 @@
1+"use strict";
2+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4+ return new (P || (P = Promise))(function (resolve, reject) {
5+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9+ });
10+};
11+var __importDefault = (this && this.__importDefault) || function (mod) {
12+ return (mod && mod.__esModule) ? mod : { "default": mod };
13+};
14+Object.defineProperty(exports, "__esModule", { value: true });
15+const koa_router_1 = __importDefault(require("koa-router"));
16+const router = new koa_router_1.default();
17+router.get("/quest", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
18+ ctx.body = {
19+ title: process.env.QUEST_TITLE,
20+ description: process.env.QUEST_DESCRIPTION,
21+ guildName: process.env.QUEST_GUILD_NAME,
22+ coverImage: process.env.QUEST_COVER_IMAGE,
23+ };
24+ ctx.status = 200;
25+ yield next();
26+}));
27+exports.default = router;
api/dist/routes.js+4−1
@@ -15,6 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
1515 const koa_router_1 = __importDefault(require("koa-router"));
1616 const authentication_1 = __importDefault(require("./authentication"));
1717 const discord_1 = __importDefault(require("./discord"));
18+const quest_1 = __importDefault(require("./quest"));
1819 const router = new koa_router_1.default();
1920 router.all("/health-check", (ctx, next) => __awaiter(void 0, void 0, void 0, function* () {
2021 // Check if server is healthy and has connection to db:
@@ -26,5 +27,7 @@ router
2627 .use(authentication_1.default.routes())
2728 .use(authentication_1.default.allowedMethods())
2829 .use(discord_1.default.routes())
29- .use(discord_1.default.allowedMethods());
30+ .use(discord_1.default.allowedMethods())
31+ .use(quest_1.default.routes())
32+ .use(quest_1.default.allowedMethods());
3033 exports.default = router;
api/prisma/dev.db+0−0
Binary file, not shown.
api/prisma/migrations/20230112165654_init/migration.sql+0−5
@@ -1,5 +0,0 @@
1--- CreateTable
2-CREATE TABLE "User" (
3- "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
4- "name" TEXT
5-);
api/prisma/migrations/20230113131737_add_wallet_address_field/migration.sql+0−2
@@ -1,2 +0,0 @@
1--- AlterTable
2-ALTER TABLE "User" ADD COLUMN "wallet_address" TEXT;
api/prisma/migrations/20230113181803_unique_wallet_address/migration.sql+0−8
@@ -1,8 +0,0 @@
1-/*
2- Warnings:
3-
4- - A unique constraint covering the columns `[wallet_address]` on the table `User` will be added. If there are existing duplicate values, this will fail.
5-
6-*/
7--- CreateIndex
8-CREATE UNIQUE INDEX "User_wallet_address_key" ON "User"("wallet_address");
api/prisma/migrations/20230113193546_remove_name_field/migration.sql+0−18
@@ -1,18 +0,0 @@
1-/*
2- Warnings:
3-
4- - You are about to drop the column `name` on the `User` table. All the data in the column will be lost.
5-
6-*/
7--- RedefineTables
8-PRAGMA foreign_keys=OFF;
9-CREATE TABLE "new_User" (
10- "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
11- "wallet_address" TEXT
12-);
13-INSERT INTO "new_User" ("id", "wallet_address") SELECT "id", "wallet_address" FROM "User";
14-DROP TABLE "User";
15-ALTER TABLE "new_User" RENAME TO "User";
16-CREATE UNIQUE INDEX "User_wallet_address_key" ON "User"("wallet_address");
17-PRAGMA foreign_key_check;
18-PRAGMA foreign_keys=ON;
api/prisma/migrations/20230115165336_add_discord_token_table/migration.sql+0−24
@@ -1,24 +0,0 @@
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+0−22
@@ -1,22 +0,0 @@
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+0−39
@@ -1,39 +0,0 @@
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/migrations/20230116011331_init/migration.sql+22−0
@@ -0,0 +1,22 @@
1+-- CreateTable
2+CREATE TABLE "User" (
3+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
4+ "walletAddress" TEXT,
5+ "discordTokenId" INTEGER,
6+ "verified" BOOLEAN NOT NULL DEFAULT false,
7+ "coupon" TEXT,
8+ CONSTRAINT "User_discordTokenId_fkey" FOREIGN KEY ("discordTokenId") REFERENCES "DiscordToken" ("id") ON DELETE SET NULL ON UPDATE CASCADE
9+);
10+
11+-- CreateTable
12+CREATE TABLE "DiscordToken" (
13+ "id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
14+ "accessToken" TEXT NOT NULL,
15+ "expiresIn" INTEGER NOT NULL,
16+ "refreshToken" TEXT NOT NULL,
17+ "scope" TEXT NOT NULL,
18+ "tokenType" TEXT NOT NULL
19+);
20+
21+-- CreateIndex
22+CREATE UNIQUE INDEX "User_walletAddress_key" ON "User"("walletAddress");
api/prisma/schema.prisma+2−1
@@ -10,12 +10,13 @@ datasource db {
1010 url = env("DATABASE_URL")
1111 }
1212
13-// @TODO: Define the user model once the login is setup so we know what to store.
1413 model User {
1514 id Int @id @default(autoincrement())
1615 walletAddress String? @unique
1716 discordToken DiscordToken? @relation(fields: [discordTokenId], references: [id])
1817 discordTokenId Int?
18+ verified Boolean @default(false)
19+ coupon String?
1920 }
2021
2122 model DiscordToken {
api/src/authentication/index.ts+1−0
@@ -28,6 +28,7 @@ router.post(
2828 if (ctx.session) {
2929 ctx.session.user = user;
3030 }
31+ ctx.body = user;
3132
3233 await next();
3334 }
api/src/discord/index.ts+77−86
@@ -5,34 +5,6 @@ import { stringify } from "querystring";
55
66 const router = new Router({ prefix: "/discord" });
77
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- }
15-
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
22-
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);
31-
32- await next();
33- }
34-);
35-
368 router.get(
379 "/callback",
3810 async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
@@ -40,21 +12,24 @@ router.get(
4012 const state = Number(ctx.request.query.state);
4113
4214 if (code) {
43- // Success, we should exchange the code for a token:
44- // https://discord.com/developers/docs/topics/oauth2#authorization-code-grant-access-token-exchange-example
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- );
15+ const response = await axios
16+ .post(
17+ "https://discord.com/api/v10/oauth2/token",
18+ stringify({
19+ client_id: process.env.DISCORD_CLIENT_ID,
20+ client_secret: process.env.DISCORD_CLIENT_SECRET,
21+ grant_type: "authorization_code",
22+ code: code,
23+ redirect_uri: process.env.DISCORD_REDIRECT_URL,
24+ }),
25+ {
26+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
27+ }
28+ )
29+ .catch((e) => {
30+ console.log(e);
31+ throw e;
32+ });
5833
5934 const discordToken = await ctx.prisma.discordToken.create({
6035 data: {
@@ -73,50 +48,54 @@ router.get(
7348
7449 ctx.status = 201;
7550 }
76- ctx.redirect(process.env.CLIENT_URL || "");
51+ ctx.redirect("/discord/join");
7752 await next();
7853 }
7954 );
8055
81-router.post("/join", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
56+router.get("/join", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
8257 if (!ctx.session) {
8358 ctx.status = 403;
8459 return await next();
8560 }
8661
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");
62+ const user = await ctx.prisma.user.findUnique({
63+ where: { walletAddress: ctx.session.user.walletAddress },
64+ include: { discordToken: true },
65+ });
66+
67+ if (!user.discordToken) {
68+ const authorize_url =
69+ "https://discord.com/api/oauth2/authorize" +
70+ `?client_id=${process.env.DISCORD_CLIENT_ID}` +
71+ `&redirect_uri=${encodeURI(process.env.DISCORD_REDIRECT_URL || "")}` +
72+ `&response_type=code` +
73+ `&scope=identify bot guilds guilds.members.read` +
74+ `&state=${user.id}`;
75+
76+ ctx.redirect(authorize_url);
77+ return await next();
11778 }
11879
119- ctx.status = 200;
80+ const inviteCode = await axios
81+ .post(
82+ `https://discord.com/api/v10/channels/${process.env.QUEST_CHANNEL_ID}/invites`,
83+ {},
84+ {
85+ headers: {
86+ Authorization: `Bot ${process.env.DISCORD_BOT_TOKEN}`,
87+ "Content-Type": "application/json",
88+ },
89+ }
90+ )
91+ .then((response) => response.data.code)
92+ .catch((e) => {
93+ console.log(e);
94+ throw e;
95+ });
96+
97+ ctx.session.user = user;
98+ ctx.redirect(`http://discord.gg/${inviteCode}`);
12099
121100 await next();
122101 });
@@ -127,24 +106,36 @@ router.get("/verify", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
127106 return await next();
128107 }
129108
130- // use the discord api to see the list of members and check if user is in the list
131- // Needs to use the token generated in the callback route
132109 const guildId = process.env.QUEST_GUILD_ID;
133-
134110 // Use the token acquired to get the user and it's joined guilds
135111 const authorizationHeader = {
136112 Authorization: `Bearer ${ctx.session.user.discordToken.accessToken}`,
137113 "Content-Type": "application/x-www-form-urlencoded",
138114 };
139- const discordUserResponse = await axios.get(
140- `https://discord.com/api/v10/users/@me/guilds/${guildId}/member`,
141- {
115+ await axios
116+ .get(`https://discord.com/api/v10/users/@me/guilds/${guildId}/member`, {
142117 headers: authorizationHeader,
143- }
144- );
145-
146- ctx.body = discordUserResponse.data;
118+ })
119+ .catch((e) => {
120+ console.log(e);
121+ throw e;
122+ });
123+
124+ // 10 random characters alphanumeric string
125+ const coupon = Math.random()
126+ .toString(36)
127+ .substring(2, 12)
128+ .toLocaleUpperCase();
129+
130+ console.log(coupon);
131+
132+ ctx.body = ctx.session.user = await ctx.prisma.user.update({
133+ where: { walletAddress: ctx.session.user.walletAddress },
134+ include: { discordToken: true },
135+ data: { verified: true, coupon },
136+ });
147137 ctx.status = 200;
138+
148139 await next();
149140 });
150141
api/src/index.ts+1−1
@@ -26,7 +26,7 @@ async function main() {
2626 .use(json())
2727 .use(bodyParser())
2828 .use(cors({ credentials: true }))
29- .use(session({ secure: false, signed: false, sameSite: "none" }, app))
29+ .use(session({ secure: false, signed: false, sameSite: "lax" }, app))
3030 .use(router.routes())
3131 .use(router.allowedMethods());
3232
api/src/quest/index.ts+18−0
@@ -0,0 +1,18 @@
1+import Router from "koa-router";
2+import Koa from "koa";
3+
4+const router = new Router();
5+
6+router.get("/quest", async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
7+ ctx.body = {
8+ title: process.env.QUEST_TITLE,
9+ description: process.env.QUEST_DESCRIPTION,
10+ guildName: process.env.QUEST_GUILD_NAME,
11+ coverImage: process.env.QUEST_COVER_IMAGE,
12+ };
13+
14+ ctx.status = 200;
15+ await next();
16+});
17+
18+export default router;
api/src/routes.ts+4−1
@@ -2,6 +2,7 @@ import Koa from "koa";
22 import Router from "koa-router";
33 import authenticationRouter from "./authentication";
44 import discordRouter from "./discord";
5+import questRouter from "./quest";
56
67 const router = new Router();
78
@@ -20,6 +21,8 @@ router
2021 .use(authenticationRouter.routes())
2122 .use(authenticationRouter.allowedMethods())
2223 .use(discordRouter.routes())
23- .use(discordRouter.allowedMethods());
24+ .use(discordRouter.allowedMethods())
25+ .use(questRouter.routes())
26+ .use(questRouter.allowedMethods());
2427
2528 export default router;
ui/package.json+1−5
@@ -11,17 +11,13 @@
1111 "@types/node": "^16.18.11",
1212 "@types/react": "^18.0.26",
1313 "@types/react-dom": "^18.0.10",
14- "@types/react-router-dom": "^5.3.3",
1514 "@types/styled-components": "^5.1.26",
16- "@types/web3": "^1.2.2",
1715 "axios": "^1.2.2",
1816 "react": "^18.2.0",
1917 "react-dom": "^18.2.0",
20- "react-router-dom": "^6.6.2",
2118 "react-scripts": "5.0.1",
2219 "styled-components": "^5.3.6",
23- "typescript": "^4.9.4",
24- "web3": "^1.8.1"
20+ "typescript": "^4.9.4"
2521 },
2622 "scripts": {
2723 "start": "react-scripts start",
ui/src/components/AuthenticationForm/index.tsx+10−27
@@ -1,30 +1,10 @@
11 import axios from "axios";
22 import React, { useContext, useState } from "react";
3-import { useNavigate } from "react-router-dom";
43 import { StyledButton } from "../../theme/button";
5-import { UserType } from "../../types";
64 import { PageContext } from "../Page";
75
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- );
22-}
23-
246 export function AuthenticationForm() {
257 const [isLoading, setIsLoading] = useState(false);
26- const [error, setError] = useState("");
27- const navigate = useNavigate();
288 const context = useContext(PageContext);
299
3010 const handleAuthenticateClick = async (e: React.MouseEvent) => {
@@ -33,7 +13,7 @@ export function AuthenticationForm() {
3313
3414 // tried to use @metamask/detect-providers but currently has an issue where the type
3515 // we need here is not exported.
36- // TODO: Link to issue
16+ // https://github.com/MetaMask/detect-provider/issues/68
3717 const provider = (window as any)?.ethereum;
3818 if (provider) {
3919 const accounts = await provider.request({
@@ -42,28 +22,33 @@ export function AuthenticationForm() {
4222
4323 await axios
4424 .post("/authenticate", { walletAddress: accounts[0] })
45- .then(() => {
46- navigate("/");
25+ .then((response) => {
26+ context?.setUser(response.data);
4727 })
4828 .catch((error) => {
4929 console.log(error);
30+ context?.setError("We we're unable to receive your account details.");
5031 });
5132 } else {
52- setError("Please install the metamask browser extension.");
33+ context?.setError("Please install the metamask browser extension.");
5334 }
5435 setIsLoading(false);
5536 };
5637
5738 const handleDeauthenticateClick = async (e: React.MouseEvent) => {
39+ e.preventDefault();
5840 setIsLoading(true);
5941
6042 await axios
6143 .post("/deauthenticate")
6244 .then(() => {
63- navigate("/sign-in");
45+ context?.setUser(null);
6446 })
6547 .catch((error) => {
6648 console.log(error);
49+ context?.setError(
50+ "We are not able to reach the api server, please try again later."
51+ );
6752 });
6853
6954 setIsLoading(false);
@@ -82,8 +67,6 @@ export function AuthenticationForm() {
8267 Connect with your wallet via MetaMask
8368 </StyledButton>
8469 )}
85-
86- {error && <p>{error}</p>}
8770 </div>
8871 );
8972 }
ui/src/components/Header/index.tsx+10−3
@@ -1,12 +1,15 @@
1-import React from "react";
1+import React, { useContext } from "react";
22 import styled from "styled-components";
33
44 import { AuthenticationForm } from "../AuthenticationForm";
5+import { PageContext } from "../Page";
56
67 export default function Header() {
8+ const context = useContext(PageContext);
79 return (
810 <StyledHeader>
911 <h1>Sesame Labs Coding Assignment</h1>
12+ <ErrorContainer>{context?.error}</ErrorContainer>
1013 <div>
1114 <AuthenticationForm />
1215 </div>
@@ -18,11 +21,11 @@ const StyledHeader = styled.div`
1821 width: 100%;
1922 height: 60px;
2023 display: grid;
21- grid-template-columns: 1fr 200px;
24+ grid-template-columns: 400px 1fr 200px;
2225 column-gap: auto;
2326
2427 > * {
25- padding: 0.5em 1em;
28+ padding: 0.5em 0;
2629 }
2730
2831 > h1 {
@@ -35,3 +38,7 @@ const StyledHeader = styled.div`
3538 justify-content: right;
3639 }
3740 `;
41+
42+const ErrorContainer = styled.div`
43+ color: red;
44+`;
ui/src/components/JoinDiscordServer/index.tsx+46−29
@@ -1,52 +1,60 @@
1+import axios from "axios";
12 import React, { useContext, useState } from "react";
3+import styled from "styled-components";
24 import { StyledButton } from "../../theme/button";
3-import { StyledLink } from "../../theme/link";
45 import { PageContext } from "../Page";
5-import styled from "styled-components";
6-import axios from "axios";
76
87 export default function JoinDiscordGuild() {
98 const context = useContext(PageContext);
109 const [isLoading, setIsLoading] = useState(false);
1110
12- const handleJoinClick = async (e: React.MouseEvent) => {
13- // Join via the api endpoint
11+ const handleJoinLink = async (e: React.MouseEvent) => {
1412 e.preventDefault();
15- setIsLoading(true);
16- await axios.post("/discord/join").catch((e) => {
17- console.log(e);
18- });
19- setIsLoading(false);
13+
14+ window.open(
15+ `${process.env.REACT_APP_API_URL}/discord/join`,
16+ "_blank",
17+ "noopener,noreferrer"
18+ );
2019 };
2120
2221 const handleVerifyClick = async (e: React.MouseEvent) => {
23- // call the verify endpoint
2422 e.preventDefault();
2523 setIsLoading(true);
26- const response = await axios.get("/discord/verify").catch((e) => {
27- console.log(e);
28- });
29-
30- console.log(response);
3124
32- setIsLoading(false);
25+ await axios
26+ .get("/discord/verify")
27+ .then((response) => {
28+ setIsLoading(false);
29+ context?.setUser(response.data);
30+ })
31+ .catch((e) => {
32+ console.log(e);
33+ setIsLoading(false);
34+ context?.setError(
35+ "We are having trouble reaching discord, please try again later."
36+ );
37+ });
3338 };
3439
3540 return isLoading ? (
3641 <p>Loading...</p>
3742 ) : (
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>
43+ <div>
44+ <ActionsContainer>
45+ {context?.user?.verified ? (
46+ <p>
47+ Verified! your coupon is:{" "}
48+ <CouponContainer>{context?.user?.coupon}</CouponContainer>
49+ </p>
50+ ) : (
51+ <>
52+ <StyledButton onClick={handleJoinLink}>Join</StyledButton>
53+ <StyledButton onClick={handleVerifyClick}>verify</StyledButton>
54+ </>
55+ )}
56+ </ActionsContainer>
57+ </div>
5058 );
5159 }
5260
@@ -55,3 +63,12 @@ const ActionsContainer = styled.div`
5563 grid-template-columns: 1fr 1fr;
5664 column-gap: 40px;
5765 `;
66+
67+const CouponContainer = styled.pre`
68+ border: 2px solid ${(props) => props.theme.colors.highlight};
69+ border-radius: 8px;
70+ color: ${(props) => props.theme.colors.background};
71+ background: ${(props) => props.theme.colors.foreground};
72+ font-size: 2em;
73+ padding: 1em;
74+`;
ui/src/components/Page/index.tsx+44−21
@@ -1,33 +1,57 @@
1-import React, { createContext, useEffect } from "react";
2-import { useLoaderData, useNavigate } from "react-router-dom";
1+import axios from "axios";
2+import React, { createContext, useState, useEffect } from "react";
33 import styled, { ThemeProvider } from "styled-components";
44 import theme from "../../theme";
5-import { PageContextType, UserType } from "../../types";
5+import { PageContextType } from "../../types";
6+import Quest from "../Quest";
67
78 export const PageContext = createContext<PageContextType | null>(null);
89
9-export default function Page({
10- requiresAuthentication,
11- redirectTarget,
12- children,
13-}: {
14- requiresAuthentication: boolean;
15- redirectTarget?: string;
16- children: React.ReactNode;
17-}) {
18- const navigate = useNavigate();
19- const user = useLoaderData() as UserType;
10+export default function Page() {
11+ const [user, setUser] = useState(null);
12+ const [quest, setQuest] = useState(null);
13+ const [error, setError] = useState("");
2014
21- // Protect authenticated routes:
2215 useEffect(() => {
23- if (requiresAuthentication && !user)
24- navigate(redirectTarget ? redirectTarget : "/");
25- }, [requiresAuthentication, redirectTarget, navigate, user]);
16+ axios
17+ .get("/authenticated_user")
18+ .then((response) => {
19+ setUser(response.data);
20+ })
21+ .catch((e) => {
22+ if (e?.response?.status !== 404) {
23+ console.log(e);
24+ setError(
25+ "We are having trouble reach the API server, please try again later."
26+ );
27+ }
28+ setUser(null);
29+ });
30+
31+ axios
32+ .get("/quest")
33+ .then((response) => setQuest(response.data))
34+ .catch((e) => {
35+ console.log(e);
36+ setError(
37+ "We are having trouble reach the API server, please try again later."
38+ );
39+ });
40+ }, []);
41+
42+ // Remove the error after 5 seconds.
43+ useEffect(() => {
44+ setTimeout(() => {
45+ setError("");
46+ }, 5000);
47+ }, [error]);
2648
2749 return (
28- <PageContext.Provider value={{ user }}>
50+ <PageContext.Provider value={{ user, setUser, quest, error, setError }}>
2951 <ThemeProvider theme={theme}>
30- <StyledPage>{children}</StyledPage>
52+ <StyledPage>
53+ <Quest />
54+ </StyledPage>
3155 </ThemeProvider>
3256 </PageContext.Provider>
3357 );
@@ -35,7 +59,6 @@ export default function Page({
3559
3660 const StyledPage = styled.div`
3761 display: flex;
38- flex-wrap: wrap;
3962 justify-content: center;
4063 width: 100%;
4164 height: 100%;
ui/src/components/Quest/index.tsx+42−0
@@ -0,0 +1,42 @@
1+import React, { useContext } from "react";
2+import styled from "styled-components";
3+import Header from "../Header";
4+import JoinDiscordGuild from "../JoinDiscordServer";
5+import { PageContext } from "../Page";
6+
7+export default function Quest() {
8+ const context = useContext(PageContext);
9+
10+ return (
11+ <QuestContainer>
12+ <Header />
13+ <QuestDetails>
14+ <QuestPrompt>
15+ <h2>{context?.quest?.title}</h2>
16+ <div>{context?.quest?.description}</div>
17+ {context?.user && <JoinDiscordGuild />}
18+ </QuestPrompt>
Cut short: this commit's diff is over 1000 lines.
ui/src/index.tsx+3−34
Cut short: this commit's diff is over 1000 lines.
ui/src/theme/link.tsx+0−14
Cut short: this commit's diff is over 1000 lines.
ui/src/types.ts+11−0
Cut short: this commit's diff is over 1000 lines.