Setting up Passport.js

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 304:- Setting up Passport.js

To set up Passport.js for authentication in your application, follow these steps:

  1. Install Passport.js and other required packages using NPM:

    luaCopy code

    npm install passport passport-local express-session bcrypt

    • passport is the core library of Passport.js.
    • passport-local is a strategy for authenticating with a username and password.
    • express-session is used to maintain user session across requests.
    • bcrypt is a library for hashing and salting passwords.
  2. Import and initialize the required packages in your application:

    javascriptCopy code

    const express = require('express'); const session = require('express-session'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; const bcrypt = require('bcrypt'); const app = express(); app.use(express.urlencoded({ extended: true })); app.use(session({  secret: 'your-secret-key',  resave: false,  saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session());

    Here, we're setting up the Express application with the following:

    • express.urlencoded() middleware for parsing request bodies.
    • express-session middleware to manage user sessions.
    • passport middleware to initialize Passport.js and configure it to use sessions.
  3. Define the LocalStrategy for authenticating users with a username and password:

    javascriptCopy code

    passport.use(new LocalStrategy((username, password, done) => {  User.findOne({ username: username }, (err, user) => {    if (err) { return done(err); }    if (!user) { return done(null, false); }    bcrypt.compare(password, user.password, (err, res) => {      if (res) {        return done(null, user);      } else {        return done(null, false);      }    });  }); }));

    This sets up the LocalStrategy to find the user with the provided username, compare the provided password against the hashed password stored in the database using bcrypt.compare(), and call the done callback with the authenticated user object or false.

  4. Serialize and deserialize the user object to and from the session:

    javascriptCopy code

    passport.serializeUser((user, done) => {  done(null, user.id); }); passport.deserializeUser((id, done) => {  User.findById(id, (err, user) => {    done(err, user);  }); });

    This defines how Passport.js should store the user object in the session and retrieve it when needed.

  5. Protect the routes that require authentication using passport.authenticate():

    javascriptCopy code

    app.get('/profile', requireLogin, (req, res) => {  res.render('profile', { user: req.user }); }); function requireLogin(req, res, next) {  if (req.isAuthenticated()) {    next();  } else {    res.redirect('/login');  } }

    Here, we're using the requireLogin middleware to check if the user is authenticated using req.isAuthenticated() and redirect them to the login page if they're not.

35. Authentication Using Passport js

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

I am not able to access videos from second class and further. I have already completed first class

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support