chore(release): 0.2.4
[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
7 export async function signup(playerId: string, username: string, password: string): Promise<void> {
8   const salt = await bcrypt.genSalt(10);
9   const hash = await bcrypt.hash(password, salt);
10   const data: Auth = {
11     id: playerId,
12     username,
13     password: hash
14   };
15
16   try {
17     const res: any = await db.insert(data).into('auth');
18     if(res.rowCount === 1) {
19       return;
20     }
21     else {
22       console.log(res);
23       throw new Error('Something weird happened..');
24     }
25
26   }
27   catch(e) {
28     console.log(e);
29     if(e?.code === '23505') {
30       if(e?.constraint === 'auth_pkey') {
31         console.log(`Key ${playerId} was already claimed. ${username} tried claiming again..`);
32       }
33       // someone already claimed this key
34       throw new Error('Invalid account');
35     }
36   }
37
38 }
39
40 export async function login(username: string, password: string): Promise<Player> {
41   const auth = await db.select('*').first().from<Auth>('auth').where({
42     username
43   });
44
45   if(auth) {
46     const compare = await bcrypt.compare(password, auth.password);
47     if(compare) {
48       return loadPlayer(auth.id);
49     }
50     else {
51       throw new Error(`Invalid password for ${username}`);
52     }
53   }
54   else {
55     throw new Error(`Requested user ${username}, does not exist`);
56   }
57
58 }