|
| 1 | +import express from "express"; |
| 2 | +import * as dotenv from "dotenv"; |
| 3 | + |
| 4 | +import { createUser, getUserByEmail } from "../db/users"; |
| 5 | +import { random, authentication } from "../helpers"; |
| 6 | + |
| 7 | +dotenv.config(); |
| 8 | + |
| 9 | +export const login = async (req: express.Request, res: express.Response) => { |
| 10 | + try { |
| 11 | + const { email, password } = req.body; |
| 12 | + |
| 13 | + if (!email || !password) { |
| 14 | + return res.sendStatus(400); |
| 15 | + } |
| 16 | + |
| 17 | + const user = await getUserByEmail(email).select( |
| 18 | + "+authentication.password +authentication.salt" |
| 19 | + ); |
| 20 | + |
| 21 | + if (!user) { |
| 22 | + return res.sendStatus(400); |
| 23 | + } |
| 24 | + |
| 25 | + const expectedHash = authentication(user.authentication.salt, password); |
| 26 | + if (user.authentication.password !== expectedHash) { |
| 27 | + return res.sendStatus(403); |
| 28 | + } |
| 29 | + |
| 30 | + const salt = random(); |
| 31 | + user.authentication.sessionToken = authentication( |
| 32 | + salt, |
| 33 | + user._id.toString() |
| 34 | + ); |
| 35 | + |
| 36 | + await user.save(); |
| 37 | + |
| 38 | + res.cookie( |
| 39 | + process.env.SESSION_TOKEN_NAME as string, |
| 40 | + user.authentication.sessionToken, |
| 41 | + { |
| 42 | + domain: "localhost", |
| 43 | + path: "/", |
| 44 | + } |
| 45 | + ); |
| 46 | + |
| 47 | + return res.status(200).json(user).end(); |
| 48 | + } catch (error) { |
| 49 | + console.log(error); |
| 50 | + return res.sendStatus(400); |
| 51 | + } |
| 52 | +}; |
| 53 | + |
| 54 | +export const register = async (req: express.Request, res: express.Response) => { |
| 55 | + try { |
| 56 | + const { email, password, username } = req.body; |
| 57 | + |
| 58 | + if (!email || !password || !username) { |
| 59 | + return res.sendStatus(400); |
| 60 | + } |
| 61 | + |
| 62 | + const existingUser = await getUserByEmail(email); |
| 63 | + |
| 64 | + if (existingUser) { |
| 65 | + return res.sendStatus(400); |
| 66 | + } |
| 67 | + |
| 68 | + const salt = random(); |
| 69 | + const user = await createUser({ |
| 70 | + email, |
| 71 | + username, |
| 72 | + authentication: { salt, password: authentication(salt, password) }, |
| 73 | + }); |
| 74 | + |
| 75 | + return res.status(200).json(user).end(); |
| 76 | + } catch (error) { |
| 77 | + console.log(error); |
| 78 | + return res.sendStatus(400); |
| 79 | + } |
| 80 | +}; |
0 commit comments