I'm pretty sure this is not a bug since googling it hasn't turned anything up.
I'm using passport JS with the local strategy. On my login route I'm using a custom callback and calling req.login once I have determined the user exists because the documentation says:
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
However, it keeps saying that reg.logIn is undefined (Note that you can call either reg.login or req.logIn as they are aliased. I've also tried both). My IDE is picking up the typescript definitions and I can see the req.logIn function defined in the output of the compiled app.js file so I'm not sure why I'm getting this error.
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);
});
"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",
You need to initiate passport middleware before the routes registration:
app.use(passport.initialize());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With