Date
passport.use(new LocalStrategy({
usernameField: 'login', // 'username' by default
passwordField: 'password'
},
function(login, password, done) {
User.findOne({ login: login }, function (err, user) {
if (err) {
return done(err);
}
if (!user || !user.checkPassword(password)) {
// don't say whether the user exists
return done(null, false, { message: 'Нет такого пользователя или пароль неверен.' });
}
return done(null, user);
});
}
));
const mongoose = require('../libs/mongoose');
const crypto = require('crypto');
const config = require('config');
var Schema=mongoose.Schema;
var userSchemaOBj={
name:{
type: String
},
salt:{
type: String,
unique: true,
},
passwordHash:{
type: String,
unique: true,
}
}
var userSchema =new mongoose.Schema(userSchemaOBj);
userSchema.virtual('password')
.set(function(password) {
if (password !== undefined) {
if (password.length < 4) {
this.invalidate('password', 'Пароль должен быть минимум 4 символа.');
}
}
this._plainPassword = password;
if (password) {
this.salt = crypto.randomBytes(config.crypto.hash.length).toString('base64');
this.passwordHash = crypto.pbkdf2Sync(password, this.salt, config.crypto.hash.iterations, config.crypto.hash.length);
} else {
// remove password (unable to login w/ password any more, but can use providers)
this.salt = undefined;
this.passwordHash = undefined;
}
})
.get(function() {
return this._plainPassword;
});
userSchema.methods.checkPassword = function(password) {
if (!password) return false; // empty password means no login by password
if (!this.passwordHash) return false; // this user does not have password (the line below would hang!)
return crypto.pbkdf2Sync(password, this.salt, config.crypto.hash.iterations, config.crypto.hash.length) ==
this.passwordHash;
};
userSchema.methods.createPassword = function(password) {
let salt = crypto.randomBytes(config.crypto.hash.length).toString('base64');
let passwordHash = crypto.pbkdf2Sync(password, salt, config.crypto.hash.iterations, config.crypto.hash.length);
return {
salt:salt,
passwordHash:passwordHash
}
};
module.exports = mongoose.model('user', userSchema);