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

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

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

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?