xonecas.io
4436
Sl

sesame-labs-coding-assignment / files

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

1.4 KB
1import Router from "koa-router";
2import Koa from "koa";
3import { StatusCodes } from "http-status-codes";
4
5const router = new Router();
6
7router.post(
8  "/authenticate",
9  async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
10    const data = ctx.request.body;
11    let user = null;
12
13    // Check for an existing user:
14    user = await ctx.prisma.user.findUnique({
15      where: { walletAddress: data.walletAddress },
16      include: { discordToken: true },
17    });
18
19    // New user:
20    if (!user) {
21      user = await ctx.prisma.user.create({
22        data: { walletAddress: data.walletAddress },
23      });
24      ctx.status = StatusCodes.CREATED;
25    } else {
26      ctx.status = StatusCodes.OK;
27    }
28
29    if (ctx.session) {
30      ctx.session.user = user;
31    }
32    ctx.body = user;
33
34    await next();
35  }
36);
37
38router.post(
39  "/deauthenticate",
40  async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
41    ctx.session = null;
42    ctx.status = StatusCodes.OK;
43    await next();
44  }
45);
46
47router.get(
48  "/authenticated_user",
49  async (ctx: Koa.ParameterizedContext, next: Koa.Next) => {
50    if (ctx.session?.user) {
51      ctx.body = ctx.session.user = await ctx.prisma.user.findUnique({
52        include: { discordToken: true },
53        where: { walletAddress: ctx.session.user.walletAddress },
54      });
55
56      ctx.status = StatusCodes.OK;
57    }
58
59    await next();
60  }
61);
62
63export default router;