passport / discuss

A forum for discussing topics related to the usage of Passport.js.
1 stars 0 forks source link

passport.authorize() clearing req.user with multiple (same) strategies #71

Open timholmez opened 1 year ago

timholmez commented 1 year ago

I need two instances of a passport local strategy ("localA" and "localB"), one instance of this authenticates against a collection "colA" in "DbA" and is used in one route sequence (Route A), the other instance authenticates against another collection (ColB) in "DbB" and is used in a second route sequence (Route B).

In both cases, access to "req.user" is needed. In the first route, "req.user" has its expected defined value, however, in the second route, "req.user" is undefined. Here is an extract of what I believe to be the relevant code:

const userA = DbA.model(`colA`, userASchema);
passport.use(`localA`, new passportLocalStrategy({usernameField: `email`, passwordField: `password`}, userA.authenticate()));
passport.serializeUser(userA.serializeUser());
passport.deserializeUser(userA.deserializeUser());

const userB = DbB.model(`colB`, userBSchema);
passport.use(`localB`, new passportLocalStrategy({usernameField: `email`, passwordField: `password`}, userB.authenticate()));
passport.serializeUser(userB.serializeUser());
passport.deserializeUser(userB.deserializeUser());

//Route A
app.post('/routeA', passport.authenticate(`localA`), (req, res) => {
    res.redirect(`/routeAA`);  
});

app.get('/routeAA', function (req, res) {
    res.render('routeA.ejs');
});

//Route B
app.post('/routeB', passport.authenticate(`localB`), (req, res) => {
     @res.redirect(`/routeBB`);
});

app.get('/routeBB', function (req, res) {
    res.render('routeB.ejs');
});

This is not a new issue, as evidenced by this post: [(https://github.com/jaredhanson/passport/issues/803)]

... which not only states the issue but also states a couple of workarounds, one from @AlanJereb and the other from @nathan6am, neither of which (due to my lack of knowledge and understanding) I've been able to implement. Would either @AlanJereb or @nathan6am or anyone else from the community be willing to add more substance / leave a few more breadcrumbs?

Many thanks, Tim.