Repository navigation
Expand file tree
/
Copy pathtest.js
More file actions
executable file
·115 lines (100 loc) · 2.67 KB
/
Copy pathtest.js
File metadata and controls
executable file
·115 lines (100 loc) · 2.67 KB
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
'use strict';
// Add ECMA262-5 Array methods if not supported natively
//
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf= function(find, i /*opt*/) {
if (i===undefined) i= 0;
if (i<0) i+= this.length;
if (i<0) i= 0;
for (let n= this.length; i<n; i++)
if (i in this && this[i]===find)
return i;
return -1;
};
}
// This class is used for logins
class Login {
constructor(hash) {
this.sessions = [];
this.users = [];
this.passwords = [];
Object.keys(hash).map(k => {
this.users.push(k);
this.passwords.push(hash[k])
});
}
logout(user) {
let index = this.users.indexOf(user);
if(index !== -1) {
// filter affect immutable and could be slower than splice, test needed
// keep filter for now
this.sessions = this.sessions.filter(session => session !== user);
}
}
// Checks if user exists
userExists(user) {
let index = this.users.indexOf(user);
return index !== -1;
}
// Register user
registerUser(user, password) {
// register user only if username does not exist
if (this.users.indexOf(user) === -1) {
let lastIndex = this.users.length;
this.users[lastIndex] = user;
this.passwords[lastIndex] = password;
}
}
removeUser(user) {
let index = this.users.indexOf(user);
if(index !== -1) {
this.users[index] = null;
this.passwords[index] = null;
this.users = this.users.filter(user => user !== null);
this.passwords = this.passwords.filter(password => password !== null);
}
}
checkPassword(user, password) {
let index = this.users.indexOf(user);
if(index === -1) {
return false;
}
return this.passwords[index] === password;
}
updatePassword(user, oldPassword, newPassword) {
// if password are the same don't do anything
if(oldPassword === newPassword) {
return false;
}
// check if the user exists
let index = this.users.indexOf(user);
if(index === -1) {
return false;
}
if (this.checkPassword(user, oldPassword)) {
this.passwords[index] = newPassword;
return true;
}
return false;
}
login(user, password) {
let index = this.users.indexOf(user);
if(index !== -1) {
if (this.passwords[index] === password) {
this.sessions.push(user);
}
}
}
}
let registeredUsers = {
user1: 'pass1',
user2: 'pass2',
user3: 'pass3'
};
let login = new Login(registeredUsers);
login.registerUser('user4', 'pass4');
login.login('user4', 'pass4');
login.updatePassword('user3', 'pass3', 'pass5');
login.login('user3', 'pass5');
login.logout('user4');
login.logout('user3');