I have authentication working with passport JWT, but I am having difficulty running a callback function/response, only if a user is authenticated. How can this be done?
In my routes:
import express from 'express';
import passport from '../../config/passport';
import memberInfoCtrl from '../controllers/memberInfo';
const router = express.Router();
router.route('/members')
.get(membersCtrl.tokenCheck, passport.authenticate('jwt', { session: false }), membersCtrl.doSomethingElse);
export default router;
I want membersCtrl.doSomethingElse
to be run if authentication is successful.
Here is my tokenCheck function:
function tokenCheck(req, res, next) {
const token = getToken(req.headers);
if (token) {
const decoded = jwt.decode(token, config.secret);
User.findOne({
email: decoded.email
}, (err, user) => {
if (err) throw err;
if (!user) {
return res.status(403).send({
success: false, msg: 'Authentication failed. User not found.'
});
}
// res.json({ success: true, msg: 'Welcome to the member area!' });
return next();
});
} else {
return res.status(403).send({ success: false, msg: 'No token provided.' });
}
}
Using res.json
in tokenCheck
works fine, but the doSomethingElse
function is not getting called afterwards.
I thought it's because we send a response like this:
res.json({ success: true, msg: 'Welcome to the member area!' });
Replacing the res.json
with return next();
returns the error:
Error: Unknown authentication strategy \"jwt\"
Why does this happen - how can I check for authentication before executing another function, for the same route?
I'm sure it's something silly i'm missing. Any help is appreciated!
Here is part of my main express script that initialises passport:
import passport from 'passport';
...
app.use(passport.initialize());
app.use('/api', routes);
...
Passport config:
const JwtStrategy = require('passport-jwt').Strategy;
import User from '../server/models/user';
import config from './env';
module.exports = (passport) => {
const opts = {};
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwtPayload, done) => {
User.findOne({ id: jwtPayload.id }, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};