Junior — Middle
Have you used the Passport.js library for authentication in Node.js projects?
sobes.tech AI
Answer from AI
Yes, I have used Passport.js for authentication in Node.js projects. This library provides a convenient and flexible way to integrate various authentication strategies, such as local (login/password), OAuth (Google, Facebook), JWT, and others.
Example of using the local strategy with Passport.js:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Incorrect username.' }); }
if (!user.verifyPassword(password)) { return done(null, false, { message: 'Incorrect password.' }); }
return done(null, user);
});
}
));
// In route
app.post('/login', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}));
Passport.js simplifies session management and integration with different authentication methods, making it a popular choice for Node.js applications.