Local authentication
suggest changeThe passport-local module is used to implement a local authentication.
This module lets you authenticate using a username and password in your Node.js applications.
Registering the user :
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
// A named strategy is used because two local strategies are registered:
// one for registration and one for sign-in.
passport.use('localSignup', new LocalStrategy({
// Override the default field names, 'username' and 'password'
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // pass the request to the verify callback
},
function(req, email, password, done) {
findUserByEmail(email, function(err, user) {
if (err) return done(err);
// If the email already exists, abort registration
if (user) return done(null, false);
// createUser must store a hash, not the raw password
let newUser = createUser(email, password);
newUser.save(function(err) {
if (err) return done(err);
return done(null, newUser);
});
});
}));
Logging in the user :
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
passport.use('localSignin', new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
},
function(email, password, done) {
findUserByEmail(email, function(err, user) {
if (err) return done(err);
// Custom info can explain why authentication failed
if (!user)
return done(null, false, {message: 'This e-mail address is not associated with any account.'});
// Compare the submitted password with the stored hash
if (!isPasswordValid(user, password)) return done(null, false);
return done(null, user);
});
}));
Creating routes :
// ...
// express-session must be registered before passport.session()
app.use(passport.initialize());
app.use(passport.session());
// Sign-in route
app.post('/login', passport.authenticate('localSignin', {
successRedirect: '/me',
failureRedirect: '/login'
}));
// Sign-up route
app.post('/register', passport.authenticate('localSignup', {
successRedirect: '/',
failureRedirect: '/signup'
}));
// Passport 0.6 and later require a callback
app.get('/logout', function(req, res, next) {
req.logout(function(err) {
if (err) return next(err);
res.redirect('/');
});
});
app.listen(3000);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents