Authenticate in Node

NodeJS – Basic Authentication

A simple example that show how to implement Basic HTTP Authentication in a Node.js API with JavaScript.

This example use validator npm to validate input data before authentication. once validated, it uses sequelize to check user in database

var generatePassword = require("password-generator"),
  models = require("../../models"),  
  validator = require("validator"),
  moment = require("moment");

exports.authenticate = function (reqresnext) {
  console.log("authenticate-index");

  var email = req.body.email.trim(),
    password = req.body.passwd.trim();

  if (!validator.isEmail(email)) {
    return res
      .status(403)
      .json(new HttpError(403, "Please, enter valid email"));
  }

  if (!validator.isNonEmpty(password)) {
    return res
      .status(403)
      .json(new HttpError(403, "Password should be filled"));
  }

  models.user
    .findOne({
      where: { email: email, verified: 1 },
    })
    .then(function (client) {
      if (!client) return res.status(404).send({ message: "User Not Found" });
      if (!client.checkPassword(password))
        return res.status(403).send(new HttpError(403, "Invalid password"));
      req.session.uid = email;
      res.send("User " + email + " successfully logged in");
    })
    .catch(function (err) {
      console.log(err);
      next(err);
    });
};