1 |
|
2 |
|
3 |
|
4 |
|
5 | class CredentialDB {
|
6 |
|
7 | constructor() {
|
8 | this.credentials = [];
|
9 | }
|
10 |
|
11 | |
12 |
|
13 |
|
14 |
|
15 |
|
16 | createPool(creds, pool) {
|
17 | const FREE_USER_TIMEOUT = 10 * 60 * 1000;
|
18 |
|
19 | const credentials = creds.map(item => {
|
20 | item.isLocked = false;
|
21 | item.freeTimeout = function() {
|
22 | setTimeout(() => {
|
23 | this.isLocked = false;
|
24 | }, FREE_USER_TIMEOUT)
|
25 | };
|
26 | return item
|
27 | });
|
28 |
|
29 | if (pool) {
|
30 | this[pool] = credentials;
|
31 | } else {
|
32 | this.credentials = credentials;
|
33 | }
|
34 | }
|
35 |
|
36 | |
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 | getCredentials(pool) {
|
43 | let poolRef = this.credentials;
|
44 | if (pool) {
|
45 | if (!this[pool]) throw new Error("Pool " + pool + "doesn't exist");
|
46 | poolRef = this[pool];
|
47 | }
|
48 | const freeUserIndex = poolRef.findIndex(item => item.isLocked === false);
|
49 |
|
50 | if (freeUserIndex !== -1) {
|
51 | poolRef[freeUserIndex].isLocked = true;
|
52 | poolRef[freeUserIndex].freeTimeout();
|
53 | return poolRef[freeUserIndex];
|
54 | } else {
|
55 | throw new Error("There are no free users");
|
56 | }
|
57 | }
|
58 |
|
59 | |
60 |
|
61 |
|
62 |
|
63 |
|
64 | freeCredentials(username, pool) {
|
65 | let poolRef = this.credentials;
|
66 | if (pool) {
|
67 | if (!this[pool]) throw new Error("Pool " + pool + "doesn't exist");
|
68 | poolRef = this[pool];
|
69 | }
|
70 | const userIndex = poolRef.findIndex(item => item.username === username);
|
71 |
|
72 | if (userIndex !== -1) {
|
73 | poolRef[userIndex].isLocked = false;
|
74 | }
|
75 | }
|
76 |
|
77 | |
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | updateProperty(username, property, value, pool) {
|
86 | let poolRef = this.credentials;
|
87 | if (pool) {
|
88 | if (!this[pool]) throw new Error("Pool " + pool + "doesn't exist");
|
89 | poolRef = this[pool];
|
90 | }
|
91 | const userIndex = poolRef.findIndex(item => item.username === username);
|
92 |
|
93 | if (userIndex !== -1) {
|
94 | poolRef[userIndex][property] = value;
|
95 | } else {
|
96 | throw new Error("User with " + username + " is not found");
|
97 | }
|
98 | }
|
99 |
|
100 | |
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 | getCredentialsByUsername(username, pool) {
|
108 | let poolRef = this.credentials;
|
109 | if (pool) {
|
110 | if (!this[pool]) throw new Error("Pool " + pool + "doesn't exist");
|
111 | poolRef = this[pool];
|
112 | }
|
113 | const freeUserIndex = poolRef.findIndex(item => item.username === username);
|
114 |
|
115 | if (freeUserIndex !== -1) {
|
116 | poolRef[freeUserIndex].isLocked = true;
|
117 | poolRef[freeUserIndex].freeTimeout();
|
118 | return poolRef[freeUserIndex];
|
119 | } else {
|
120 | throw new Error("There are no users with username: " + username);
|
121 | }
|
122 | }
|
123 |
|
124 | }
|
125 |
|
126 | module.exports = CredentialDB; |
\ | No newline at end of file |