Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false, {message: 'foo'});
// or you could create a new account
}
});
}));
opts.jwtFromRequest = ExtractJwt.fromHeader('x-api-key');
opts.jwtFromRequest = ExtractJwt.fromBodyField('field_name');
opts.jwtFromRequest = ExtractJwt.fromUrlQueryParameter('param_name');
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('param_name');
opts.jwtFromRequest = ExtractJwt.fromExtractors([ExtractJwt.fromHeader('x-api-key'), ExtractJwt.fromBodyField('field_name'), ExtractJwt.fromUrlQueryParameter('param_name')]);
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.jwtFromRequest = (req: Request) => { return req.query.token; };
opts.secretOrKey = new Buffer('secret');
declare function findUser(condition: {id: string}, callback: (error: any, user :any) => void): void;
}))
*/
let EFruitUnavail = new Error('fruitmix unavailable')
// passport.use(new BasicStrategy(Fruit.verifyUserPassword.bind(Fruit)))
passport.use(new BasicStrategy((userUUID, password, done) => {
let fruit = getFruit()
if (!fruit) return done(EFruitUnavail)
fruit.verifyUserPassword(userUUID, password, done)
}))
passport.use(new JwtStrategy({
secretOrKey: secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('jwt')
},
(jwt_payload, done) => {
let fruit = getFruit()
if (!fruit) return done(EFruitUnavail, false)
let user = fruit.findUserByUUID(jwt_payload.uuid)
user ? (user.disabled ? done(null, false) : done(null, user)) : done(null, false)
}))
module.exports = {
init: () => passport.initialize(),
basic: () => passport.authenticate('basic', { session: false }),
jwt: () => passport.authenticate('jwt', { session: false })
}
.then(user => {
// koa-passport returns false if object is not formatted as {username, password}
if (user === false)
throw new Error('invalid POST data, expected {username, password[, remember]}');
return user;
})
.catch(error => ctx.throw(400, error))
.then(user => {
ctx.body = this.getToken(user, ctx.request.body.remember);
})
.catch(error => ctx.throw(422, error))
.then(next);
this.passport.use(new JwtStrategy(
{
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),
secretOrKey: secret
}, (user, done) => {
// Check whether payload is user
if (!user.id)
done(new Error('invalid token'));
else
done(null, user);
}));
this.authenticateJwt = (ctx, next) => new Promise((resolve, reject) =>
this.passport.authenticate('jwt',
{session: false}, (err, user) => resolve(user))(ctx, () => {})
.catch(reject))
// TODO next line connects to DB, token already embodies roles,
// change when access token is implemented
.then(this.appendRoles)
}
// Attach the original token onto the payload.
return callback(false, { token, jwt });
});
};
// Extract the JWT from the 'Authorization' header with the 'Bearer' scheme.
passport.use(
new JwtStrategy(
{
// Prepare the extractor from the header.
jwtFromRequest: ExtractJwt.fromExtractors([
cookieExtractor,
ExtractJwt.fromUrlQueryParameter('access_token'),
ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
]),
// Use the secret passed in which is loaded from the environment. This can be
// a certificate (loaded) or a HMAC key.
secretOrKey: jwt,
// Verify the issuer.
issuer: JWT_ISSUER,
// Verify the audience.
audience: JWT_AUDIENCE,
// Enable only the HS256 algorithm.
algorithms: [JWT_ALG],
// Pass the request object back to the callback so we can attach the JWT to
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// JWT
const jwtOpts = {};
jwtOpts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('Bearer');
jwtOpts.secretOrKey = config.jwt.secret;
passport.use(
new StrategyJwt(jwtOpts, function(payload, done) {
User.findOne({ _id: payload.uid })
.select('-password -services -token')
.exec(function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
})
if (!user) return done({message : 'User not found.'});
if (!user.validPassword(password)) return done({message : 'Wrong password.'});
return done(null, user);
});
}));
// =========================================================================
// JWT AUTH ================================================================
// =========================================================================
var opts = {
secretOrKey : config.secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer')
};
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
var strategy = jwt_payload.strategy
, query = {};
query[strategy + '.email'] = jwt_payload[strategy].email;
User.findOne(query, function(err, user) {
if (err || !user) return done(err || {message : 'Unable to authenticate.'}, false);
switch (strategy) {
case 'facebook':
if (!user.validFacebook(jwt_payload[strategy].token)) return done({message : 'Wrong facebook token.'}, false);
break;
default:
if (!user.validHash(jwt_payload[strategy].password)) return done({message : 'Wrong password.'}, false);
}
done (null, user);
return done(null, false);
}
return done(null, user);
} catch (e) {
return done(e, false);
}
},
);
/**
* JWT Strategy Auth
*/
const jwtOpts = {
// Telling Passport to check authorization headers for JWT
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('JWT'),
// Telling Passport where to find the secret
secretOrKey: constants.JWT_SECRET,
};
const jwtLogin = new JWTStrategy(jwtOpts, async (payload, done) => {
try {
const user = await User.findById(payload._id);
if (!user) {
return done(null, false);
}
return done(null, user);
} catch (e) {
return done(e, false);
}
console.log('passwords do not match');
return done(null, false, { message: 'passwords do not match' });
}
console.log('user found & authenticated');
return done(null, user);
});
});
} catch (err) {
done(err);
}
},
),
);
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
secretOrKey: jwtSecret.secret,
};
passport.use(
'jwt',
new JWTstrategy(opts, (jwt_payload, done) => {
try {
User.findOne({
where: {
id: jwt_payload.id,
},
}).then(user => {
if (user) {
console.log('user found in db in passport');
done(null, user);
} else {
function getExtractor(extractor: string, param: string) {
switch(extractor) {
case 'header': return ExtractJwt.fromHeader(param);
case 'queryParam': return ExtractJwt.fromUrlQueryParameter(param);
case 'authHeader': return ExtractJwt.fromAuthHeaderWithScheme(param);
case 'bodyField': return ExtractJwt.fromBodyField(param);
case 'cookie': return (req)=>{
let token = null;
if (req && req.cookies)
{
token = req.cookies[param];
}
return token;
};
}
return ExtractJwt.fromAuthHeader();
}
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.data._id, (err, user) => {
if(err) {
return done(err, false);
}
if(user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}