chore(release): 0.3.3
[risinglegends.git] / src / server / auth.ts
1 import { Player } from 'shared/player';
2 import xss from 'xss';
3 import bcrypt from 'bcrypt';
4 import { loadPlayer } from './player';
5 import { Auth } from '../shared/auth';
6 import { db } from './lib/db';
7 import { Request, Response } from 'express';
8
9 export async function signup(playerId: string, username: string, password: string): Promise<void> {
10   const salt = await bcrypt.genSalt(10);
11   const hash = await bcrypt.hash(password, salt);
12   const data: Auth = {
13     id: playerId,
14     username: xss(username, { whiteList: {} }),
15     password: hash
16   };
17
18   try {
19     const res: any = await db.insert(data).into('auth');
20     if(res.rowCount === 1) {
21       return;
22     }
23     else {
24       console.log(res);
25       throw new Error('Something weird happened..');
26     }
27
28   }
29   catch(e) {
30     console.log(e);
31     if(e?.code === '23505') {
32       if(e?.constraint === 'auth_pkey') {
33         console.log(`Key ${playerId} was already claimed. ${data.username} tried claiming again..`);
34       }
35       // someone already claimed this key
36       throw new Error('Invalid account');
37     }
38   }
39
40 }
41
42 export async function login(username: string, password: string): Promise<Player> {
43   const auth = await db.select('*').first().from<Auth>('auth').where({
44     username
45   });
46
47   if(auth) {
48     const compare = await bcrypt.compare(password, auth.password);
49     if(compare) {
50       return loadPlayer(auth.id);
51     }
52     else {
53       throw new Error(`Invalid password for ${username}`);
54     }
55   }
56   else {
57     throw new Error(`Requested user ${username}, does not exist`);
58   }
59
60 }
61
62 export async function authEndpoint(req: Request, res: Response, next: any) {
63   const authToken = req.headers['x-authtoken'];
64   if(!authToken) {
65     console.log(`Invalid auth token ${authToken}`);
66     res.sendStatus(401)
67   }
68   else {
69     const player: Player = await loadPlayer(authToken.toString());
70     if(player) {
71       req.player = player;
72       next()
73     }
74     else {
75       console.log(`Invalid auth token ${authToken}`);
76       res.sendStatus(401);
77     }
78   }
79 }