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 interface AuthRequest extends Request {
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);
22 const res: any = await db.insert(data).into('auth');
23 if(res.rowCount === 1) {
28 throw new Error('Something weird happened..');
34 if(e?.code === '23505') {
35 if(e?.constraint === 'auth_pkey') {
36 console.log(`Key ${playerId} was already claimed. ${username} tried claiming again..`);
38 // someone already claimed this key
39 throw new Error('Invalid account');
45 export async function login(username: string, password: string): Promise<Player> {
46 const auth = await db.select('*').first().from<Auth>('auth').where({
51 const compare = await bcrypt.compare(password, auth.password);
53 return loadPlayer(auth.id);
56 throw new Error(`Invalid password for ${username}`);
60 throw new Error(`Requested user ${username}, does not exist`);
65 export async function authEndpoint(req: AuthRequest, res: Response, next: any) {
66 const authToken = req.headers['x-authtoken'];
68 console.log(`Invalid auth token ${authToken}`);
72 const player: Player = await loadPlayer(authToken.toString());
78 console.log(`Invalid auth token ${authToken}`);