Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Issue #96 #98

Merged
merged 5 commits into from
Sep 14, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 55 additions & 27 deletions lib/passport-local-mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ module.exports = function(schema, options) {
// Populate field names with defaults if not set
options.usernameField = options.usernameField || 'username';
options.usernameUnique = options.usernameUnique === undefined ? true : options.usernameUnique;
// Populate username query fields with defaults if not set,

// Populate username query fields with defaults if not set,
// otherwise add username field to query fields.
if (options.usernameQueryFields) {
options.usernameQueryFields.push(options.usernameField);
options.usernameQueryFields.push(options.usernameField);
} else {
options.usernameQueryFields = [options.usernameField];
}
Expand Down Expand Up @@ -61,8 +61,8 @@ module.exports = function(schema, options) {
if (!schema.path(options.usernameField)) {
schemaFields[options.usernameField] = { type : String, unique : options.usernameUnique };
}
schemaFields[options.hashField] = String;
schemaFields[options.saltField] = String;
schemaFields[options.hashField] = { type: String, select: false };
schemaFields[options.saltField] = { type: String, select: false }

if (options.limitAttempts){
schemaFields[options.attemptsField] = {type: Number, default: 0};
Expand Down Expand Up @@ -113,48 +113,46 @@ module.exports = function(schema, options) {
});
};

schema.methods.authenticate = function(password, cb) {
var self = this;

function authenticate(user, password, cb) {
if (options.limitAttempts) {
var attemptsInterval = Math.pow(options.interval, Math.log(this.get(options.attemptsField) + 1));
var attemptsInterval = Math.pow(options.interval, Math.log(user.get(options.attemptsField) + 1));
var calculatedInterval = (attemptsInterval < options.maxInterval) ? attemptsInterval : options.maxInterval;

if (Date.now() - this.get(options.lastLoginField) < calculatedInterval) {
this.set(options.lastLoginField, Date.now());
this.save();
if (Date.now() - user.get(options.lastLoginField) < calculatedInterval) {
user.set(options.lastLoginField, Date.now());
user.save();
return cb(null, false, { message: options.attemptTooSoonError });
}

if (self.get(options.attemptsField) >= options.maxAttempts) {
if (user.get(options.attemptsField) >= options.maxAttempts) {
return cb(null, false, { message: options.tooManyAttemptsError });
}
}

if (!this.get(options.saltField)) {
if (!user.get(options.saltField)) {
return cb(null, false, { message: options.noSaltValueStoredError });
}

pbkdf2(password, this.get(options.saltField), function(err, hashRaw) {
pbkdf2(password, user.get(options.saltField), function(err, hashRaw) {
if (err) {
return cb(err);
}

var hash = new Buffer(hashRaw, 'binary').toString(options.encoding);

if (scmp(hash, self.get(options.hashField))) {
if (scmp(hash, user.get(options.hashField))) {
if (options.limitAttempts){
self.set(options.lastLoginField, Date.now());
self.set(options.attemptsField, 0);
self.save();
user.set(options.lastLoginField, Date.now());
user.set(options.attemptsField, 0);
user.save();
}
return cb(null, self);
return cb(null, user);
} else {
if (options.limitAttempts){
self.set(options.lastLoginField, Date.now());
self.set(options.attemptsField, self.get(options.attemptsField) + 1);
self.save(function(err) {
if (self.get(options.attemptsField) >= options.maxAttempts) {
user.set(options.lastLoginField, Date.now());
user.set(options.attemptsField, user.get(options.attemptsField) + 1);
user.save(function(err) {
if (user.get(options.attemptsField) >= options.maxAttempts) {
return cb(null, false, { message: options.tooManyAttemptsError });
} else {
return cb(null, false, { message: options.incorrectPasswordError });
Expand All @@ -165,6 +163,26 @@ module.exports = function(schema, options) {
}
}
});

}

schema.methods.authenticate = function(password, cb) {
var self = this;

// With hash/salt marked as "select: false" - load model including the salt/hash fields form db and authenticate
if (!self.get(options.saltField)) {
self.constructor.findByUsername(self.get(options.usernameField), true, function(err, user) {
if (err) { return cb(err); }

if (user) {
return authenticate(user, password, cb);
} else {
return cb(null, false, { message: util.format(options.incorrectUsernameError, options.usernameField) })
}
});
} else {
return authenticate(self, password, cb);
}
};

if (options.limitAttempts) {
Expand All @@ -178,7 +196,7 @@ module.exports = function(schema, options) {
var self = this;

return function(username, password, cb) {
self.findByUsername(username, function(err, user) {
self.findByUsername(username, true, function(err, user) {
if (err) { return cb(err); }

if (user) {
Expand Down Expand Up @@ -238,13 +256,19 @@ module.exports = function(schema, options) {
});
};

schema.statics.findByUsername = function(username, cb) {
schema.statics.findByUsername = function(username, selectHashSaltFields, cb) {
var queryParameters = {};
if (typeof cb === 'undefined') {
cb = selectHashSaltFields;
selectHashSaltFields = false;
}

// if specified, convert the username to lowercase
if (username !== undefined && options.usernameLowerCase) {
username = username.toLowerCase();
}

// Add each username query field
// Add each username query field
var queryOrParameters = [];
for (var i = 0; i < options.usernameQueryFields.length; i++) {
var parameter = {};
Expand All @@ -254,6 +278,10 @@ module.exports = function(schema, options) {

var query = this.findOne({$or : queryOrParameters});

if (selectHashSaltFields) {
query.select('+' + options.hashField + " +" + options.saltField);
}

if (options.selectFields) {
query.select(options.selectFields);
}
Expand Down
22 changes: 11 additions & 11 deletions test/alternative-query-field.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('alternative query field', function () {
var user = new User({ username : 'hugo', email : email });
user.save(function (err) {
assert.ifError(err);

User.findByUsername(email, function (err, user) {
assert.ifError(err);
assert.ok(user);
Expand All @@ -31,7 +31,7 @@ describe('alternative query field', function () {
});
});
});

it('should authenticate an existing user by alternative query field', function (done) {
this.timeout(5000); // Five seconds - mongo db access needed

Expand All @@ -45,7 +45,7 @@ describe('alternative query field', function () {
var user = new User({ username : 'hugo', email : email });
User.register(user, 'password', function (err) {
assert.ifError(err);

User.authenticate()('[email protected]', 'password', function(err, user, message) {
assert.ifError(err);
assert.ok(user);
Expand All @@ -54,8 +54,8 @@ describe('alternative query field', function () {
done();
});
});
});
});

it('should authenticate an existing user by default username field', function (done) {
this.timeout(5000); // Five seconds - mongo db access needed

Expand All @@ -69,7 +69,7 @@ describe('alternative query field', function () {
var user = new User({ username : 'hugo', email : email });
User.register(user, 'password', function (err) {
assert.ifError(err);

User.authenticate()('hugo', 'password', function(err, user, message) {
assert.ifError(err);
assert.ok(user);
Expand All @@ -78,8 +78,8 @@ describe('alternative query field', function () {
done();
});
});
});
});

it('should not authenticate an existing user by unconfigured alternative query field', function (done) {
this.timeout(5000); // Five seconds - mongo db access needed

Expand All @@ -93,7 +93,7 @@ describe('alternative query field', function () {
var user = new User({ username : 'hugo', email : email });
User.register(user, 'password', function (err) {
assert.ifError(err);

User.authenticate()('[email protected]', 'password', function(err, user, message) {
assert.ifError(err);
assert.ok(!user);
Expand All @@ -102,5 +102,5 @@ describe('alternative query field', function () {
done();
});
});
});
});
});
});
70 changes: 63 additions & 7 deletions test/issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,9 @@ describe('issues', function () {

var authenticate = User.authenticate();

authenticate('hugo', 'password', function(err, auth, reason) {
authenticate('hugo', 'password', function(err, result) {
assert.ifError(err);

assert.equal(false, auth);
assert.ok(reason);

assert.equal('Authentication not possible. No salt value stored in mongodb collection!', reason.message);
assert.ok(result instanceof User);

done();
});
Expand Down Expand Up @@ -150,4 +146,64 @@ describe('issues', function () {
done();
});
});
});

it('should not expose hash and salt fields - Issue #72', function(done) {
this.timeout(5000); // Five seconds - mongo db access needed

var UserSchema = new Schema({});

UserSchema.plugin(passportLocalMongoose, { });
var User = mongoose.model('ShouldNotExposeHashAndSaltFields_Issue_72', UserSchema);

User.register({username: "nicolascage"}, 'password', function (err, user) {
assert.ifError(err);
assert.ok(user);
User.findOne({username: "nicolascage"}, function(err, user) {
assert.ifError(err);
assert.ok(user);
assert.equal(user.username, "nicolascage");
assert.strictEqual(user.hash, undefined);
assert.strictEqual(user.salt, undefined);
done();
});
});
});

describe('authentication should work with salt/hash field marked as select: false - Issue #96', function() {
this.timeout(5000); // Five seconds - mongo db access needed
var UserSchema = new Schema({});
UserSchema.plugin(passportLocalMongoose, { });
var userName = 'user_' + Math.random();
var User = mongoose.model('ShouldAuthenticateWithSaltAndHashNotExposed_Issue_96', UserSchema);
beforeEach(function(done) {
User.register({username: userName}, 'password', function (err, user) {
assert.ifError(err);
assert.ok(user);
done();
});
});

it('instance.authenticate( password, callback )', function(done) {
User.findOne({username: userName}, function(err, user) {
assert.ifError(err);
assert.ok(user);
assert.equal(user.username, userName);
user.authenticate('password', function(err, auth, reason) {
assert.ifError(err);

assert.ok(auth);
done();
});
});
});

it('Model.autheticate(username, password, callback)', function(done) {
User.authenticate()( userName, 'password', function(err, auth, reason){
assert.ifError(err);
assert.ok(auth);

done();
});
});
});
});
6 changes: 6 additions & 0 deletions test/mongotest.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ function dropCollections(collections, index, cb) {

module.exports = {
prepareDb : function(connectionString, options) {
// support use of non localhost MongoDB using env variable MONGO_SERVER
if (process.env.MONGO_SERVER) {
connectionString = connectionString.replace('mongodb://localhost', 'mongodb://' + process.env.MONGO_SERVER);
}


options = options || {};
options.timeout = options.timeout || 5000;
return function(cb) {
Expand Down
6 changes: 3 additions & 3 deletions test/passport-local-mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ describe('passportLocalMongoose', function () {
debugger;
expect(err).to.not.exist;
expect(result).to.be.false;

done();
});
});
Expand Down Expand Up @@ -673,7 +673,7 @@ describe('passportLocalMongoose', function () {
});
});
});

it('should not authenticate registered user with wrong password', function (done) {
this.timeout(5000); // Five seconds - mongo db access needed

Expand All @@ -693,7 +693,7 @@ describe('passportLocalMongoose', function () {
});
});
});

it('it should add username existing user without username', function (done) {
this.timeout(5000); // Five seconds - mongo db access needed

Expand Down