|
| 1 | +// middleware functions create a new user and verify users |
| 2 | + |
1 | 3 | const Users = require('../models/userModels');
|
| 4 | + |
| 5 | +const userController = {}; |
| 6 | +const bcrypt = require('bcryptjs'); |
| 7 | + |
| 8 | +userController.createUser = (req, res, next) => { |
| 9 | + const { username, password } = req.body; |
| 10 | + // error handling if username or password is missing |
| 11 | + if (!username || !password) { |
| 12 | + return next('Missing username or password in userController.createUser'); |
| 13 | + } |
| 14 | + const projects = []; |
| 15 | + // create user using username and password |
| 16 | + Users.create({ username, password, projects }, (err, newUser) => { |
| 17 | + if (err) { |
| 18 | + return next({ |
| 19 | + log: `Error in userController.createUser: ${err}`, |
| 20 | + message: { |
| 21 | + err: `Error in userController.createUser. Check server logs for details` |
| 22 | + } |
| 23 | + }); |
| 24 | + } else { |
| 25 | + // this id property will be used in other middleware for cookie |
| 26 | + res.locals.id = newUser.id; |
| 27 | + return next(); |
| 28 | + } |
| 29 | + }); |
| 30 | +}; |
| 31 | + |
| 32 | +// verifyUser - Obtain username and password from the request body, locate |
| 33 | +// the appropriate user in the database, and then authenticate the submitted password against the password stored in the database. |
| 34 | + |
| 35 | +userController.verifyUser = (req, res, next) => { |
| 36 | + const { username, password } = req.body; |
| 37 | + Users.findOne({ username }, (err, user) => { |
| 38 | + if (err) { |
| 39 | + return next({ |
| 40 | + log: `Error in userController.verifyUser: ${err}`, |
| 41 | + message: { |
| 42 | + err: `Error in userController.verifyUser, check server logs for details` |
| 43 | + } |
| 44 | + }); |
| 45 | + } else { |
| 46 | + // bcrypt compare function checks input password against hashed password |
| 47 | + bcrypt.compare(password, user.password).then(isMatch => { |
| 48 | + if (isMatch) { |
| 49 | + // if password matches, save user id for following middleware |
| 50 | + res.locals.id = user.id; |
| 51 | + return next(); |
| 52 | + } else { |
| 53 | + // if password does not match, redirect to ? |
| 54 | + res.redirect('/login'); |
| 55 | + } |
| 56 | + }); |
| 57 | + } |
| 58 | + }); |
| 59 | +}; |
| 60 | + |
| 61 | +module.exports = userController; |
0 commit comments