jaredhanson / passport-local

Username and password authentication strategy for Passport and Node.js.
https://www.passportjs.org/packages/passport-local/?utm_source=github&utm_medium=referral&utm_campaign=passport-local&utm_content=about
MIT License
2.73k stars 497 forks source link

set authentication on two entity of user #182

Open behzadnm99 opened 5 years ago

behzadnm99 commented 5 years ago

Environment

hello guys. i using passport-local for authentication and i want apply local auth strategy on two type of user : normal users and admin.

how to handle this senario with passport-local?

please help me. thank you.

usamamashkoor commented 4 years ago

@behzadnm99 did you find any solution for this? I am facing the same issue here.

martiendt commented 3 years ago

you can rename your strategy, for example :

passport.use("local-admin", new LocalStrategy(
  function(username, password, done) {
    UserAdmin.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));
passport.use("local-user", new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) { return done(null, false); }
      if (!user.verifyPassword(password)) { return done(null, false); }
      return done(null, user);
    });
  }
));

and in your route :

app.post('/admin/login', 
  passport.authenticate('local-admin', { failureRedirect: '/admin/login' }),
  function(req, res) {
    res.redirect('/admin');
  });

app.post('/login', 
  passport.authenticate('local-user', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });