I am using sails js v1.0. I am not getting way to how I call passport's authenticate function. Since req, res and next is not there in sails new controller type (action2).
I want to use a passport JWT based auth in sails js v1 app.
fn: async function (inputs, exits) {
passport.authenticate('jwt', {session: false}, (err, user, info) => {
})(inputs, exits);
}
my config/passport.js looks like
passport.use('jwt', new JWTStrategy(opts, (jwtPayload, done) => {
//find the user in db if needed. This functionality may be omitted if you store everything you'll need in JWT payload.
User.findOne({email: jwtPayload.email}).then(async (err, user) => {
if (err) {
return done(err, false);
}
if (!user) {
return done(null, false, {message: 'Incorrect email.'});
}
const validate = await sails.helpers.checkPassword(inputs.password, userRecord.password);
if(!validate) return done(null, false, { message : 'Wrong Password'});
return done(null, user, { message : 'Logged in Successfully Hola'});
}).catch(err => {
return done(err);
})
}));
In Sails.js document, the two ways are simply mentioned to access req
object.
this.req
I used this.req
and this.res
for passport.authenticate()
function, and it worked.
As you know, req.login()
is required for login, but in my case, this.req
didn't have login()
function derived by passport. So, I failed to use it in this way.
env
as the 3rd parameter.In the document, this method is an alternative, but, in my case, both are different.
I can access env.req.login()
.
So I think using env
as the 3rd parameter is better then this.req
.
fn: async function (inputs, exits, env) {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
// Write your codes. The below is an example.
if (err || !user) return exits.unauthorized();
env.req.login(user, function (err) {
if (err) exits.error(err);
return exits.success(user);
});
})(env.req, env.res);
}