Require verification after email change

When the User model is configured to require email verification,
then any change of the email address should trigger re-verification.
This commit is contained in:
Loay 2016-09-20 11:10:18 -04:00 committed by Miroslav Bajtoš
parent fcbe028e11
commit eb640d8da0
2 changed files with 77 additions and 0 deletions

View File

@ -683,6 +683,19 @@ module.exports = function(User) {
ctx.hookState.originalUserData = userInstances.map(function(u) {
return { id: u.id, email: u.email };
});
if (ctx.instance) {
var emailChanged = ctx.instance.email !== ctx.hookState.originalUserData[0].email;
if (emailChanged && ctx.Model.settings.emailVerificationRequired) {
ctx.instance.emailVerified = false;
}
} else {
var emailChanged = ctx.hookState.originalUserData.some(function(data) {
return data.email != ctx.data.email;
});
if (emailChanged && ctx.Model.settings.emailVerificationRequired) {
ctx.data.emailVerified = false;
}
}
next();
});
});

View File

@ -2193,6 +2193,70 @@ describe('User', function() {
});
});
describe('Verification after updating email', function() {
var NEW_EMAIL = 'updated@example.com';
var userInstance;
beforeEach(createOriginalUser);
it('sets verification to false after email update if verification is required',
function(done) {
User.settings.emailVerificationRequired = true;
async.series([
function updateUser(next) {
userInstance.updateAttribute('email', NEW_EMAIL, function(err, info) {
if (err) return next (err);
assert.equal(info.email, NEW_EMAIL);
next();
});
},
function findUser(next) {
User.findById(userInstance.id, function(err, info) {
if (err) return next (err);
assert.equal(info.email, NEW_EMAIL);
assert.equal(info.emailVerified, false);
next();
});
},
], done);
});
it('leaves verification as is after email update if verification is not required',
function(done) {
User.settings.emailVerificationRequired = false;
async.series([
function updateUser(next) {
userInstance.updateAttribute('email', NEW_EMAIL, function(err, info) {
if (err) return next (err);
assert.equal(info.email, NEW_EMAIL);
next();
});
},
function findUser(next) {
User.findById(userInstance.id, function(err, info) {
if (err) return next (err);
assert.equal(info.email, NEW_EMAIL);
assert.equal(info.emailVerified, true);
next();
});
},
], done);
});
function createOriginalUser(done) {
var userData = {
email: 'original@example.com',
password: 'bar',
emailVerified: true,
};
User.create(userData, function(err, instance) {
if (err) return done(err);
userInstance = instance;
done();
});
}
});
describe('password reset with/without email verification', function() {
it('allows resetPassword by email if email verification is required and done',
function(done) {