forked from aditosoftware/nodepki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.js
104 lines (77 loc) · 2.18 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
/*
* Auth module
*/
var crypto = require('crypto');
var fs = require('fs-extra');
/*
* Checks login credentials
* Input: Username, password (plain)
*/
var checkUser = function(username, password) {
var hash = crypto.createHash('sha256').update(password).digest('base64');
// Check if there is an entry with username:hash
// ...
var expected = username + ':' + hash;
// Read password file
var passfile = fs.readFileSync('data/user.db', 'utf8');
var lines = passfile.split('\n');
var found = false;
lines.forEach(function(line) {
if (line === expected) found = true;
});
return found;
};
/*
* Add a new user to DB
*/
var addUser = function(username, password) {
// Make sure DB file exists ...
fs.ensureFileSync('data/user.db');
// Calc passhash
var passhash = crypto.createHash('sha256').update(password).digest('base64');
// Read existing file
var passfile = fs.readFileSync('data/user.db', 'utf8');
// Check if user alreadys exists
var lines = passfile.split('\n');
var found = false;
lines.forEach(function(line) {
var line_username = line.split(':')[0];
if (line_username === username) found = true;
});
if(found === false) {
// Update file
passfile = passfile + username + ':' + passhash + '\n';
fs.writeFileSync('data/user.db', passfile, 'utf8');
return true;
} else {
return false;
}
};
/*
* Delete user from DB
*/
var delUser = function(username) {
fs.ensureFileSync('data/user.db');
var passfile = fs.readFileSync('data/user.db', 'utf8');
var lines = passfile.split('\n');
var changed = false;
var passfile_out = '';
// Re-write file without user
lines.forEach(function(line) {
if(line !== '') {
var line_username = line.split(':')[0];
if(line_username !== username) {
passfile_out += line + '\n'
} else {
changed = true;
}
}
});
fs.writeFileSync('data/user.db', passfile_out);
return changed;
};
module.exports = {
addUser: addUser,
checkUser: checkUser,
delUser: delUser
}