larvituser 0.18.1 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js DELETED
@@ -1,955 +0,0 @@
1
- 'use strict';
2
-
3
- const topLogPrefix = 'larvituser: index.js: ',
4
- DataWriter = require(__dirname + '/dataWriter.js'),
5
- Intercom = require('larvitamintercom'),
6
- uuidLib = require('uuid'),
7
- Helpers = require(__dirname + '/helpers.js'),
8
- LUtils = require('larvitutils'),
9
- bcrypt = require('bcryptjs'),
10
- async = require('async');
11
-
12
- function User(options, cb) {
13
- const logPrefix = topLogPrefix + 'User() - ',
14
- that = this;
15
-
16
- if (typeof cb !== 'function') {
17
- cb = function () {};
18
- }
19
-
20
- that.options = options || {};
21
-
22
- if ( ! options.log) {
23
- const tmpLUtils = new LUtils();
24
- options.log = new tmpLUtils.Log();
25
- }
26
-
27
- that.options = options;
28
-
29
- for (const key of Object.keys(options)) {
30
- that[key] = options[key];
31
- }
32
-
33
- that.lUtils = new LUtils({'log': that.log});
34
-
35
- if ( ! that.db) {
36
- const err = new Error('Required option db is missing');
37
- that.log.error(logPrefix + err.message);
38
- throw err;
39
- }
40
-
41
- if ( ! that.exchangeName) {
42
- that.exchangeName = 'larvituser';
43
- }
44
-
45
- if ( ! that.mode) {
46
- that.log.info(logPrefix + 'No "mode" option given, defaulting to "noSync"');
47
- that.mode = 'noSync';
48
- } else if (['noSync', 'master', 'slave'].indexOf(that.mode) === - 1) {
49
- const err = new Error('Invalid "mode" option given: "' + that.mode + '"');
50
- that.log.error(logPrefix + err.message);
51
- throw err;
52
- }
53
-
54
- if ( ! that.intercom) {
55
- that.log.info(logPrefix + 'No "intercom" option given, defaulting to "loopback interface"');
56
- that.intercom = new Intercom('loopback interface');
57
- }
58
-
59
- that.dataWriter = new DataWriter({
60
- 'exchangeName': that.exchangeName,
61
- 'intercom': that.intercom,
62
- 'mode': that.mode,
63
- 'log': that.log,
64
- 'db': that.db,
65
- 'amsync_host': that.options.amsync_host || null,
66
- 'amsync_minPort': that.options.amsync_minPort || null,
67
- 'amsync_maxPort': that.options.amsync_maxPort || null
68
- }, function (err) {
69
- if (err) return cb(err);
70
-
71
- that.helpers = new Helpers({
72
- 'dataWriter': that.dataWriter,
73
- 'log': that.log,
74
- 'db': that.db
75
- });
76
-
77
- cb();
78
- });
79
- };
80
-
81
- /**
82
- * Add a single user field to database
83
- *
84
- * @param str userUuid
85
- * @param str fieldName
86
- * @param str fieldValue
87
- * @param func cb(err)
88
- */
89
- User.prototype.addUserDataField = function addUserDataField(userUuid, fieldName, fieldValue, cb) {
90
- const fields = {},
91
- that = this;
92
-
93
- fields[fieldName] = fieldValue;
94
-
95
- that.addUserDataFields(userUuid, fields, cb);
96
- };
97
-
98
- /**
99
- * Add user fields
100
- *
101
- * @param str userUuid
102
- * @param obj fields - field name as key, field values as array to that key - ex: {'role': ['admin','user']}
103
- * @param func cb(err)
104
- */
105
- User.prototype.addUserDataFields = function addUserDataFields(userUuid, fields, cb) {
106
- const options = {'exchange': this.exchangeName},
107
- sendObj = {},
108
- that = this;
109
-
110
- // do not want to broadcast msg on queue for no reason
111
- if ( ! fields || Object.keys(fields).length === 0) return cb();
112
-
113
- sendObj.action = 'addUserDataFields';
114
- sendObj.params = {};
115
- sendObj.params.userUuid = userUuid;
116
- sendObj.params.fields = fields;
117
-
118
- that.intercom.send(sendObj, options, function (err, msgUuid) {
119
- if (err) return cb(err);
120
-
121
- that.dataWriter.emitter.once(msgUuid, cb);
122
- });
123
- };
124
-
125
- /**Analyze Optimize Check Repair Truncate Drop * Checks a password for validity
126
- *
127
- * @param str password - plain text password
128
- * @param str hash - hash to check password against
129
- * @param func cb(err, res) res is boolean
130
- */
131
- User.prototype.checkPassword = function checkPassword(password, hash, cb) {
132
- const logPrefix = topLogPrefix + 'checkPassword() - ',
133
- that = this;
134
-
135
- password = password.trim();
136
-
137
- bcrypt.compare(password, hash, function (err, result) {
138
- if (err) {
139
- that.log.error(logPrefix + err.message);
140
- }
141
-
142
- cb(err, result);
143
- });
144
- };
145
-
146
- /**
147
- * Creates a new user (and adds to it to db)
148
- *
149
- * @param str username
150
- * @param str password (plain text) or false for no password (user will not be able to login at all)
151
- * @param obj fields - key, value pairs, where value can be an array of values
152
- * @param uuid custom uuid - if not supplied a random will be generated
153
- * @param func cb(err, user) - user being an instance of the new user
154
- */
155
- User.prototype.create = function create(username, password, userData, uuid, cb) {
156
- const logPrefix = topLogPrefix + 'create() - ',
157
- tasks = [],
158
- that = this;
159
-
160
- let hashedPassword;
161
-
162
- if (typeof uuid === 'function') {
163
- cb = uuid;
164
- uuid = uuidLib.v1();
165
- } else if (typeof userData === 'function') {
166
- userData = undefined;
167
- uuid = uuidLib.v1();
168
- cb = userData;
169
- }
170
-
171
- if (cb === undefined) {
172
- cb = function () {};
173
- }
174
-
175
- if (uuid === undefined) {
176
- uuid = uuidLib.v1();
177
- }
178
-
179
- username = username.trim();
180
-
181
- if (password) {
182
- password = password.trim();
183
- }
184
-
185
- if (username.length === 0) {
186
- const err = new Error('Trying to create user with empty username');
187
- that.log.warn(logPrefix + err.message);
188
- return cb(err);
189
- }
190
-
191
- // Check for username availability
192
- tasks.push(function (cb) {
193
- that.usernameAvailable(username, function (err, result) {
194
- if (err) return cb(err);
195
-
196
- if (result === true) {
197
- that.log.debug(logPrefix + 'Username available: "' + username + '"');
198
- cb();
199
- } else {
200
- const err = new Error('Trying to create user with taken username: "' + username + '"');
201
-
202
- that.log.info(logPrefix + err.message);
203
- cb(err);
204
- }
205
- });
206
- });
207
-
208
- // Hash Password
209
- tasks.push(function (cb) {
210
- if (password === false) {
211
- that.log.debug(logPrefix + 'Password set to empty string for no-login, username: "' + username + '"');
212
- hashedPassword = '';
213
- return cb();
214
- }
215
-
216
- that.hashPassword(password, function (err, hash) {
217
- if (err) return cb(err);
218
-
219
- hashedPassword = hash;
220
- that.log.debug(logPrefix + 'Password hashed, username: "' + username + '"');
221
- cb();
222
- });
223
- });
224
-
225
- // Create all fields
226
- tasks.push(function (cb) {
227
- const tasks = [];
228
-
229
- for (const fieldName of Object.keys(userData)) {
230
- tasks.push(function (cb) {
231
- that.helpers.getFieldUuid(fieldName, cb);
232
- });
233
- }
234
-
235
- async.parallel(tasks, cb);
236
- });
237
-
238
- // Write new user via queue
239
- tasks.push(function (cb) {
240
- const options = {'exchange': that.exchangeName},
241
- sendObj = {};
242
-
243
- sendObj.action = 'create';
244
- sendObj.params = {};
245
- sendObj.params.uuid = uuid;
246
- sendObj.params.username = username;
247
- sendObj.params.password = hashedPassword;
248
- sendObj.params.fields = userData;
249
-
250
- that.intercom.send(sendObj, options, function (err, msgUuid) {
251
- if (err) return cb(err);
252
-
253
- that.dataWriter.emitter.once(msgUuid, cb);
254
- });
255
- });
256
-
257
- async.series(tasks, function (err) {
258
- if (err) return cb(err);
259
-
260
- that.fromUuid(uuid, function (err, user) {
261
- if (err) {
262
- that.log.error(logPrefix + err.message);
263
- return cb(err);
264
- }
265
-
266
- cb(null, user);
267
- });
268
- });
269
- };
270
-
271
- /**
272
- * Create a user object from a field
273
- * IMPORTANT! Only fetches first matching user!
274
- *
275
- * @param str fieldName
276
- * @param str fieldValue
277
- * @param func cb(err, user) - "user" being a new user object or boolean false on failed search
278
- */
279
- User.prototype.fromField = function fromField(fieldName, fieldValue, cb) {
280
- const dbFields = [fieldName.trim(), fieldValue.trim()],
281
- that = this,
282
- sql = 'SELECT uud.userUuid\n' +
283
- 'FROM user_users_data uud\n' +
284
- ' JOIN user_data_fields udf ON udf.uuid = uud.fieldUuid\n' +
285
- 'WHERE udf.name = ? AND uud.data = ?\n' +
286
- 'LIMIT 1';
287
-
288
- that.dataWriter.ready(function (err) {
289
- if (err) return cb(err);
290
- that.db.query(sql, dbFields, function (err, rows) {
291
- if (err) return cb(err);
292
-
293
- if (rows.length === 0) return cb(null, false);
294
-
295
- that.fromUuid(that.lUtils.formatUuid(rows[0].userUuid), cb);
296
- });
297
- });
298
- };
299
-
300
- /**
301
- * Create a user object from fields
302
- * IMPORTANT! Only fetches first matching user that matches all fields!
303
- *
304
- * @param obj fields - {'fieldName': 'fieldValue', 'fieldName2': 'fieldValue2'}
305
- * @param func cb(err, user) - "user" being a new user object or boolean false on failed search
306
- */
307
- User.prototype.fromFields = function fromFields(fields, cb) {
308
- const dbFields = [],
309
- that = this;
310
-
311
- let sql = 'SELECT uuid FROM user_users u\nWHERE\n 1 + 1\n';
312
-
313
- for (const fieldName of Object.keys(fields)) {
314
- sql += ' AND uuid IN (SELECT userUuid FROM user_users_data WHERE data = ? AND fieldUuid = (SELECT uuid FROM user_data_fields WHERE name = ?))\n';
315
- dbFields.push(fields[fieldName].trim());
316
- dbFields.push(fieldName.trim());
317
- }
318
-
319
- sql += 'LIMIT 1';
320
-
321
- that.dataWriter.ready(function (err) {
322
- if (err) return cb(err);
323
- that.db.query(sql, dbFields, function (err, rows) {
324
- if (err) return cb(err);
325
-
326
- if (rows.length === 0) return cb(null, false);
327
-
328
- that.fromUuid(that.lUtils.formatUuid(rows[0].uuid), cb);
329
- });
330
- });
331
- };
332
-
333
- /**
334
- * Create a user object from username and password
335
- *
336
- * @param str username
337
- * @param str password
338
- * @param func cb(err, user) - "user" being a new user object or boolean false on failed login
339
- */
340
- User.prototype.fromUserAndPass = function fromUserAndPass(username, password, cb) {
341
- const logPrefix = topLogPrefix + 'fromUserAndPass() - ',
342
- tasks = [],
343
- that = this;
344
-
345
- let hashedPassword,
346
- userUuid,
347
- userObj;
348
-
349
- username = username.trim();
350
- password = password.trim();
351
-
352
- tasks.push(function (cb) {
353
- that.dataWriter.ready(cb);
354
- });
355
-
356
- tasks.push(function (cb) {
357
- const dbFields = [username],
358
- sql = 'SELECT uuid, password FROM user_users WHERE username = ?';
359
-
360
- that.db.query(sql, dbFields, function (err, rows) {
361
- if (err) return cb(err);
362
-
363
- if (rows.length === 0) {
364
- userObj = false;
365
- return cb();
366
- }
367
-
368
- hashedPassword = rows[0].password;
369
- userUuid = rows[0].uuid;
370
- cb();
371
- });
372
- });
373
-
374
- tasks.push(function (cb) {
375
- if ( ! hashedPassword) return cb();
376
-
377
- that.checkPassword(password, hashedPassword, function (err, res) {
378
- if (err) {
379
- that.log.error(logPrefix + err.message);
380
- return cb(err);
381
- }
382
-
383
- if (res === false) {
384
- userObj = false;
385
- return cb();
386
- }
387
-
388
- that.fromUuid(that.lUtils.formatUuid(userUuid), function (err, result) {
389
- userObj = result;
390
- if (err) userObj = false;
391
- cb(err);
392
- });
393
- });
394
- });
395
-
396
- async.series(tasks, function (err) {
397
- cb(err, userObj);
398
- });
399
- };
400
-
401
- /**
402
- * Create a user object from username
403
- *
404
- * @param str username
405
- * @param func cb(err, user) - "user" being a new user object
406
- */
407
- User.prototype.fromUsername = function fromUsername(username, cb) {
408
- const logPrefix = topLogPrefix + 'fromUsername() - ',
409
- dbFields = [],
410
- that = this,
411
- sql = 'SELECT uuid FROM user_users WHERE username = ?';
412
-
413
- username = username.trim();
414
- dbFields.push(username);
415
-
416
- that.dataWriter.ready(function (err) {
417
- if (err) return cb(err);
418
-
419
- that.db.query(sql, dbFields, function (err, rows) {
420
- if (err) return cb(err);
421
-
422
- if (rows.length === 0) {
423
- that.log.debug(logPrefix + 'No user found for username: "' + username + '"');
424
- return cb(null, false);
425
- }
426
-
427
- // Use fromUuid() to get the user instance
428
- that.fromUuid(that.lUtils.formatUuid(rows[0].uuid), cb);
429
- });
430
- });
431
- };
432
-
433
- /**
434
- * Instanciate user object from user id
435
- *
436
- * @param int userUuid
437
- * @param func cb(err, userObj) - userObj will be false if no user is found
438
- */
439
- User.prototype.fromUuid = function fromUuid(userUuid, cb) {
440
- const userUuidBuf = this.lUtils.uuidToBuffer(userUuid),
441
- logPrefix = topLogPrefix + 'fromUuid() - ',
442
- returnObj = new UserBase(this),
443
- dbFields = [userUuidBuf],
444
- that = this,
445
- sql = 'SELECT\n' +
446
- ' u.uuid,\n' +
447
- ' u.username,\n' +
448
- ' u.password,\n' +
449
- ' uf.uuid AS fieldUuid,\n' +
450
- ' uf.name AS fieldName,\n' +
451
- ' ud.data AS fieldData\n' +
452
- 'FROM\n' +
453
- ' user_users u\n' +
454
- ' LEFT JOIN user_users_data ud ON ud.userUuid = u.uuid\n' +
455
- ' LEFT JOIN user_data_fields uf ON uf.uuid = ud.fieldUuid\n' +
456
- 'WHERE u.uuid = ?';
457
-
458
- if ( ! userUuidBuf) {
459
- const err = new Error('Invalid userUuid');
460
- that.log.warn(logPrefix + err.message);
461
- return cb(err);
462
- }
463
-
464
- that.dataWriter.ready(function (err) {
465
- if (err) return cb(err);
466
-
467
- that.db.query(sql, dbFields, function (err, rows) {
468
- if (err) return cb(err);
469
-
470
- if (rows.length === 0) {
471
- const err = new Error('No user found for userUuid: "' + userUuid + '"');
472
- that.log.debug(logPrefix + err.message);
473
- return cb(null, false);
474
- }
475
-
476
- returnObj.uuid = that.lUtils.formatUuid(rows[0].uuid);
477
- returnObj.username = rows[0].username;
478
-
479
- if (rows[0].password === '') {
480
- returnObj.passwordIsFalse = true;
481
- } else {
482
- returnObj.passwordIsFalse = false;
483
- }
484
-
485
- for (let i = 0; rows[i] !== undefined; i ++) {
486
- const row = rows[i];
487
-
488
- if (row.fieldUuid) {
489
- if (returnObj.fields[row.fieldName] === undefined) {
490
- returnObj.fields[row.fieldName] = [];
491
- }
492
-
493
- returnObj.fields[row.fieldName].push(row.fieldData);
494
- }
495
- }
496
-
497
- cb(null, returnObj);
498
- });
499
- });
500
- };
501
-
502
- /**
503
- * Get field data for a user
504
- *
505
- * @param str userUuid
506
- * @param str fieldName
507
- * @param func cb(err, data) - data is always an array of data (or empty array)
508
- */
509
- User.prototype.getFieldData = function getFieldData(userUuid, fieldName, cb) {
510
- const logPrefix = topLogPrefix + 'getFieldData() - ',
511
- that = this;
512
-
513
- that.helpers.getFieldUuid(fieldName, function (err, fieldUuid) {
514
- const userUuidBuffer = that.lUtils.uuidToBuffer(userUuid),
515
- fieldUuidBuffer = that.lUtils.uuidToBuffer(fieldUuid),
516
- dbFields = [userUuidBuffer, fieldUuidBuffer],
517
- sql = 'SELECT data FROM user_users_data WHERE userUuid = ? AND fieldUuid = ?';
518
-
519
- if (err) return cb(err);
520
-
521
- if (userUuidBuffer === false) {
522
- const err = new Error('Invalid user uuid');
523
- that.log.verbose(logPrefix + err.message);
524
- return cb(err);
525
- }
526
-
527
- if (fieldUuidBuffer === false) {
528
- const err = new Error('Invalid field uuid');
529
- that.log.verbose(logPrefix + err.message);
530
- return cb(err);
531
- }
532
-
533
- that.db.query(sql, dbFields, function (err, rows) {
534
- const data = [];
535
-
536
- if (err) return cb(err);
537
-
538
- for (let i = 0; rows[i] !== undefined; i ++) {
539
- data.push(rows[i].data);
540
- }
541
-
542
- cb(null, data);
543
- });
544
- });
545
- };
546
-
547
- /**
548
- * Hashes a new password
549
- *
550
- * @param str password
551
- * @param func cb(err, hash)
552
- */
553
- User.prototype.hashPassword = function hashPassword(password, cb) {
554
- const logPrefix = topLogPrefix + 'hashPassword() - ',
555
- that = this;
556
-
557
- if ( ! password) {
558
- password = '';
559
- }
560
-
561
- password = password.trim();
562
-
563
- bcrypt.hash(password, 10, function (err, hash) {
564
- if (err) {
565
- that.log.error(logPrefix + err.message);
566
- }
567
-
568
- cb(err, hash);
569
- });
570
- };
571
-
572
- /**
573
- * Replace all fields
574
- * IMPORTANT!!! Will clear all data not given in the fields parameter
575
- *
576
- * @param str userUuid
577
- * @param obj fields - field name as key, field values as array to that key - ex: {'role': ['admin','user']}
578
- * @param func cb(err)
579
- */
580
- User.prototype.replaceUserFields = function replaceUserFields(uuid, fields, cb) {
581
- const options = {'exchange': this.dataWriter.exchangeName},
582
- sendObj = {},
583
- that = this;
584
-
585
- that.fromUuid(uuid, function (err, user) {
586
- if (err) return cb(err);
587
-
588
- sendObj.action = 'replaceFields';
589
- sendObj.params = {};
590
- sendObj.params.username = user.username;
591
- sendObj.params.userUuid = uuid;
592
- sendObj.params.fields = fields;
593
-
594
- that.intercom.send(sendObj, options, function (err, msgUuid) {
595
- if (err) return cb(err);
596
-
597
- that.dataWriter.emitter.once(msgUuid, cb);
598
- });
599
- });
600
- };
601
-
602
- /**
603
- * Remove a user
604
- *
605
- * @param uuid userUuid
606
- * @param func cb(err)
607
- */
608
- User.prototype.rmUser = function rmUser(userUuid, cb) {
609
- const options = {'exchange': this.dataWriter.exchangeName},
610
- sendObj = {},
611
- that = this;
612
-
613
- sendObj.action = 'rmUser';
614
- sendObj.params = {};
615
- sendObj.params.userUuid = userUuid;
616
-
617
- that.intercom.send(sendObj, options, function (err, msgUuid) {
618
- if (err) return cb(err);
619
-
620
- that.dataWriter.emitter.once(msgUuid, cb);
621
- });
622
- };
623
-
624
- /**
625
- * Remove a user field
626
- *
627
- * @param uuid userUuid
628
- * @param str fieldName
629
- * @param func cb(err)
630
- */
631
- User.prototype.rmUserField = function rmUserField(userUuid, fieldName, cb) {
632
- const options = {'exchange': this.dataWriter.exchangeName},
633
- sendObj = {},
634
- that = this;
635
-
636
- sendObj.action = 'rmUserField';
637
- sendObj.params = {};
638
- sendObj.params.userUuid = userUuid;
639
- sendObj.params.fieldName = fieldName;
640
-
641
- that.intercom.send(sendObj, options, function (err, msgUuid) {
642
- if (err) return cb(err);
643
-
644
- that.dataWriter.emitter.once(msgUuid, cb);
645
- });
646
- };
647
-
648
- /**
649
- * Set password for a user
650
- *
651
- * @param str userUuid
652
- * @param str newPassword (plain text) or false for no valid password (user will not be able to login at all)
653
- * @param func cb(err)
654
- */
655
- User.prototype.setPassword = function setPassword(userUuid, newPassword, cb) {
656
- const tasks = [],
657
- that = this;
658
-
659
- let hashedPassword;
660
-
661
- tasks.push(function (cb) {
662
- if (newPassword) {
663
- that.hashPassword(newPassword.trim(), function (err, hash) {
664
- hashedPassword = hash;
665
- cb(err);
666
- });
667
- } else {
668
- hashedPassword = false;
669
- cb();
670
- }
671
- });
672
-
673
- tasks.push(function (cb) {
674
- const options = {'exchange': that.dataWriter.exchangeName},
675
- sendObj = {};
676
-
677
- sendObj.action = 'setPassword';
678
- sendObj.params = {};
679
- sendObj.params.userUuid = userUuid;
680
- sendObj.params.password = hashedPassword;
681
-
682
- that.intercom.send(sendObj, options, function (err, msgUuid) {
683
- if (err) return cb(err);
684
-
685
- that.dataWriter.emitter.once(msgUuid, cb);
686
- });
687
- });
688
-
689
- async.series(tasks, cb);
690
- };
691
-
692
- /**
693
- * Set the username for a user
694
- *
695
- * @param str userUuid
696
- * @param str newusername
697
- * @param fucn cb(err)
698
- */
699
- User.prototype.setUsername = function setUsername(userUuid, newUsername, cb) {
700
- const userUuidBuf = this.lUtils.uuidToBuffer(userUuid),
701
- logPrefix = topLogPrefix + 'setUsername() - ',
702
- that = this;
703
-
704
- newUsername = newUsername.trim();
705
-
706
- if ( ! newUsername) {
707
- const err = new Error('No new username supplied');
708
- that.log.warn(logPrefix + err.message);
709
- return cb(err);
710
- }
711
-
712
- if (userUuidBuf === false) {
713
- const err = new Error('Invalid user uuid');
714
- that.log.warn(logPrefix + err.message);
715
- return cb(err);
716
- }
717
-
718
- that.dataWriter.ready(function (err) {
719
- if (err) return cb(err);
720
-
721
- that.db.query('SELECT uuid FROM user_users WHERE username = ? AND uuid != ?', [newUsername, userUuidBuf], function (err, rows) {
722
- const options = {'exchange': that.dataWriter.exchangeName},
723
- sendObj = {};
724
-
725
- if (err) return cb(err);
726
-
727
- if (rows.length && that.lUtils.formatUuid(rows[0].uuid) !== userUuid) {
728
- const err = new Error('Username is already taken');
729
- return cb(err);
730
- }
731
-
732
- sendObj.action = 'setUsername';
733
- sendObj.params = {};
734
- sendObj.params.userUuid = userUuid;
735
- sendObj.params.username = newUsername;
736
-
737
- that.intercom.send(sendObj, options, function (err, msgUuid) {
738
- if (err) return cb(err);
739
-
740
- that.dataWriter.emitter.once(msgUuid, cb);
741
- });
742
- });
743
- });
744
- };
745
-
746
- /**
747
- * Checks if a unsername is available
748
- *
749
- * @param str username
750
- * @param func cb(err, result) - result is a bolean
751
- */
752
- User.prototype.usernameAvailable = function usernameAvailable(username, cb) {
753
- const that = this;
754
-
755
- let isAvailable;
756
-
757
- username = username.trim();
758
-
759
- that.dataWriter.ready(function (err) {
760
- if (err) return cb(err);
761
-
762
- that.db.query('SELECT uuid FROM user_users WHERE username = ?', [username], function (err, rows) {
763
- if (err) return cb(err);
764
-
765
- if (rows.length === 0) {
766
- isAvailable = true;
767
- } else {
768
- isAvailable = false;
769
- }
770
-
771
- cb(null, isAvailable);
772
- });
773
- });
774
- };
775
-
776
- function UserBase(userInstance) {
777
- const that = this;
778
-
779
- that.fields = {};
780
-
781
- that.userInstance = userInstance;
782
- that.log = that.userInstance.log;
783
- }
784
-
785
- /**
786
- * Add a field with value
787
- *
788
- * @param str name
789
- * @param str value
790
- * @param func cb(err)
791
- */
792
- UserBase.prototype.addField = function addField(name, value, cb) {
793
- const logPrefix = topLogPrefix + 'UserBase.addField() - ',
794
- that = this;
795
-
796
- if (that.uuid === undefined) {
797
- const err = new Error('Cannot add field; no user loaded');
798
- that.log.verbose(logPrefix + err.message);
799
- return cb(err);
800
- }
801
-
802
- that.userInstance.addUserDataField(that.uuid, name, value, function (err) {
803
- if (err) return cb(err);
804
-
805
- if (that.fields[name] === undefined) {
806
- that.fields[name] = [];
807
- }
808
-
809
- that.fields[name].push(value);
810
- cb();
811
- });
812
- };
813
-
814
- /**
815
- * Adds one or more fields with values to the user object. Does not overwrite existing values. It is possible to add the same value multiple times
816
- *
817
- * @param obj fields - field name as key, field values as array to that key - ex: {'role': ['admin','user']}
818
- * @param func cb(err)
819
- */
820
- UserBase.prototype.addFields = function addFields(fields, cb) {
821
- const logPrefix = topLogPrefix + 'UserBase.addFields() - ',
822
- that = this;
823
-
824
- if (that.uuid === undefined) {
825
- const err = new Error('Cannot add field; no user loaded');
826
- that.log.verbose(logPrefix + err.message);
827
- return cb(err);
828
- }
829
-
830
- that.userInstance.addUserDataFields(that.uuid, fields, function (err) {
831
- if (err) return cb(err);
832
-
833
- for (let key in fields) {
834
- if (that.fields[key] === undefined) {
835
- that[key] = fields[key];
836
- } else {
837
- for (let value of fields[key]) {
838
- that.fields[key].push(value);
839
- }
840
- }
841
- }
842
-
843
- cb();
844
- });
845
- };
846
-
847
- /**
848
- * Replace all fields
849
- * IMPORTANT!!! Will clear all data not given in the fields parameter
850
- *
851
- * @param obj fields - field name as key, field values as array to that key - ex: {'role': ['admin','user']}
852
- * @param func cb(err)
853
- */
854
- UserBase.prototype.replaceFields = function replaceFields(fields, cb) {
855
- const logPrefix = topLogPrefix + 'UserBase.replaceFields() - ',
856
- that = this;
857
-
858
- if (that.uuid === undefined) {
859
- const err = new Error('Cannot replace fields; no user loaded');
860
- that.log.verbose(logPrefix + err.message);
861
- return cb(err);
862
- }
863
-
864
- that.userInstance.replaceUserFields(that.uuid, fields, function (err) {
865
- if (err) return cb(err);
866
-
867
- // Reload everything
868
- that.userInstance.fromUuid(that.uuid, function (err, user) {
869
- if (err) return cb(err);
870
-
871
- that.fields = user.fields;
872
- cb();
873
- });
874
- });
875
- };
876
-
877
- UserBase.prototype.rm = function rm(cb) {
878
- const logPrefix = topLogPrefix + 'UserBase.rm() - ',
879
- that = this;
880
-
881
- if (that.uuid === undefined) {
882
- const err = new Error('Cannot remove field; no user loaded');
883
- that.log.verbose(logPrefix + err.message);
884
- return cb(err);
885
- }
886
-
887
- that.userInstance.rmUser(that.uuid, function (err) {
888
- if (err) return cb(err);
889
-
890
- delete that.uuid;
891
- delete that.username;
892
-
893
- that.fields = {};
894
-
895
- cb();
896
- });
897
- };
898
-
899
- /**
900
- * Remove a field from this user
901
- *
902
- * @param str name
903
- * @param func cb(err)
904
- */
905
- UserBase.prototype.rmField = function rmField(name, cb) {
906
- const logPrefix = topLogPrefix + 'UserBase.rmField() - ',
907
- that = this;
908
-
909
- if (that.uuid === undefined) {
910
- const err = new Error('Cannot remove field; no user loaded');
911
- that.log.verbose(logPrefix + err.message);
912
- return cb(err);
913
- }
914
-
915
- that.userInstance.rmUserField(that.uuid, name, function (err) {
916
- if (err) return cb(err);
917
-
918
- delete that.fields[name];
919
- cb();
920
- });
921
- };
922
-
923
- UserBase.prototype.setPassword = function (newPassword, cb) {
924
- const logPrefix = topLogPrefix + 'UserBase.setPassword() - ',
925
- that = this;
926
-
927
- if (that.uuid === undefined) {
928
- const err = new Error('Cannot set password; no user loaded');
929
- that.log.verbose(logPrefix + err.message);
930
- return cb(err);
931
- }
932
-
933
- that.userInstance.setPassword(that.uuid, newPassword, cb);
934
- };
935
-
936
- UserBase.prototype.setUsername = function (newUsername, cb) {
937
- const logPrefix = topLogPrefix + 'UserBase.setUsername() - ',
938
- that = this;
939
-
940
- if (that.uuid === undefined) {
941
- const err = new Error('Cannot set username; no user loaded');
942
- that.log.verbose(logPrefix + err.message);
943
- return cb(err);
944
- }
945
-
946
- that.userInstance.setUsername(that.uuid, newUsername, function (err) {
947
- if (err) return cb(err);
948
-
949
- that.username = newUsername;
950
- cb();
951
- });
952
- };
953
-
954
- exports = module.exports = User;
955
- exports.Users = require(__dirname + '/users.js');