closes #1976
parent
9511e4a633
commit
005405b16c
@ -0,0 +1,30 @@
|
||||
|
||||
'use strict';
|
||||
|
||||
|
||||
var bcrypt = require('bcryptjs');
|
||||
|
||||
process.on('message', function(m) {
|
||||
if (m.type === 'hash') {
|
||||
hash(m.rounds, m.password);
|
||||
} else if (m.type === 'compare') {
|
||||
compare(m.password, m.hash);
|
||||
}
|
||||
});
|
||||
|
||||
function hash(rounds, password) {
|
||||
bcrypt.genSalt(rounds, function(err, salt) {
|
||||
if (err) {
|
||||
return process.send({type:'hash', err: {message: err.message}});
|
||||
}
|
||||
bcrypt.hash(password, salt, function(err, hash) {
|
||||
process.send({type:'hash', err: err ? {message: err.message} : null, hash: hash, password: password});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function compare(password, hash) {
|
||||
bcrypt.compare(password, hash, function(err, res) {
|
||||
process.send({type:'compare', err: err ? {message: err.message} : null, hash: hash, password: password, result: res});
|
||||
});
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
|
||||
|
||||
'use strict';
|
||||
var fork = require('child_process').fork;
|
||||
|
||||
(function(module) {
|
||||
|
||||
var child = fork('./bcrypt', process.argv.slice(2), {
|
||||
env: process.env
|
||||
});
|
||||
|
||||
var callbacks = {
|
||||
'hash': {},
|
||||
'compare': {}
|
||||
};
|
||||
|
||||
module.hash = function(rounds, password, callback) {
|
||||
sendCommand({type: 'hash', password: password, rounds: rounds}, callback);
|
||||
};
|
||||
|
||||
module.compare = function(password, hash, callback) {
|
||||
sendCommand({type: 'compare', password: password, hash: hash}, callback);
|
||||
};
|
||||
|
||||
function sendCommand(data, callback) {
|
||||
callbacks[data.type][data.password] = callbacks[data.type][data.password] || [];
|
||||
callbacks[data.type][data.password].push(callback);
|
||||
child.send(data);
|
||||
}
|
||||
|
||||
child.on('message', function(msg) {
|
||||
var cbs = callbacks[msg.type] ? callbacks[msg.type][msg.password] : null;
|
||||
|
||||
if (Array.isArray(cbs)) {
|
||||
if (msg.err) {
|
||||
var err = new Error(msg.err.message);
|
||||
cbs.forEach(function(callback) {
|
||||
callback(err);
|
||||
});
|
||||
cbs.length = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
cbs.forEach(function(callback) {
|
||||
callback(null, msg.type === 'hash' ? msg.hash : msg.result);
|
||||
});
|
||||
cbs.length = 0;
|
||||
}
|
||||
});
|
||||
|
||||
}(exports));
|
Loading…
Reference in New Issue