-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
80 lines (67 loc) · 2.65 KB
/
example.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
'use strict'
const dboxpwd = require('./index');
//this should be stored somewhere else than users and their passwords
//it could be a file with permissions: "-r--------" which should be read every time the 'secret' is required to encrypt/decrypt data
const secret = 'secretPassword123';
const registerUser = function() {
//data from the registration form
const userName = 'tomek';
const userPassword = 'password123';
//Hash and encrypt the password. Choose the bcryptRounds value experimentally. Bigger values are more secure but also more time consuming.
//The value can be stored in a config file and increased periodically(for example +1 every year).
dboxpwd.encrypt(userPassword, secret, 10)
.then(function(encryptedPassword) {
console.log('Encrypted password:', encryptedPassword);
//now you can save user information to db
//db.saveUser(userName, encryptedPassword)
})
.catch(function(error) {
console.error(error);
});
};
const successfulLogin = function() {
//data from the login form
const userName = 'tomek';
const userPassword = 'password123';
//select the user information from db
const userPasswordFromDB = '591e81c3c3491709095f13d296fe013f57c5ebc98a2371decae2b0555e6030e96a6ddb4bcaba78d51097262b7728e56f01c2c53380f06f5e9ac5edca0125eb1b';
dboxpwd.compare(userPassword, userPasswordFromDB, secret)
.then(function(passwordsMatch) {
if(passwordsMatch) {
console.log('Login successful');
//create session, etc...
} else {
console.error('Wrong user name or password');
//
}
})
.catch(function(error) {
//something went wrong during password decryption or comparison
console.error(error);
});
};
const unsuccessfulLogin = function() {
//data from the login form
const userName = 'tomek';
const userPassword = 'incorrectPassword';
//select the user information from db
const userPasswordFromDB = '591e81c3c3491709095f13d296fe013f57c5ebc98a2371decae2b0555e6030e96a6ddb4bcaba78d51097262b7728e56f01c2c53380f06f5e9ac5edca0125eb1b';
dboxpwd.compare(userPassword, userPasswordFromDB, secret)
.then(function(passwordsMatch) {
if(passwordsMatch) {
console.log('Login successful');
//create session, etc...
} else {
console.error('Wrong user name or password');
//
}
})
.catch(function(error) {
//something went wrong during password decryption or comparison
console.error(error);
});
};
//to test run: node example.js
registerUser();
successfulLogin();
unsuccessfulLogin();