70 lines
1.8 KiB
JavaScript
70 lines
1.8 KiB
JavaScript
const _ = require('lodash');
|
|
const passport = require('passport');
|
|
const { Strategy: LocalStrategy } = require('passport-local');
|
|
const { Strategy: JWTStrategy} = require('passport-jwt');
|
|
|
|
const models = require('./models');
|
|
const securityHelper = require('../helpers/security.helper');
|
|
|
|
|
|
passport.serializeUser((user, done) => {
|
|
done(null, user.id);
|
|
});
|
|
|
|
passport.deserializeUser((id, done) => {
|
|
models.User.findById(id, (err, user) => {
|
|
done(err, user);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Sign in using Email and Password.
|
|
*/
|
|
const localOptions = {
|
|
usernameField: 'email',
|
|
passwordField: 'password'
|
|
}
|
|
|
|
passport.use('local', new LocalStrategy(localOptions, async (email, password, done) => {
|
|
try {
|
|
const user = await models.User.findOne({
|
|
where: { email },
|
|
});
|
|
|
|
if (_.isNull(user)) {
|
|
return done(null, false, { message: 'User not found' })
|
|
} else {
|
|
const isPasswordValid = await user.comparePassword(password);
|
|
|
|
if (!isPasswordValid) {
|
|
return done(null, false, { message: 'Wrong Password' })
|
|
} else {
|
|
delete user.password;
|
|
return done(null, user, { message: 'Logged in Successfully' });
|
|
}
|
|
}
|
|
} catch (error) {
|
|
return done(error);
|
|
}
|
|
}));
|
|
|
|
// JWT
|
|
passport.use('jwt', new JWTStrategy(securityHelper.jwtOptions, async (jwtPayload, done) => {
|
|
try {
|
|
const user = await models.User.findOne({
|
|
attributes: { exclude: [ 'password' ] },
|
|
where: { id: jwtPayload.id },
|
|
raw: true
|
|
});
|
|
|
|
if (_.isNull(user)) {
|
|
return done(null, false, { message: 'User not found' })
|
|
} else {
|
|
return done(null, user, { message: 'User found' });
|
|
}
|
|
} catch (error) {
|
|
return done(error);
|
|
}
|
|
}));
|
|
|