PassportJS - Using Multiple Folders in an Express Application

Suppose I need two different passports inside the same express application (for example, user and room). Therefore, I define two separate vars:

var passport = require('passport'); var roomPassport = require('passport'); 

then I initialize them with separate passport strategies:

 require('./config/passport')(passport); // pass passport for configuration require('./config/roompassport')(roomPassport); // pass passport for configuration 

The final step is to install them as Express middleware:

 // required for passport application.use(session({ secret: 'ilovepassport;-)' })); // session secret application.use(passport.initialize({ userProperty: "user" })); application.use(passport.session()); // persistent login sessions application.use(roomPassport.initialize({ userProperty: "room" })); application.use(roomPassport.session()); // persistent login sessions application.use(flash()); // use connect-flash for flash messages stored in session` 

however, if I did it like this, in fact roomPassport redefines the passport and instead of two objects - req.user and req.room, I have only one req.room, but it is initialized with user data.

It is important to note that each passport (user or room) can authenticate independently of each other, that is, there is a scenario in which both req.user and req.room objects must exist.

How to resolve this?

EDIT 1

Well, after a few hours it seems that although I have to separate passport objects, after calling application.use(roomPassport.initialize({ userProperty: "room" })); everything becomes messy - and this is because the req.login() method works with the last passport attached. Therefore, instead of calling the correct passport.serializeUser method, it calls the roomPassport.serializeUser method.

My next question is how to make req.login() to call the correct method?

+6
source share
2 answers

The problem is that the passport module exports an instance of the Passport object when you need it. And since this object is cached by node when you need it, you get the same object every time.

Fortunately, the passport module also gives you a link to the class , that is, you can do it.

 var Passport = require('passport').Passport, passport = new Passport(), roomPassport = new Passport(); 

You should now have two completely different passport objects.

+10
source

Source: https://habr.com/ru/post/1202796/


All Articles