-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
406 lines (343 loc) · 11.7 KB
/
index.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
const authClass = require("./user-auth");
const joi = require("joi");
const uniqid = require("uniqid");
const clr = require("./cli-colors");
const pool = require("./pool");
const env = process.env;
const key = env.AUTH_JWT_KEY;
if (!key) {
throw `${clr.Red}\n\nERROR: JWT Key not found. Please, add AUTH_JWT_KEY value to .env file${clr.Reset}\n\n`;
}
const auth = new authClass(key);
class userAuthModel {
constructor(options = {}) {
this.user = null;
this.pool = pool;
this.error = null;
this.options = {
// default options
...{
queries: {
// login query - SELECT * from users where email='[email protected]'
login: "SELECT * FROM `{{table}}` WHERE `{{login}}`=?",
// insert query
insert: "INSERT INTO {{table}} {{fields}} VALUES {{values}}",
// update query
insert: "UPDATE {{table}} set {{fields}} where ?=?",
},
tables: {
users: process.env.AUTH_TABLES_USERS || "users",
sessions: process.env.AUTH_TABLES_SESSIONS || "sessions",
},
userFields: {
id: env.AUTH_USER_FIELDS_ID || "id",
login: env.AUTH_USER_FIELDS_LOGIN || "email",
password: env.AUTH_USER_FIELDS_PASSWORD || "password",
},
sessionFields: {
session_id: env.AUTH_SESSION_FIELDS_SESSION || "sessionId",
session_user: env.AUTH_SESSION_FIELDS_USER || "userId",
},
verification: {
user: joi.object({
email: joi.string().email().required(),
password: joi.string().min(6).required(),
}),
},
// token lifespan in minutes
tokenLifespan: 30,
// error string handler
errorStringHandler: (e) => {
let error;
switch (e.code) {
case "ECONNREFUSED":
error = "Connection refused";
this.log(error);
break;
default:
error = "Error fetching user from DB";
this.log(error);
break;
}
return error;
},
// Logger calback for error messages. Default is console.log
logger: console.log,
},
// overrides
...options,
};
}
/**
* Run a dummy query to check DB connection
*/
async checkConnection() {
// this query must run if there is a connection and database is selected
try {
await pool.query("SHOW TABLES;");
return true;
} catch (e) {
return false;
}
}
// /**
// * Retuns user by login/password combination using current configuration or null if not found.
// * @param {*} login
// * @param {*} password
// * @throws {Error} database error when fetching user
// * @returns {object|null}
// */
// async userByLoginAndPassword(login, password) {
// // get users table name from options
// const table = this.options.tables.users;
// // get login field from options
// const field = this.options.userFields.login;
// // get login query from options
// const query = this.options.queries.login
// // replace table placeholder
// .replace(/{{(table)}}/, table)
// // replace field placeholder
// .replace(/{{(login)}}/, field);
// // fetch user from DB
// const [result] = await this.pool.query(query, [login]);
// //const user = result[0]
// return result[0];
// }
/**
* Authenticates user: stores session in DB and returns authentication token on success, returns false on fail.
* @param {*} login
* @param {*} password
* @param {function: bool} shouldAuthenticate optional async boolean callback function. If returns false, login process won't be finished. Can be used to additional validation, e.g. user credentials. Set callback's .error property to customize error message.
* @returns {string|false} Returns token string or false on fail. Error message is stored in instance's .error property.
*/
async login(login, password, shouldAuthenticate = async () => true) {
const self = this;
self.error = null;
const { tokenLifespan, userFields, errorStringHandler } = this.options;
try {
// get users table name from options
const table = this.options.tables.users;
// get login field from options
const field = userFields.login;
const idField = userFields.id;
const passwordField = userFields.password;
// get login query from options
const query = this.options.queries.login
// replace table placeholder
.replace(/{{(table)}}/, table)
// replace field placeholder
.replace(/{{(login)}}/, field);
// fetch user from DB
const [result] = await this.pool.query(query, [login]);
const user = result[0];
// if user fetched
if (!(user && user[passwordField] && user[idField])) {
this.error = "Error fetching user from DB";
return false;
}
// additional validation via callback
if (!(await shouldAuthenticate(user))) {
// error for additional validation via shouldAuthenticate
// set shouldAuthenticate.error to some error text to customize this specific error.
this.error = shouldAuthenticate.error || "User validation failed";
return false;
}
// create session id
const sessionId = uniqid();
// check the password hash and get token
const token = await auth.auth(
// login data
password,
user.password,
// payload
{ userId: user[idField], sessionId },
// expire to tokenLifeSpan (defaults to 30 minutes)
tokenLifespan
);
// if token received - store session to DB and return token
if (!token) {
this.error = auth.error;
return false;
}
this.token = token;
this.user = user;
// store session to DB
if (await this.storeSession(sessionId, user[idField])) {
return token;
}
this.error = "Error storing session";
return false;
} catch (e) {
// get error string from error string handler
this.error =
typeof errorStringHandler === "function"
? errorStringHandler(e)
: e.message;
return false;
}
}
async register(user) {
this.error = null;
const { value, error } = this.options.verification.user.validate(user);
if (error) {
this.error = error.details[0].message;
return false;
} else {
this.log("Registration user data", value);
// hash the password
const hash = await auth.hash(user.password);
if (hash) {
// replace password with hash
user.password = hash;
// prepare insert statement
const { query, values } = this.prepareInsertStatement(
user,
this.options.tables.users
);
try {
// execute insert query
const [insert] = await this.pool.execute(query, values);
this.log(insert, insert.insertId);
return insert.insertId;
} catch (e) {
this.log("error registering", e.message);
let message = "Error writing user to database";
switch (e.code) {
// catch duplicate entry error
case "ER_DUP_ENTRY":
message = "User with such parameters already exists!";
break;
}
this.error = message;
return false;
}
} else {
this.error = "Error creating password hash. Registration failed";
return false;
}
}
}
async storeSession(sessionId, userId) {
const { session_id, session_user } = this.options.sessionFields;
const q = this.prepareInsertStatement(
{
[session_id]: sessionId,
[session_user]: userId,
},
this.options.tables.sessions
);
try {
this.log("inserting session");
const res = await this.pool.query(q.query, q.values);
this.log("session store result", res);
return true;
} catch (e) {
this.log("error inserting session", e.message);
this.error = e.message;
return false;
}
}
/**
* Prepares insert statement for given table with data from passed item object.
* Returns an object with two elements: {query, values} to be used like: pool.execute(query, values)
* @param {*} item
* @param {*} table
*/
prepareInsertStatement(item, table) {
const fields = "`" + Object.keys(item).join("`, `") + "`";
const placeholders = Object.keys(item).fill("?").join(", "); // "'" + Object.values(item).join("', '") + "'"
const values = Object.values(item);
let query = `INSERT INTO \`${table}\` (${fields}) VALUES(${placeholders});`;
this.log("prepared insert statement", { query, values });
return { query, values };
}
async logout(token) {
const content = auth.decodeToken(token);
if (content) {
const { sessionId, userId } = content;
if (sessionId && userId) {
await this.deleteSesion(sessionId, userId);
} else {
this.log("Session id and user id were not found in token");
}
} else {
this.log("Could not decode token");
}
}
async deleteSesion(sessionId, userId) {
try {
const { session_id, session_user } = this.options.sessionFields;
// const sessionIdField = this.options.sessionFields.session_id
// const userIdField = this.options.userFields.id
const sessionTable = this.options.tables.sessions;
await this.pool.query(
`DELETE FROM ${sessionTable} WHERE ${session_id}=? AND ${session_user}=?`,
[sessionId, userId]
);
this.log("session deleted:", `${sessionId}, ${userId}`);
return true;
} catch (e) {
this.log("deleteSession: " + e.mesage, e);
return false;
}
}
async verifyToken(token) {
this.error = null;
const result = await auth.verifyToken(token);
if (result.error) {
this.error = result.error;
return false;
} else {
return result;
}
}
async renewToken(token) {
try {
const decoded = await auth.decodeToken(token);
if (!decoded) {
return false;
}
// TODO: fetch payload from old token, get new token and return
const { userId, sessionId, iat, exp } = decoded;
// check whether we actually have session ID and user ID
if (!(userId && sessionId)) {
this.error =
"Error renewing token: Somehow the old token didn't hold userId and/or sessionId";
this.log(this.error, decoded);
return false;
}
// verify token
if (!(await this.verifyToken(token))) {
// delete the session if token not verified
if (!(await this.deleteSesion(sessionId, userId))) {
this.log(
`renewToken: could not delete session ${sessionId} for user ${userId}`
);
}
return false;
}
// attempt to fetch expiration time from previous token
const diff = exp - iat;
// difference between exp and iat is the expiration time in seconds.
// if difference is a positive number, use it, divided by 60, otherwise use default 30 minutes
const expireIn = !isNaN(diff) && diff > 0 ? diff / 60 : 30;
// return new token
try {
return await auth.getToken({ userId, sessionId }, expireIn);
} catch (e) {
this.error = "Error fetching new token:" + e.mesage;
this.log(this.error);
return false;
}
} catch (e) {
this.error = "Error renewing token: " + e.message;
this.log(this.error);
return false;
}
}
log(message, params = {}) {
this.options.logger(message, params);
}
}
module.exports = userAuthModel;
module.exports.service = auth;