meteor: check a user's password
Out of the box, a meteor application's server and client can agree on who the current user is. However, for some critical operations (like account modifications) it's sometimes nice to have the user re-verify her password after she is already logged in.
In previous versions of meteor, the only way to accomplish this was to re-implement a portion of the login functionality on both the client and the server. Fortunately with meteor 0.8.2 we now have access to Accounts._checkPassword
which makes the task much easier.
We will take the following steps:
1. Read the password on the client.
2. Compute a SHA256 digest of the password.
3. Call a method with the digest (note we are not sending the password in cleartext).
4. Call Accounts._checkPassword
on the server and return the result.
For our client code, I'm going to assume you have a form with an input called password
and a button called check-password
. The event code could look something like this:
Template.userAccount.events({
'click #check-password': function() {
var digest = Package.sha.SHA256($('#password').val());
Meteor.call('checkPassword', digest, function(err, result) {
if (result) {
console.log('the passwords match!');
}
});
}
});
Then on the server, we can implement the checkPassword
method like so:
Meteor.methods({
checkPassword: function(digest) {
check(digest, String);
if (this.userId) {
var user = Meteor.user();
var password = {digest: digest, algorithm: 'sha-256'};
var result = Accounts._checkPassword(user, password);
return result.error == null;
} else {
return false;
}
}
});
Note that Accounts._checkPassword
always returns a result object, but success is determined by the absence of an error value.