User authentication and authorization

Last modified: May 04, 2022

Create a folder called Controller, create a file auth.controller.js and save it to it.

In this controller, we have two functions

  • Sigin
  • Signup

Imports

const db = require('../db/models/index'); const { verifySignUp } = require("../middleware"); const User = db.user; const UserRole = db.userrole; const Role = db.role; const Op = db.Sequelize.Op; var jwt = require("jsonwebtoken"); //generate jwt token var bcrypt = require("bcryptjs"); //encryption

signup

  • Input username, email, and password
  • Hash the password
  • Create User and if success, return promise
  • Upon create create successful, return message
app.post("/api/auth/signup" , [ verifySignUp.checkDuplicateUsernameOrEmail, verifySignUp.checkRolesExisted ], async function(request, response){ try { await User.create({ username: request.body.username, email: request.body.email, password: bcrypt.hashSync(request.body.password, 10), }) .then(u => { UserRole.create({ roleId: process.env.UserRoleId, //default user to be user role userId : u.id }) .then(msg => { response.send({ message: "User was registered successfully!" }); }) }); } catch (error) { response.status(500).send({ message: error.message }); } });

signin

  • First check if username exist in the database, if no return response "User Not found.",
  • Then compare password pass in body against the database by hasing it, if not match return response "Invalid Password",
  • Finally, when both username and password match, then issue a JWT (Json Web Token).
app.post("/api/auth/signin" , async function(request, response){ User.findOne( {where: { username: request.body.username}, include: Role }) .then(user => { if (!user) { return response.status(404).send({ message: "User Not found." }); } var passwordIsValid = bcrypt.compareSync( request.body.password, user.password ); if (!passwordIsValid) { return response.status(401).send({ accessToken: null, message: "Invalid Password!" }); } var token = jwt.sign({ id: user.id }, process.env.JWT_SECRET_KEY, { expiresIn: 86400 // 24 hours }); response.status(200).send({ id: user.id, username: user.username, email: user.email, accessToken: token }); }) .catch(err => { response.status(500).send({ message: err.message }); }); });