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';
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);
18 const res: any = await db.insert(data).into('auth');
19 if(res.rowCount === 1) {
24 throw new Error('Something weird happened..');
30 if(e?.code === '23505') {
31 if(e?.constraint === 'auth_pkey') {
32 console.log(`Key ${playerId} was already claimed. ${username} tried claiming again..`);
34 // someone already claimed this key
35 throw new Error('Invalid account');
41 export async function login(username: string, password: string): Promise<Player> {
42 const auth = await db.select('*').first().from<Auth>('auth').where({
47 const compare = await bcrypt.compare(password, auth.password);
49 return loadPlayer(auth.id);
52 throw new Error(`Invalid password for ${username}`);
56 throw new Error(`Requested user ${username}, does not exist`);
61 export function authEndpoint(req: Request, res: Response, next: any) {
62 const authToken = req.headers['x-authtoken'];
64 console.log(`Invalid auth token ${authToken}`);