If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To set up Passport.js for authentication in your application, follow these steps:
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.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.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
.
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.
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.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.