NodeJS, Passport: how to change user's password by admin - node.js

I start to make admin panel for modify users. I want to have ability to change users passwords by admin. For authentication I use passport. The I change user's password - the data is saving to mongo, but after that, user can't logIn to site.
Please, help.
My Passport configuration:
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id)
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use('local-login', new LocalStrategy({
usernameField : 'email',
passwordField : 'password_first',
passReqToCallback : true
},
function(req, email, password, done) {
User.findOne({ 'email' : email }, function(err, user) {
if (err)
return done(err);
if (!user)
return done(null, false, function(req, res){
res.send({error: true})
});
if (!user.isAuthenticated )
return done(null, false, function(req, res){
res.send({error: true})
});
if (!user.validPassword(password))
return done(null, false, function(req, res){
res.send({error: true})
});
if(user){
return done(null, user);
}
});
}));
User model:
var userSchema = mongoose.Schema({
date : Date,
role : String,
newRole : { type: mongoose.Schema.Types.ObjectId, ref: 'newRole'},
authToken : { type: String, required : true, unique:true },
isAuthenticated : { type: Boolean, required : true },
username : String,
email : String,
password_first : String,
firstName : String,
lastName : String,
address : String,
phone : String,
resetPasswordToken : String,
resetPasswordExpires: Date });
Methods:
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password_first);
};
var User = mongoose.model('User', userSchema);
module.exports = User;
And finally:
exports.changeByAdmin = function (req, res, next) {
User.findById({ _id : req.params.id }, function(err, updateUser) {
if(err) return next(err);
if (!updateUser) return next();
updateUser.email = req.body.email;
updateUser.firstName = req.body.firstName;
updateUser.lastName = req.body.lastName;
updateUser.address = req.body.address;
updateUser.phone = req.body.phone;
updateUser.password_first = updateUser.generateHash(req.body.password_first);
updateUser.save(function(err, updateUser) {
if(err) return next(err);
if(!updateUser) return next();
res.send({ success: true });
});
});
};
If I change only email of user, the user can login with new email and old password, but if I change password - user can't login. Please, advise the solution of this problem. Thank you.

Related

How to change collection name in mongoose.model?

Am new in Nodejs, Am trying to create user login system with mongoDB and passportjs. Here i want to change collection name.
i refer this video here
This is my code:
Database connection js
config/database.js
module.exports = {
database : 'mongodb://localhost:27017/my_first_project',
secret : 'Mysecret'
}
models/admin.js
const mongoose = require('mongoose');
let AdminSchema = mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
username:{
type: String,
required: true
},
password:{
type: String,
required: true
},
created_on:{
type: Date,
default: Date.now
},
status:{
type: Number,
required: true,
validate : {
validator : Number.isInteger,
message : '{VALUE} is not an integer value'
}
}
});
const Admin = module.exports = mongoose.model('User', AdminSchema);
config/passport.js
const LocalStorage = require('passport-local').Strategy;
const User = require('../models/admin');
const config = require('../config/database');
const bcrypt = require('bcryptjs');
module.exports = function(passport){
//Local Strategy
passport.use(new LocalStorage(function(username, password, done){
//Check username
let query = {username:username};
console.log(query);
User.findOne(query, function(err, user){
console.log(user);
if(err) throw err;
if(!user)
{
return done(null, false, {message: 'No user found'});
}
//check password
bcrypt.compare(password, user.password, function(err, isMatch){
if(err) throw err;
if(isMatch){
return done(null, user);
}else{
return done(null, false, {message: 'Wrong password'});
}
});
});
}));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
}
This is my database structure
When i user correct username and password for login passportjs shows null.
Need to change collection name as admin.
I don't know how to ask this question. If am asking wrong sorry for all.
You can use this structure.
API structure of mongoose.model is this:
Mongoose#model(name, [schema], [collection], [skipInit])
which means
mongoose.model('User', AdminSchema, 'admin');
//Here 3rd argument 'admin': as collection name
You can do with this too
let AdminSchema = mongoose.Schema({
username : String,
password : String.
.......
}, { collection: 'admin' });
See this link from the Mongoose documentation.

Passport not logging in | Think due to strategy's

I have a pretty simple application that is just an auth service and a profile page with a logout button at this point. I am trying to signup a user, who is redirected to /profile and then I logout. All of this works fine. I also have a verification email in there too but that is currently besides the point.
My issue is that when I go to log into the site it gives me no error messages, nothing, just redirects me to /login which is what my passport strategy's meant to do if there is an error.
Can anyone spot an error in my code that would cause me not to log into the site? I have included what I think are the important parts of my application.
app.js
// PASSPORT CONFIGURATION
require('./controllers/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
require('./routes/index.js')(app, passport);
passport.js login strategy
passport.use('login', new LocalStrategy({
usernameField: 'email',
passReqToCallback : true
},
function(req, email, password, done) {
User.findOne({ 'email' : email },
function(err, user) {
if (err) return done(err);
if (!user){
return done(null, false, req.flash('error', 'User not found'));
}
user.comparePassword(password, function(err, isMatch) {
if(err){
console.log(err);
}
if (isMatch) {
// Make sure the user has been verified
if (!user.isVerified) return done (null, false, req.flash('error', 'Your account has not been verified.' ));
var time = 14 * 24 * 3600000;
req.session.cookie.maxAge = time; //2 weeks
req.session.cookie.expires = new Date(Date.now() + time);
req.session.touch();
return done(null, user, req.flash('success', 'Successfully logged in.'));
} else {
return done(null, false, req.flash('error', 'Invalid Password'));
}
});
}
);
})
);
login route
app.post('/login', passport.authenticate('login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
}));
user.js model
var UserSchema = new mongoose.Schema({
email: String,
password: String,
role: String,
avatar: String,
isVerified: { type: Boolean, default: false },
resetPasswordToken: String,
resetPasswordExpires: Date
});
UserSchema.plugin(passportLocalMongoose, { usernameField : 'email' });
UserSchema.plugin(timestamps);
UserSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, null, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
I am not sure how this solved it but it did... I added in my auth middleware that checks if a user should be able to access the page or not and now I can log in. Here is my middleware that checks it.
middleware
exports.isUnauthenticated = function(req, res, next) {
if (!req.isAuthenticated()){
return next();
}
res.redirect('/');
};
Then I just required it and updated my post route to be
post login route
app.post('/login', isUnauthenticated, passport.authenticate('login', {
successRedirect : '/profile',
failureRedirect : '/login',
failureFlash : true
}));

Node JS Authentications with passport-jwt unauthorized

Im trying to setup my Node JS API.
I have a User model :
// Dependencies
var restful = require('node-restful');
var mongoose = restful.mongoose;
var bcrypt = require('bcrypt');
// Schema
var userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true},
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: true},
},
{
timestamps: true
});
// Saves the user's password hashed
userSchema.pre('save', function (next) {
var user = this;
if (this.isModified('password') || this.isNew) {
bcrypt.genSalt(10, function (err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
} else {
return next();
}
});
// Use bcrypt to compare passwords
userSchema.methods.comparePassword = function(pw, cb) {
bcrypt.compare(pw, this.password, function(err, isMatch) {
if (err) {
return cb(err);
}
cb(null, isMatch);
});
};
module.exports = restful.model('Users', userSchema);
I want to use passport with jwt for authentication :
// Dependencies
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var config = require('../config/database');
// Load models
var User = require('../models/user');
// Logique d'authentification JWT
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('JWT');
opts.secretOrKey = config.secret;
opts.audience = 'localhost';
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findById(jwt_payload._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
Company.findById(jwt_payload._id, function(err, company) {
if (err) {
return done(err, false);
}
if (company) {
done(null, company);
} else {
done(null, false)
}
});
}));
};
And my route for authentication :
// User
router.post('/users/login', (req, res) => {
User.findOne({
email: req.body.email
}, (err, user) => {
if (err) throw err;
if (!user) {
res.json({success: false, message: 'Authentication failed. User not found.'});
} else {
// Check if passwords matches
user.comparePassword(req.body.password, (err, isMatch) => {
if (isMatch && !err) {
// Create token if the password matched and no error was thrown
var token = jwt.sign(user, config.secret, {
expiresIn: 10080 // in seconds
});
res.json({success: true, token: 'JWT ' + token, user: {
id: user._id,
username: user.username,
email: user.email
}});
} else {
res.json({success: false, message: 'Authentication failed. Passwords did not match.'});
}
});
}
});
});
Everything work great on postman.
The token is correctly generated and signed with user's informations.
But i have a problem with the authentication on a protected route :
router.get('/users/profile', passport.authenticate('jwt', { session: false }), function(req, res) {
res.send('It worked! User id is: ' + req.user._id + '.');
});
Everytime, it gives me an "Unauthorized 401" Error.
I really dont know where is the problem, i think the problem is around jwtFromRequest, i also tried with Bearer but it also doesn't work...
I think a good option to avoid this kind of problems is to start from a base project that uses this authentication strategy, and after you have that working, modify it with your functionality.
Here you have an example with jwt authentication strategy and Refresh token implementation: https://solidgeargroup.com/refresh-token-autenticacion-jwt-implementacion-nodejs?lang=es

Facebook Passport Strategy returning 500 error

I am trying to make a Logged in or Signed In user to connect their account with facebook using passport.js facebook strategy, and save their profile photo, id, gender, timeline cover and token according the userSchema (as made in user.jsmodel shown below.
I tried many combinations but still either getting 500error from facebook, or if showing facebook auth, facebook can't return (the code combination, I tried) and save the object.
PS : I had entered correct callback URL in facebook
PPS: Please refer my UPDATED routes.js and updated passport.js below.
This is my routes.js file:
app.get('/auth/connect/facebook', passport.authenticate('facebook-connect', { authType: 'rerequest', scope: ['id', 'cover', 'gender', 'photos'] }));
app.get('/auth/connect/facebook/callback',
passport.authenticate('facebook-connect', {
successRedirect: '/profile/configure',
failureRedirect: '/profile/congigure'
// failureFlash: true
}));
My passport.js file of facebook-connect:
passport.use('facebook-connect', new FacebookStrategy({
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL,
profileFields: ['id', 'cover', 'gender', 'photos'],
enableProof: true
},
function(token, refreshToken, profile, cb) {
process.nextTick(function() {
User.findOne({ 'local.facebook.id': profile.id }, function(err, user) {
if (err)
return cb(err);
if (user) {
return cb(null, false, req.flash('fbflash', 'This facebook user is already connected with an account at eBird.'));
} else {
user.local.facebook.id = profile.id;
user.local.facebook.token = token;
user.local.profile.gender = profile.gender;
user.local.profile.herobg = profile.cover;
user.local.profile.dp = user.local.profile.dp ? user.local.profile.dp : profile.photos[0].value;
if (user.local.profile.dp == '') {
if (user.local.profile.gender == 'male') {
user.local.profile.dp = 'http://res.cloudinary.com/pinterested222/image/upload/v1487659283/an-av-3_jxrhwc.png';
}
if (user.local.profile.gender == 'female') {
user.local.profile.dp = 'http://res.cloudinary.com/pinterested222/image/upload/v1487770814/female-avatar_vvyvtj.png';
}
}
user.save(function(err) {
if (err)
throw err;
return cb(null, user);
});
}
});
});
}));
My user.js model:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var DateOnly = require('mongoose-dateonly')(mongoose);
var shortid = require('shortid');
var uniqueValidator = require('mongoose-unique-validator');
var userSchema = mongoose.Schema({
_id: {
type: String,
default: shortid.generate
},
local: {
email: String,
username: { type: String, unique: true },
firstname: String,
surname: String,
name: String,
role: { type: String, default: 'user' },
department: String,
pno: Number,
password: String,
verified: { type: Boolean, default: false },
profile: {
dp: String,
createdAt: { type: Date, default: Date.now },
herobg: String,
location: String,
website: String,
gender: String,
birthday: DateOnly,
lastlogin: { type: Date },
notifications: {
name: String,
namedp: String,
type: { type: String },
date: { type: Date, default: Date.now },
read: { type: Boolean, default: false }
}
},
facebook: {
id: String,
token: String
}
}
});
userSchema.plugin(uniqueValidator, { message: '{Path}:{VALUE} is already taken.' });
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.local.password);
};
// userSchema.methods.bellTimesAgo = function(date);
module.exports = mongoose.model('User', userSchema);
The error, it's throwing me:
The www.facebook.com page isn’t working
www.facebook.com is currently unable to handle this request.
HTTP ERROR 500
Any help would be appreciated,
Thanks.
UPDATE - 1
I read (& from passportjs docs) about passport.authorize() and updated my passport.js file accordig to passport.authorize() and also updated my routes, but still the same problem.
Here is my updated passport.js:
// Facebook Strategy Updated using authorize
passport.use(new FacebookStrategy({
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
callbackURL: configAuth.facebookAuth.callbackURL,
// profileFields: ['id', 'cover', 'gender', 'photos'],
// enableProof: true,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
process.nextTick(function() {
if (!req.user) {
User.findOne({ 'local.facebook.id': profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
return done(null, false, req.flash('fbflash', 'This facebook user is already connected with an account at eBird.'));
} else {
user.local.facebook.id = profile.id;
user.local.facebook.token = accessToken;
user.local.profile.gender = profile.gender;
user.local.profile.herobg = profile.cover;
user.local.profile.dp = user.local.profile.dp ? user.local.profile.dp : profile.photos[0].value;
if (user.local.profile.dp == '') {
if (user.local.profile.gender == 'male') {
user.local.profile.dp = 'http://res.cloudinary.com/pinterested222/image/upload/v1487659283/an-av-3_jxrhwc.png';
}
if (user.local.profile.gender == 'female') {
user.local.profile.dp = 'http://res.cloudinary.com/pinterested222/image/upload/v1487770814/female-avatar_vvyvtj.png';
}
}
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
});
} else {
var user = req.user;
user.local.facebook.id = profile.id;
user.local.facebook.token = accessToken;
user.local.profile.gender = profile.gender;
user.local.profile.herobg = profile.cover;
user.local.profile.dp = user.local.profile.dp ? user.local.profile.dp : profile.photos[0].value;
if (user.local.profile.dp == '') {
if (user.local.profile.gender == 'male') {
user.local.profile.dp = 'http://res.cloudinary.com/pinterested222/image/upload/v1487659283/an-av-3_jxrhwc.png';
}
if (user.local.profile.gender == 'female') {
user.local.profile.dp = 'http://res.cloudinary.com/pinterested222/image/upload/v1487770814/female-avatar_vvyvtj.png';
}
}
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
});
}));
Here is my updated routes.js:
app.get('/auth/connect/facebook', passport.authorize('facebook', { authType: 'rerequest', scope: ['id', 'cover', 'gender', 'photos'] }));
app.get('/auth/connect/facebook/callback',
passport.authorize('facebook', {
successRedirect: '/profile/configure',
failureRedirect: '/profile/configure'
// failureFlash: true
})
);
Here is the snapshot of my app callback settings from Facebook:
Snapshot of the error, facebook keeps throwing in:
Passport.js documentation said:
Values for the scope option are provider-specific. Consult the provider's documentation for details regarding supported scopes.
If you check allowed permissions in Facebook documentation, you will not find such permissions as 'id', 'cover', 'gender', 'photos'. These items are part of a person's public profile.
So, you should change scope in routes.js from:
scope: ['id', 'cover', 'gender', 'photos']
to:
scope: ['public_profile']
or don't specify scope, because public_profile is default facebook permission.
P.S. I told about your "update 1" code version.
Taking inspiration from #anton-novik, I fixed the bug.
The problem was in my routes.js file. First have a look at my routes.js file above, and then follow the code below:
app.get('/auth/connect/facebook', ensureLoggedIn('/login'), passport.authorize('facebook', { authType: 'rerequest' }));
app.get('/auth/connect/facebook/callback',
passport.authenticate('facebook', {
successRedirect: '/profile',
failureRedirect: '/profile/settings',
failureFlash: true
})
);
There was no need of scope for the request I was making was already approved by Facebook for every app.
And then updated my passport.js file to look like this:
// // Facebook Strategy
passport.use(new FacebookStrategy({
clientID: configAuth.facebookAuth.clientID,
clientSecret: configAuth.facebookAuth.clientSecret,
profileFields: ['id', 'picture.type(large)', 'gender', 'cover'],
callbackURL: configAuth.facebookAuth.callbackURL,
passReqToCallback: true
},
function(req, accessToken, refreshToken, profile, done) {
process.nextTick(function() {
// User is not logged in yet
if (!req.user) {
User.findOne({ 'local.facebook.id': profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
if (!user.facebook.token) {
user.facebook.token = accessToken;
user.facebook.name = profile.displayName;
user.facebook.email = profile.emails[0].value;
user.save(function(err) {
if (err) throw err;
return done(null, user);
});
}
return done(null, user);
} else {
// User should be created here
// and saved to mongoose
}
});
}
//else user is logged in and needs to be merged
else {
console.log(profile); //display the returned json from fb
// Connect the user and save the details, since the user already exsists
var user = req.user;
user.local.facebook.id = profile.id;
user.local.facebook.token = accessToken;
user.local.profile.gender = profile.gender;
user.local.profile.dp = profile.photos[0].value;
user.local.profile.herobg = profile._json.cover.source;
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
});
}));
Hope, it may help someone. :)

PassportJS Not Recognizing Password Change

I created added some password reset functionality to my sign up flow that allows users to change their password, but when a user resets their password, they are unable to login with the new password and I receive a consoled Server Error. I'm wondering if this has to do with updating the user password outside of the passportjs logic or maybe because my password isn't hashed on the update?
Here is the console log:
GET /login 200 9.507 ms - 1793
GET /stylesheets/styles.css 304 1.093 ms - -
Database query triggered
Executing (default): SELECT `user_id`, `first_name` AS `firstName`, `last_name` AS `lastName`, `email`, `password`, `organization_id` AS `organizationId`, `reset_password_token` AS `resetPasswordToken`, `reset_password_expires` AS `resetPasswordExpires`, `createdAt`, `updatedAt` FROM `user` AS `user` WHERE `user`.`email` = 'test#gmail.com' LIMIT 1;
Server Error
POST /login 302 16.169 ms - 56
GET /login 200 10.926 ms - 1862
Here is my password update route:
var express = require('express');
var siteRoutes = express.Router();
var path = require('path');
var async = require('async');
var crypto = require('crypto');
var nodemailer = require('nodemailer');
var sgTransport = require('nodemailer-sendgrid-transport');
var moment = require('moment');
var url = require('url');
var passport = require(path.resolve(__dirname, '..', '..','./config/passport.js'));
var models = require('../models/db-index');
/*==== /RESET ====*/
siteRoutes.route('/reset/:token')
.get(function(req, res){
var urlPath = url.parse(req.url).pathname.split('/');
var urlToken = urlPath[2];
console.log(urlToken);
models.User.findOne({
where: {
resetPasswordToken: req.params.token,
resetPasswordExpires: {
$gt: moment().format('YYYY-MM-DD HH:mm:ss')
}
}
}).then(function(){
res.render('pages/app/reset-password.hbs',{
urlToken: urlToken
});
})
})
.post(function(req, res){
async.waterfall([
function(done){
models.User.update({
password: req.body.password,
resetPasswordToken: null,
resetPasswordExpires: null
}, { where: {
resetPasswordToken: req.body.token,
resetPasswordExpires: {
$gt: moment().format('YYYY-MM-DD HH:mm:ss')
}
}})
// Nodemailer
var transporter = nodemailer.createTransport(sgTransport(options));
var mailOptions = {
from: '"Tester" <test#test.com',
to: 'test#gmail.com', //Replace with Email
subject: 'Your password has been changed',
text: 'Hello,\n\n' +
'This is a confirmation that the password for your account ' + 'test#gmail.com' + ' has just been changed.\n'
};
transporter.sendMail(mailOptions, function(error, info){
if(error){
return console.log(error + 'During Post');
}
console.log('Message sent: ' + info.response);
})
}
])
res.redirect('/login');
});
Here is my login routing:
/*==== Login ====*/
siteRoutes.route('/login')
.get(function(req, res){
res.render('pages/site/login.hbs',{
error: req.flash('error')
});
})
.post(passport.authenticate('local', {
successRedirect: '/app',
failureRedirect: '/login',
failureFlash: 'Invalid email or password.'
}));
Here is the user model:
var bcrypt = require('bcrypt-nodejs');
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('user', {
user_id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
firstName: {
type: DataTypes.STRING,
field: 'first_name'
},
lastName: {
type: DataTypes.STRING,
field: 'last_name'
},
email: {
type: DataTypes.STRING,
isEmail: true,
unique: true,
set: function(val) {
this.setDataValue('email', val.toLowerCase());
}
},
password: DataTypes.STRING,
organizationId: {
type: DataTypes.INTEGER,
field: 'organization_id',
allowNull: true
},
resetPasswordToken: {
type: DataTypes.STRING,
field: 'reset_password_token'
},
resetPasswordExpires: {
type: DataTypes.DATE,
field: 'reset_password_expires'
}
}, {
freezeTableName: true,
classMethods: {
associate: function(db) {
User.belongsToMany(db.Organization, { through: 'member', foreignKey: 'organizationId'})
},
generateHash: function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
},
},
instanceMethods: {
validPassword: function(password) {
return bcrypt.compareSync(password, this.password);
},
},
});
return User;
}
Here is the passportjs logic:
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var models = require('../app/models/db-index');
/*==== Passport Configuration ====*/
// Serialize sessions
passport.serializeUser(function(user, done) {
console.log("User ID: " + user.user_id + " is serializing");
done(null, user.user_id);
});
passport.deserializeUser(function(user_id, done) {
models.User.find({where: {user_id: user_id}}).then(function(user){
console.log("User ID: " + user.user_id + " is deserializing");
done(null, user);
}).error(function(err){
done(err, null);
});
});
//Login logic
passport.use('local', new LocalStrategy({
passReqToCallback: true,
usernameField: 'email'
}, function(req, email, password, done) {
console.log("Database query triggered");
//Find user by email
models.User.findOne({
where: {
email: req.body.email
}
}).then(function(user) {
if (!user) {
done(null, false, { message: 'The email you entered is incorrect' }, console.log("Unknown User"));
} else if (!user.validPassword(password)){
done(null, false, console.log("Incorrect Password"));
} else {
console.log("User match");
done(null, user);
}
}).catch(function(err) {
console.log("Server Error");
return done(null, false);
});
}));
//Sign Up Logic
passport.use('local-signup', new LocalStrategy({
passReqToCallback: true,
usernameField: 'email'
}, function(req, email, password, done){
models.User.findOne({
where: {
email: email
}
}).then(function(existingUser){
if (existingUser)
return done(null, false, req.flash('error', 'Email already exists.'));
if (req.user) {
var user = req.user;
user.firstName = firstName;
user.lastName = lastName;
user.email = email;
user.password = models.User.generateHash(password);
user.save().catch(function(err){
throw err;
}).then(function(){
done(null, user, req.flash('error', 'All fields need to be filled in'));
});
} else {
var newUser = models.User.build({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: models.User.generateHash(password)
});
newUser.save().then(function(){
done(null, newUser);
}).catch(function(err){
done(null, false, console.log(err));
});
}
}).catch(function(e){
done(null, false, req.flash('error', 'All fields need to be filled in'),console.log(e.email + e.message));
})
}));
module.exports = passport;
Looks like you forget to generate your password again.
.post(function(req, res){
async.waterfall([
function(done){
models.User.update({
password: models.User.generateHash(req.body.password)

Resources