Aquasar
  • Home
  • Portfolio
  • Articles
  • Pricing
  • About
  • Contact
WEB DEVELOPMENT |SEO |DIGITAL ADS

Logging in a user using Express

Jun 28th, 2019

Alex Quasar

expressauthenticationlogging in a user in expresslogin with express

There are many methods to login a user. Here is on method using express, jwt and bcrypt. See `Registering a user with express` if you have not already.

In our routes/api directory, we will create an auth.js file as below:

const express = require('express');
const router = express.Router();

const auth = require('../../middleware/auth');
const jwt = require('jsonwebtoken');
const config = require('../../config/keys').jwtSecret;
const { check, validationResult } = require('express-validator');

const User = require('../../models/User');

// name         :   Login User
// Type         :   POST
// Route        :   api/auth
// Description  :   Log user in and send token
// Access       :   User must be registered. 
router.post(
  '/',
  [
    check('email', 'Please include a valid email').isEmail(),
    check('password', 'Password is required').exists()
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { email, password } = req.body;
 
    try {
      
      let user = await User.findOne({ email }).select('+password');

      // user does not exist or password is not correct.
      if (!user || !(await user.checkPassword(password, user.password)) ) {
        return res
          .status(400)
          .json({ errors: [{ msg: 'Invalid Credentials' }] });
      }
    
      const payload = {
        user: {
          id: user.id,
          admin: user.admin
        }
      };

      jwt.sign(
        payload,
        config,
        { expiresIn: 360000 },
        (err, token) => {
          if (err) throw err;
          res.json({ token });
        }
      );
    } catch (err) {
      console.error(err.message);
      res.status(500).send('Server error');
    }
  }
);

module.exports = router;

There is a few steps here.

1. Find user from database.

2. Compare the input password the user enters to the password for that user in the database. Since our password is encrypted, we must first encrypt that inputPassword to compare the two passwords.

That happens inside the User model:

// check password
UserSchema.methods.checkPassword= async function( inputpassword, userPassword ) {
    return await bcrypt.compare(inputpassword, userPassword);
}

We create this method called checkPassword which is then available on all User documents. It simply encrypts the inputPassword and compares it to our password stored in the database.