-
Notifications
You must be signed in to change notification settings - Fork 30
/
user.js
544 lines (429 loc) · 14.8 KB
/
user.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/* Copyright (c) 2012-2023 Richard Rodger and other contributors, MIT License. */
'use strict'
const Assert = require('assert')
const Crypto = require('crypto')
const Seneca = require('seneca')
const Uuid = require('uuid')
const { Nid } = Seneca.util
module.exports = user
module.exports.errors = {}
const intern = (module.exports.intern = make_intern())
module.exports.defaults = {
test: false,
salt: {
bytelen: 16,
format: 'hex',
},
pepper: '',
rounds: 11111,
fields: {
standard: ['handle', 'email', 'name', 'active', 'profile'],
},
onetime: {
expire: 15 * 60 * 1000, // 15 minutes
},
password: {
minlen: 8,
},
handle: {
minlen: 3,
maxlen: 15,
reserved: ['guest', 'visitor'],
must_match: (handle) => handle.match(/^[a-z0-9_]+$/),
// a function returning an array of strings
must_not_contain: Nid.curses,
sanitize: (handle) => handle.replace(/[^a-z0-9_]/g, '_'),
downcase: true,
},
limit: 111, // default result limit
generate_salt: intern.generate_salt,
ensure_handle: intern.ensure_handle,
make_handle: intern.make_handle,
make_token: intern.make_token,
}
function user(options) {
var seneca = this
var ctx = intern.make_ctx({}, options)
// TODO @seneca/audit - record user modifications - e.g activate
// TODO @seneca/microcache - short duration cache of msg responses
seneca
.fix('sys:user')
.message('register:user', intern.make_msg('register_user', ctx))
.message('get:user', intern.make_msg('get_user', ctx))
.message('list:user', intern.make_msg('list_user', ctx))
.message('adjust:user', intern.make_msg('adjust_user', ctx))
.message('update:user', intern.make_msg('update_user', ctx))
.message('remove:user', intern.make_msg('remove_user', ctx))
.message('login:user', intern.make_msg('login_user', ctx))
.message('logout:user', intern.make_msg('logout_user', ctx))
.message('list:login', intern.make_msg('list_login', ctx))
.message('make:verify', intern.make_msg('make_verify', ctx))
.message('list:verify', intern.make_msg('list_verify', ctx))
.message('change:pass', intern.make_msg('change_pass', ctx))
.message('change:handle', intern.make_msg('change_handle', ctx))
.message('change:email', intern.make_msg('change_email', ctx))
.message('check:handle', intern.make_msg('check_handle', ctx))
.message('check:verify', intern.make_msg('check_verify', ctx))
.message('check:exists', intern.make_msg('check_exists', ctx))
.message('auth:user', intern.make_msg('auth_user', ctx))
.message('hook:password,cmd:encrypt', intern.make_msg('cmd_encrypt', ctx))
.message('hook:password,cmd:pass', intern.make_msg('cmd_pass', ctx))
// TODO seneca.alias method?
.message('change:password', intern.make_msg('change_pass', ctx))
return {
exports: {
find_user: async function (seneca, msg, special_ctx) {
var merged_ctx =
null == special_ctx ? ctx : seneca.util.deep({}, ctx, special_ctx)
return intern.find_user(seneca, msg, merged_ctx)
},
},
}
}
function make_intern() {
return {
SV: 1, // semantic version, used for data migration
make_msg: function (msg_fn, ctx) {
return require('./lib/' + msg_fn)(ctx)
},
make_ctx: function (initial_ctx, options) {
Assert(initial_ctx)
Assert(options)
// convert arrays to lookup maps
var handle = { reserved: {} }
for (var i = 0; i < options.handle.reserved.length; i++) {
handle.reserved[options.handle.reserved[i]] = true
}
var must_not_contain_array = options.handle.must_not_contain()
var must_not_contain_map = {}
for (i = 0; i < must_not_contain_array.length; i++) {
must_not_contain_map[must_not_contain_array[i]] = true
}
handle.must_not_contain = () => must_not_contain_map
return Object.assign(
{
options,
intern,
// Standard entity canons
sys_user: 'sys/user',
sys_login: 'sys/login',
sys_verify: 'sys/verify',
// Standard user fields to load - keep data volume low by default
standard_user_fields: options.fields.standard,
// Convenience query fields - msg.email etc.
convenience_fields: 'id,user_id,handle,email,name'.split(','),
handle,
},
initial_ctx,
)
},
user_exists: async function (seneca, msg, ctx) {
ctx.fields = []
var found = await intern.find_user(seneca, msg, ctx)
return found.ok
},
find_user: async function (seneca, msg, ctx) {
// User may already be provided in parameters.
var user = msg.user && msg.user.entity$ ? msg.user : null
// user_q when q used for caller's query
var msg_user_query = msg.user_q || msg.q || {}
if (null == user) {
msg = intern.fix_nick_handle(msg, ctx.options)
var why = null
// allow use of `q` (or `user_q`) to specify query,
// or `user` prop (q has precedence)
var q = Object.assign(
{},
msg.user || {},
msg.user_data || {},
msg_user_query,
)
// can only use one convenience field - they are ordered by decreasing
// precedence
for (var cfI = 0; cfI < ctx.convenience_fields.length; cfI++) {
var f = ctx.convenience_fields[cfI]
if (null != msg[f]) {
q[f] = msg[f]
break
}
}
// `user_id` is an alias for `id`
if (null == q.id && null != q.user_id) {
q.id = q.user_id
}
delete q.user_id
// TODO waiting for fix: https://github.com/senecajs/seneca-entity/issues/57
if (0 < Object.keys(seneca.util.clean(q)).length) {
// Add additional fields to standard fields.
var fields = Array.isArray(msg.fields) ? msg.fields : []
q.fields$ = [
...new Set((q.fields$ || fields).concat(ctx.standard_user_fields)),
]
// These are the unique fields
if (null == q.id && null == q.handle && null == q.email) {
var users = await seneca.entity(ctx.sys_user).list$(q)
if (1 === users.length) {
user = intern.fix_nick_handle(users[0], ctx.options)
} else if (1 < users.length) {
// This is bad, as you could operate on another user
why = 'multiple-matching-users'
}
} else {
// Use load$ to trigger entity cache
user = await seneca.entity(ctx.sys_user).load$(q)
}
} else {
why = 'no-user-query'
}
}
var out = { ok: null != user, user: user || null }
if (null == user) {
out.why = why || 'user-not-found'
}
return out
},
// expects normalized user data
build_pass_fields: async function (seneca, user_data, ctx) {
var pass = user_data.pass
var repeat = user_data.repeat // optional
var salt = user_data.salt
if ('string' === typeof repeat && repeat !== pass) {
return { ok: false, why: 'repeat-password-mismatch' }
}
var res = await seneca.post('sys:user,hook:password,cmd:encrypt', {
pass: pass,
salt: salt,
whence: 'build',
})
if (res.ok) {
return {
ok: true,
fields: {
pass: res.pass,
salt: res.salt,
},
}
} else {
return {
ok: false,
why: res.why,
/* $lab:coverage:off$ */
details: res.details || {},
/* $lab:coverage:on$ */
}
}
},
generate_salt: function (options) {
return Crypto.randomBytes(options.salt.bytelen).toString(
options.salt.format,
)
},
// Automate migration of nick->handle. Removes nick.
// Assume update value will be saved elsewhere in due course.
fix_nick_handle: function (data, options) {
Assert(options)
if (null == data) {
return data
}
var downcase = options.handle.downcase
if (null != data.nick) {
data.handle = null != data.handle ? data.handle : data.nick
data.handle = downcase ? data.handle.toLowerCase() : data.handle
delete data.nick
}
if (null != data.user && null != data.user.nick) {
data.user.handle =
null != data.user.handle ? data.user.handle : data.user.nick
data.user.handle = downcase
? data.user.handle.toLowerCase()
: data.user.handle
delete data.user.nick
}
if (null != data.user_data && null != data.user_data.nick) {
data.user_data.handle =
null != data.user_data.handle
? data.user_data.handle
: data.user_data.nick
data.user_data.handle = downcase
? data.user_data.handle.toLowerCase()
: data.user_data.handle
delete data.user_data.nick
}
if (null != data.q && null != data.q.nick) {
data.q.handle = null != data.q.handle ? data.q.handle : data.q.nick
data.q.handle = downcase ? data.q.handle.toLowerCase() : data.q.handle
delete data.q.nick
}
return data
},
// expects normalized user data
ensure_handle: function (user_data, options) {
var handle = user_data.handle
if ('string' != typeof handle) {
var email = user_data.email
// NOTE: assumes email already validated in user_data
if (null != email) {
handle =
email.split('@')[0].toLowerCase() +
('' + Math.random()).substring(2, 6)
handle = options.handle
.sanitize(handle)
.substring(0, options.handle.maxlen)
} else {
handle = options.make_handle()
}
}
handle = handle.substring(0, options.handle.maxlen)
if (options.handle.downcase) {
handle = handle.toLowerCase()
}
return handle
},
make_handle: Nid({ length: '12', alphabet: 'abcdefghijklmnopqrstuvwxyz' }),
make_token: Uuid.v4, // Random! Don't leak things.
make_login: async function (spec) {
/* $lab:coverage:off$ */
var seneca = Assert(spec.seneca) || spec.seneca
var user = Assert(spec.user) || spec.user
var why = Assert(spec.why) || spec.why
var ctx = Assert(spec.ctx) || spec.ctx
var options = Assert(ctx.options) || ctx.options
/* $lab:coverage:on$ */
var login_data = spec.login_data || {} // custom data fields
var onetime = !!spec.onetime
var full_login_data = {
// custom data fields for login entry
...login_data,
// token field should be indexed for quick lookups
token: options.make_token(),
// deliberately copied
handle: user.handle,
email: user.email,
user_id: user.id,
when: new Date().toISOString(),
active: true,
why: why,
sv: intern.SV,
}
if (onetime) {
full_login_data.onetime_active = true
;(full_login_data.onetime_token = options.make_token()),
(full_login_data.onetime_expiry = Date.now() + options.onetime.expire)
}
var login = await seneca
.entity(ctx.sys_login)
.data$(full_login_data)
.save$()
return login
},
load_user_fields: function (msg, ...rest) {
/* $lab:coverage:off$ */
// Seventh Circle of Hell, aka node < 12
rest.flat =
'function' == typeof rest.flat
? rest.flat
: function () {
return this.reduce((a, y) => {
return Array.isArray(y) ? a.concat(y) : (a.push(y), a)
}, [])
}.bind(rest)
/* $lab:coverage:on$ */
var fields = rest
.flat()
.filter((f) => 'string' === typeof f && 0 < f.length)
msg.q = msg.q || {}
msg.q.fields$ = msg.q.fields$ || []
msg.q.fields$ = msg.q.fields$.concat(fields)
msg.q.fields$ = [...new Set(msg.q.fields$)] // remove dups
return msg
},
valid_email: async function (seneca, email, ctx) {
// TODO: improve
var email_valid = /@/.test(email)
if (!email_valid) {
return { ok: false, email: email, why: 'email-invalid-format' }
}
var email_taken = await intern.find_user(seneca, { email: email }, ctx)
return {
ok: !email_taken.ok,
email: email,
why: email_taken.ok ? 'email-exists' : null,
}
},
valid_handle: async function (seneca, handle, ctx) {
var options = ctx.options
if ('string' != typeof handle) {
return { ok: false, why: 'not-string', details: { handle: handle } }
}
handle = options.handle.downcase ? handle.toLowerCase() : handle
if (ctx.handle.reserved[handle]) {
return { ok: false, why: 'reserved', details: { handle: handle } }
}
var mnc = ctx.handle.must_not_contain()
if (mnc[handle]) {
return {
ok: false,
why: 'disallowed',
details: { handle_base64: Buffer.from(handle).toString('base64') },
}
}
if (!options.handle.must_match(handle)) {
return { ok: false, why: 'invalid-chars', details: { handle: handle } }
}
if (handle.length < options.handle.minlen) {
return {
ok: false,
why: 'handle-too-short',
details: {
handle: handle,
handle_length: handle.length,
minimum: options.handle.minlen,
},
}
}
if (options.handle.maxlen < handle.length) {
return {
ok: false,
why: 'handle-too-long',
details: {
handle: handle,
handle_length: handle.length,
maximum: options.handle.maxlen,
},
}
}
var exists = await intern.user_exists(seneca, { handle: handle }, ctx)
if (exists) {
return {
ok: false,
why: 'handle-exists',
details: { handle: handle },
}
}
return { ok: true, handle: handle }
},
normalize_user_data: function (msg, ctx) {
msg = intern.fix_nick_handle(msg, ctx.options)
var msg_user = msg.user || {}
var msg_user_data = msg.user_data || {}
var top_data = {}
var top_fields = ctx.convenience_fields.concat([
'pass',
'password',
'repeat',
])
top_fields.forEach((f) => null == msg[f] || (top_data[f] = msg[f]))
var user_data = Object.assign({}, msg_user, msg_user_data, top_data)
// password -> pass
if (null != user_data.password) {
user_data.pass = user_data.pass || user_data.password
delete user_data.password
}
// strip undefineds
Object.keys(user_data).forEach(
(k) => void 0 === user_data[k] && delete user_data[k],
)
return user_data
},
}
}