After researching extensively, I am confident that the issue I'm facing is not a known bug. I am currently utilizing passport JS with the local strategy in my login route, employing a custom callback and invoking req.login once I confirm the user's existence. This approach is in line with the documentation's guidance:
Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response
Despite following the recommendations, I continually encounter an error indicating that req.logIn is undefined (Note that you can call either reg.login or req.logIn as they are aliased. I've also tried both). Strangely, my IDE is recognizing the typescript definitions, and I can verify the presence of the req.logIn function in the compiled app.js output. This discrepancy is perplexing.
app.ts
const localStrategy = LocalStrategy.Strategy;
passport.use(new localStrategy({
usernameField: 'email',
passwordField: 'password'
},
async function (email, password, done) {
const member: IMember | null = await MemberModel.findOne({where: {email: email}});
if (member) {
bcrypt.compare(password, member.hash, function (err, res) {
if (err) return done(null, false, {message: err.message});
if (!res) {
return done(null, false, {message: 'Incorrect password.'});
} else {
return done(null, member);
}
});
}
else {
return done(null, false, {message: 'Couldn\'t find a matching user.'});
}
}
));
passport.serializeUser(function(user: IMember, done) {
done(null, user.id);
});
passport.deserializeUser(async function(id: string[], done) {
const user: IMember | null = await MemberModel.findOne({where: {id: id}});
if (user) {
done(null, user);
}
});
// Initialize the app
const app: e.Express = express();
app.use(bodyParser.json());
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, options) => {
if (err) {
return next(err);
}
if (!user) {
return next(options.message);
}
req.logIn(user, ((err) => { // <-- Errors on this line
if (err) {
return next(err); }
return res.redirect('/users/' + user.username);
}));
})(req, res, next);
});
Versions
"express": "^4.17.1",
"express-session": "^1.17.0",
"passport": "^0.4.1",
"passport-local": "^1.0.0",
"typescript": "^3.7.4",
"@types/express-session": "^1.15.16",
"@types/passport": "^1.0.2",
"@types/passport-local": "^1.0.33",
"@types/express": "^4.17.2",