-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
119 lines (100 loc) · 2.38 KB
/
auth.js
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
var fs = require('fs');
var jwt = require('jsonwebtoken');
var userdb = require('./userdb.js');
var hash = require('./hash.js');
var defaultLoginLog = './login.log';
var ndays_later = function (n) {
return Math.floor(new Date().getTime() / 1000) + n * 24 * 60 * 60;
}
var nsec_later = function (n) {
return Math.floor(new Date().getTime() / 1000) + n;
}
var memUsrPassMap = {};
exports.verifyUsrPasswd = function (name, passwd) {
var user = userdb.getUser(name);
/* this user has no password */
if (user['hash'] === undefined || user['hash'] == '')
return true;
/* verify otherwise */
var salt = user['salt'];
var vrfy_hash = hash.hashPasswd(name, passwd, salt);
return (vrfy_hash == user['hash']);
};
function gen_jwt_token(username, password,
perm, expire_timestamp)
{
return jwt.sign({
exp: expire_timestamp,
"loggedInAs": username,
"perm": perm,
}, password, {algorithm: 'HS256'});
}
exports.login = function (name, passwd, ip) {
var msg = 'Login successful.';
var pass = false;
var perm = [];
var token = '';
name = name || '';
passwd = passwd || 'foo'; // jwt.sign() does not take
// empty string.
ip = ip || '';
try {
pass = exports.verifyUsrPasswd(name, passwd);
if (!pass)
msg = 'Wrong password.';
else
perm = userdb.getUser(name)["perm"] || [];
} catch (e) {
msg = e.message;
}
/* login log */
let now = (new Date()).toString();
fs.appendFileSync(defaultLoginLog, now + ' ' + ip +
' "' + name + '" ' + msg + "\n");
/* generate token */
if (pass) {
token = gen_jwt_token(
name, passwd, perm,
//DEBUG: nsec_later(10)
ndays_later(3)
);
memUsrPassMap[name] = passwd;
}
return {
'pass': pass,
'msg': msg,
'perm': perm,
'token': token
}
}
function tryDecodeJWT(token) {
var decTok = {};
try {
decTok = jwt.decode(token) || {};
} catch (e) {
; // fall through
}
//console.log(decTok);
return decTok;
}
exports.tokVerify = function (token) {
token = token || '';
var decTok = tryDecodeJWT(token);
var username = decTok['loggedInAs'] || '';
var perm = decTok['perm'] || [];
var passwd = memUsrPassMap[username] || '';
var pass = true, msg = 'Auth successful.';
try {
decTok = jwt.verify(token, passwd);
} catch (e) {
pass = false;
perm = [];
msg = e.message;
}
return {
'pass': pass,
'msg': msg,
'user': username,
'perm': perm
}
};