1 import { Player } from 'shared/player';
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';
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);
14 username: xss(username, { whiteList: {} }),
19 const res: any = await db.insert(data).into('auth');
20 if(res.rowCount === 1) {
25 throw new Error('Something weird happened..');
31 if(e?.code === '23505') {
32 if(e?.constraint === 'auth_pkey') {
33 console.log(`Key ${playerId} was already claimed. ${data.username} tried claiming again..`);
35 // someone already claimed this key
36 throw new Error('Invalid account');
42 export async function login(username: string, password: string): Promise<Player> {
43 const auth = await db.select('*').first().from<Auth>('auth').where({
48 const compare = await bcrypt.compare(password, auth.password);
50 return loadPlayer(auth.id);
53 throw new Error(`Invalid password for ${username}`);
57 throw new Error(`Requested user ${username}, does not exist`);
62 export async function authEndpoint(req: Request, res: Response, next: any) {
63 const authToken = req.headers['x-authtoken'];
65 console.log(`Invalid auth token ${authToken}`);
69 const player: Player = await loadPlayer(authToken.toString());
75 console.log(`Invalid auth token ${authToken}`);