|
| 1 | +import express from 'express'; |
| 2 | + |
| 3 | +import { UserDatabase } from '../../db/users'; |
| 4 | +import { authentication, random } from '../../helpers' |
| 5 | +import { Logger } from '../../loggers/logger' |
| 6 | +export class V1AuthController { |
| 7 | + private static userDB = UserDatabase.getInstance(); |
| 8 | + |
| 9 | + public static v1login = async (req: express.Request, res: express.Response) => { |
| 10 | + try { |
| 11 | + const { email, password} = req.body; |
| 12 | + if (!email || !password ) { |
| 13 | + return res.sendStatus(400) |
| 14 | + } |
| 15 | + const user = await V1AuthController.userDB.getUserByEmail(email).select("+authentication.salt +authentication.password"); |
| 16 | + |
| 17 | + if (!user) { |
| 18 | + return res.sendStatus(400) |
| 19 | + } |
| 20 | + |
| 21 | + const expectedHash = authentication(user.authentication.salt, password); |
| 22 | + if (user.authentication.password != expectedHash) { |
| 23 | + return res.sendStatus(401) |
| 24 | + } |
| 25 | + |
| 26 | + const salt = random(); |
| 27 | + user.authentication.sessionToken = authentication(salt, user._id.toString()); |
| 28 | + await user.save() |
| 29 | + |
| 30 | + res.cookie("VWS-AUTH", user.authentication.sessionToken, { |
| 31 | + domain: 'localhost', |
| 32 | + path: "/" |
| 33 | + }); |
| 34 | + return res.status(200).json(user).end() |
| 35 | + |
| 36 | + } catch (error) { |
| 37 | + Logger.Error(error.toString()) |
| 38 | + return res.sendStatus(400) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public static v1register = async (req: express.Request, res: express.Response) => { |
| 43 | + try { |
| 44 | + const { email, password, username } = req.body; |
| 45 | + |
| 46 | + if (!email || !password || !username) { |
| 47 | + return res.sendStatus(400); |
| 48 | + }; |
| 49 | + |
| 50 | + const existingUser = await V1AuthController.userDB.getUserByEmail(email); |
| 51 | + if (existingUser) { |
| 52 | + return res.sendStatus(400); |
| 53 | + }; |
| 54 | + |
| 55 | + const salt = random(); |
| 56 | + const user = await V1AuthController.userDB.createUser({ |
| 57 | + email, |
| 58 | + username, |
| 59 | + authentication: { |
| 60 | + salt, |
| 61 | + password: authentication(salt, password) |
| 62 | + }, |
| 63 | + }); |
| 64 | + |
| 65 | + return res.status(200).json(user).end() |
| 66 | + |
| 67 | + } catch (error) { |
| 68 | + Logger.Error(error.toString()); |
| 69 | + return res.sendStatus(400); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + public static v1logSuccessMsg = async (req: express.Request, res: express.Response, next: express.NextFunction) => { |
| 74 | + Logger.Info("successfully registered"); |
| 75 | + next(); |
| 76 | + } |
| 77 | +} |
0 commit comments