|
| 1 | +import { Request, Response } from 'express'; |
| 2 | +import axios, { AxiosError } from 'axios'; |
| 3 | +import { BadRequestError, CurrentUserRequest, EventTypes, Events } from '@chronosrx/common'; |
| 4 | +import { User } from '../models/user'; |
| 5 | +import { attachCookie } from '../util/attachCookie'; |
| 6 | + |
| 7 | +export const signup = async (req: Request, res: Response) => { |
| 8 | + // console.log('💥 authController signup'); |
| 9 | + const { username, password } = req.body; |
| 10 | + |
| 11 | + // Validate inputs |
| 12 | + if (!username || !password || password.length < 4) { |
| 13 | + throw new BadRequestError('Invalid inputs'); |
| 14 | + } |
| 15 | + |
| 16 | + // Check to see if user with supplied username already exists |
| 17 | + const existingUser = await User.findOne({ username }); |
| 18 | + if (existingUser) { |
| 19 | + throw new BadRequestError('User with that username exists'); |
| 20 | + } |
| 21 | + |
| 22 | + // create the user document |
| 23 | + const newUser = User.build({ |
| 24 | + username, |
| 25 | + password, |
| 26 | + }); |
| 27 | + // save newly created user document to the database |
| 28 | + await newUser.save(); |
| 29 | + |
| 30 | + // TODO PUBLISH AN EVENT TO THE EVENT BUS - type USER_CREATED, with data of user - user.id & username |
| 31 | + // console.log('Publishing event USER_CREATED'); |
| 32 | + |
| 33 | + const event: Events = { |
| 34 | + type: EventTypes.USER_CREATED, |
| 35 | + payload: { |
| 36 | + id: newUser.id, |
| 37 | + username: newUser.username, |
| 38 | + }, |
| 39 | + }; |
| 40 | + try { |
| 41 | + await axios.post('http://localhost:3005/', { |
| 42 | + event, |
| 43 | + }); |
| 44 | + } catch (err) { |
| 45 | + console.log( |
| 46 | + `Failed to emit event USER_CREATED from auth: ${ |
| 47 | + (err as AxiosError).message || 'unknown error' |
| 48 | + } ` |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + // create a JWT w/ userId store on it |
| 53 | + // note: createJwt method created on the userSchema |
| 54 | + const token = newUser.createJwt(); |
| 55 | + // set cookie on response object with name 'token' and value of the jwt |
| 56 | + // attachCookie method - defined in util folder |
| 57 | + attachCookie(res, token); |
| 58 | + |
| 59 | + // |
| 60 | + res.status(201).send(newUser); |
| 61 | +}; |
| 62 | + |
| 63 | +export const login = async (req: Request, res: Response) => { |
| 64 | + // console.log('💥 authController login'); |
| 65 | + // pull username and password off request body |
| 66 | + const { username, password } = req.body; |
| 67 | + // validate username and password - they exist |
| 68 | + if (!username || !password) { |
| 69 | + throw new BadRequestError('Must provide username and password'); |
| 70 | + } |
| 71 | + // query database for user with that username |
| 72 | + const existingUser = await User.findOne({ username }); |
| 73 | + // handle case where no user exists with that username |
| 74 | + if (!existingUser) { |
| 75 | + throw new BadRequestError('Invalid credentials'); |
| 76 | + } |
| 77 | + |
| 78 | + // if user does exist - compare provided password to user's password in DB |
| 79 | + // * we defined a comparePassword method on the userSchema -> accepts provided password as argument |
| 80 | + // handle case when passwords do not match |
| 81 | + const passwordsMatch = await existingUser.comparePassword(password); |
| 82 | + if (!passwordsMatch) { |
| 83 | + throw new BadRequestError('Invalid credentials'); |
| 84 | + } |
| 85 | + |
| 86 | + // if passwords do match - create a JWT |
| 87 | + // * we created a method createJwt on the userSchema that returns the jwt (aka token) |
| 88 | + const token = existingUser.createJwt(); |
| 89 | + // attach the jwt to the cookie |
| 90 | + // * we defined an attachCookie helper function (in util folder) - is already imported for us |
| 91 | + // accepts the response object and jwt/token as arguments |
| 92 | + attachCookie(res, token); |
| 93 | + // send back the found user with status code 200 |
| 94 | + res.status(200).send(existingUser); |
| 95 | +}; |
| 96 | + |
| 97 | +export const logout = async (req: Request, res: Response) => { |
| 98 | + // console.log('💥 authController logout'); |
| 99 | + |
| 100 | + // Set cookie on response object with name 'token' to null |
| 101 | + // make the cookie httpOnly |
| 102 | + // set cookie expiration to 500ms from now |
| 103 | + res.cookie('token', null, { |
| 104 | + httpOnly: true, |
| 105 | + secure: false, |
| 106 | + expires: new Date(Date.now() + 500), |
| 107 | + }); |
| 108 | + |
| 109 | + res.status(200).send({ message: 'success' }); |
| 110 | +}; |
| 111 | + |
| 112 | +export const getCurrentUser = async (req: CurrentUserRequest, res: Response) => { |
| 113 | + // check request object for currentUser property |
| 114 | + if (!req.currentUser) { |
| 115 | + // if it doesn't exist send back status 200 with object with currentUser property set to null |
| 116 | + return res.status(200).send({ currentUser: null }); |
| 117 | + } |
| 118 | + |
| 119 | + // if it does exist - use req.currentUser to find user in database by id |
| 120 | + const user = await User.findById(req.currentUser); |
| 121 | + // send back 200 with object with property currentUser set to the user from the database |
| 122 | + res.status(200).send({ currentUser: user }); |
| 123 | +}; |
0 commit comments