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