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