Support for multiple user types by Passport-local

2019-04-03 00:50发布

I wanted two types of users logging in (User, Client). How exactly can I create localStrategies, serialize and deserialize user for both types in my app.js I have two separate schemas, both using the PassportLocalMongoose plugin.

I currently configuraing my passport like below,

var User = require('./models/User');
var Client= require('./models/Client');
passport.use(new LocalStrategy(User.authenticate(), Client.authenticate()));
passport.serializeUser(User.serializeUser(), Client.serializeUser());
passport.deserializeUser(User.deserializeUser(), Client.deserializeUser());

The problem lies when I try to register. Registering as a User works, but as a client shows "Unauthorized" error. How can I fix this problem?

2条回答
Fickle 薄情
2楼-- · 2019-04-03 01:09

You can make role in mongoose schema and give it to user or client. Based on the role you can do the authentication

查看更多
Lonely孤独者°
3楼-- · 2019-04-03 01:14

After going through the documentation of passport.js (kudos to Jared), I understood that I was doing almost everything wrong.

  1. Created two localStrategies

    passport.use('userLocal', new LocalStrategy(User.authenticate())); passport.use('clientLocal', new LocalStrategy(Client.authenticate()));

and to authenticate,

passport.authenticate('userLocal')(req, res, function () {
    res.redirect('/profile');
  });
and
passport.authenticate('clientLocal')(req, res, function () {
    res.redirect('/client');
  });
  1. Used passport module (l=not using the passport-local-mongoose module) for serializeUser and deseriealizeUser.

    passport.serializeUser(function(user, done) { done(null, user); });

    passport.deserializeUser(function(user, done) { if(user!=null) done(null,user); });

The whole user schema (object) is now stored in the request and can be accessed through any of your routes.

Hope it helps out others with a similar issue.

查看更多
登录 后发表回答