1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
/*
* auth.js
*
* authentication
*
*/
/* helpful links:
* http://stackoverflow.com/questions/7990890/how-to-implement-login-auth-in-node-js/8003291#8003291
*
*/
var util = require('util');
var crypto = require('crypto');
var db = require('./mydb.js');
var len = 128;
var iterations = 12000;
/**
* Hashes a password with optional `salt`, otherwise
* generate a salt for `pass` and invoke `fn(err, salt, hash)`.
*
* @param {String} password to hash
* @param {String} optional salt
* @param {Function} callback
* @api public
*/
function hash(pwd, salt, fn) {
if (3 == arguments.length) {
crypto.pbkdf2(pwd, salt, iterations, len, fn);
} else {
fn = salt;
crypto.randomBytes(len, function(err, salt) {
if (err) return fn(err);
salt = salt.toString('base64');
crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash) {
if (err) return fn(err);
fn(null, salt, hash);
});
});
}
};
/* pull out a user record from db along with http status code */
function auth_user(tag, id, fn) {
db.users.find({tag: tag}, function(err, user_record) {
if (err)
{
fn(err, null, -1);
}
else if (!user_record || user_record.length == 0)
{
fn(null, null, 403);
}
else
{
/* util.log('[auth] retrived user: ' + util.inspect(user_record)); */
hash(id, user_record[0].salt, function(err, hash) {
if (err)
return fn(err, null, -1);
if (hash == user_record[0].hash)
return fn(null, user_record[0], 200); /* granted */
fn(null, null, 401);
});
}
});
}
exports.hash = hash;
exports.auth_user = auth_user;
|