proc-gen equipment drops from monsters can be picked up
[sketchy-heroes.git] / src / routes / account / login.ts
1 import { server } from '../../lib/server';
2 import { Static, Type } from '@sinclair/typebox';
3 import { prisma } from '../../lib/db';
4 import { NotFoundError } from '../../lib/http-errors';
5 import { v4 as uuid } from 'uuid';
6 import {Player} from '@prisma/client';
7
8 const LoginInput = Type.Object({
9   body: Type.Object({
10     username: Type.String(),
11     password: Type.String()
12   })
13 });
14
15 type LoginInputType = Static<typeof LoginInput>;
16
17 export type LoginOutputType = {
18   token: string,
19   player: Player
20 };
21
22 export const login = server.post<LoginInputType, any>('/v1/accounts/auth', {
23   schema: LoginInput
24 }, async req => {
25   const {username, password} = req.body;
26   const player = await prisma.player.findUnique({
27     where: {
28       username: username
29     }
30   });
31
32   if(!player || password !== player.password) { 
33     throw new NotFoundError('Invalid user credentials');
34   }
35
36   const token = await prisma.authToken.upsert({
37     where: {
38       playerId: player.id
39     },
40     create: {
41       playerId: player.id
42     },
43     update: {
44       token: uuid()
45     }
46   });
47
48   return {
49     token: token.token,
50     player
51   };
52 });