ArabDROPS
ArabDROPS

Reputation: 101

Why do we use connect-mongo with express-session, passport, and express?

I am still new to Passport, and i have created an application with express, passport, and express-session and it's authenticating as expected. but for some reason I keep running into connect-mongo in every tuturial. so please can you explain what is the role of connect-mongo exactly and/or and it wou be greate if you could provide some good document about it. thank you for your time sir.

Upvotes: 1

Views: 205

Answers (1)

Smit Gajera
Smit Gajera

Reputation: 1039

@ArabDROPS first of all, are you using the wrong package for connecting our node app with the mongo database use Mongoose Package for connecting our app with the database

In modern web applications, JWTs are widely used as it scales better than that of a session-cookie

You can follow this template for when the user login generates token and you can check with middleware not need to use express-session.


1. GENERATE JWT TOKEN WHEN USER LOGIN

Generate Token and Send this token with a response...

    router.post("/login", async (req, res) => {
      try {
        // checking username
        const user = await User.findOne({ email: req.body.email });
        !user && res.status(401).json("Wrong Username");
    
        // checking password
        const bytes = CryptoJS.AES.decrypt(user.password, process.env.SECRET_KEY);
        const originalPassword = bytes.toString(CryptoJS.enc.Utf8);
    
        // If password not match return respond
        originalPassword !== req.body.password &&
          res.status(401).json("Wrong Password");
    
        // Creating Json Web Token
    
        const accessToken = jwt.sign(
          { id: user._id, isAdmin: user.isAdmin },
          process.env.SECRET_KEY,
          { expiresIn: "5d" }
        );
    
        // stop sending password to respond
        const { password, ...info } = user._doc;
    
        // Returning User(info) , also sending accessToken
        res.status(200).json({ ...info, accessToken });
      } catch (err) {
        res.status(500).json(err);
      }
    });

2. VERIFY TOKEN MIDDLEWARE

Create this verify token function used as a MIDDLEWARE in your routes...

const jwt = require("jsonwebtoken");

function verify(req, res, next) {
  const authHeader = req.headers.token;
  if (authHeader) {
    const token = authHeader.split(" ")[1];
    jwt.verify(token, process.env.SECRET_KEY, (err, user) => {
      if (err) res.status(403).json("Token is not valid");
      req.user = user;
      next();
    });
  } else {
    return res.status(402).json("You are not authorized");
  }
}

module.exports = verify;

3. VERIFY-IN ROUTES AS AN MIDDLEWARE

const verify = require("../verifyToken");

// CREATE
router.post("/", verify, async (req, res) => {
  if (req.user.isAdmin) {
    const newList = new List(req.body);
    try {
      const savedList = await newList.save();
      res.status(201).json(savedList);
    } catch (error) {
      res.status(500).json(err);
    }
  } else {
    res.status(403).json("You are not allowed!");
  }
});

// DELETE
router.delete("/:id", verify, async (req, res) => {
  if (req.user.isAdmin) {
    try {
      await List.findByIdAndDelete(req.params.id);
      res.status(201).json("The list has been deleted");
    } catch (err) {
      res.status(500).json(err);
    }
  } else {
    res.status(403).json("You are not allowed!");
  }
});

CONCLUSION:-

  1. Create a token with jwt.sign when user login...
  2. Create a verify function in the root directory export this function...
  3. Require this function in routes file use as a middleware...

Upvotes: 2

Related Questions