Reputation: 59
I'm try to use passport with express, mongoose and jsonwebtoken, but got no response, when calling to /api. Please say what I'm missing.
index.js:
get passport and local strategy dependencies:
var passport = require("passport"),
LocalStrategy = require("passport-local").Strategy;
configure passport:
app.use(passport.initialize());
passport.use(new LocalStrategy({
usernameField: "email"
},
function (username, password, done) {
User.findOne({email: username}, function (err, user) {
if (err) return done(err);
if (!user) {
return done(null, false, {message: "User doesnt exist"});
}
if (!user.comparePassword(password)) {
return done(null, false, {message: "Wrong password!"});
}
return done(null, user);
});
})
);
and routes:
app.use("/api/login", require("./controllers/login"));
in my ./controllers/login.js
:
function loginHandler(req, res, next) {
passport.authenticate("local", function(err, user, info) {
if (err) return next(err);
...
var token = jwt.sign({name: user.email}, req.app.get("superSecret"),{expiresIn: 60000});
return res.json({token: token});
});
}
Upvotes: 0
Views: 282
Reputation: 1826
So this is quite a bit late, but I just spent two days struggling with this issue. The problem is very simple and not at all obvious:
function loginHandler(req, res, next) {
passport.authenticate("local", function(err, user, info) {
if (err) return next(err);
...
var token = jwt.sign({name: user.email}, req.app.get("superSecret"),{expiresIn: 60000});
return res.json({token: token});
})(req, res, next);
}
Note the (req, res, next)
added to the end of the passport call. This is necessary. Without this, the authenticate
function will not run.
Upvotes: 1