sumba 2.34.4 → 2.35.0
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/docs/Sumba.html +1 -1
- package/docs/data/search.json +1 -1
- package/docs/global.html +1 -1
- package/docs/index.html +1 -1
- package/docs/index.js.html +1564 -233
- package/docs/lib_constant.js.html +98 -0
- package/docs/lib_token-schema.js.html +47 -0
- package/extend/bajo/hook.js +27 -192
- package/extend/bajo/intl/en-US.json +12 -12
- package/extend/bajo/intl/id.json +13 -13
- package/extend/dobo/model.js +27 -1
- package/extend/waibuDb/schema/model-guard.js +2 -2
- package/extend/waibuMpa/extend/waibuAdmin/route/action-guard/@action.js +11 -0
- package/extend/waibuMpa/extend/waibuAdmin/route/{model-guard → query-guard}/@action.js +2 -2
- package/extend/waibuMpa/extend/waibuAdmin/route/team/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/team-setting/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/team-user/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/user/@action.js +1 -1
- package/extend/waibuMpa/extend/waibuAdmin/route/user-setting/@action.js +1 -1
- package/extend/waibuRestApi/route/user/access-token/@type/create.js +1 -1
- package/extend/waibuRestApi/route/user/api-key/get.js +1 -1
- package/extend/waibuRestApi/route/your-stuff/api-key/update.js +1 -1
- package/index.js +1061 -45
- package/lib/constant.js +95 -0
- package/package.json +9 -3
- package/wiki/CHANGES.md +6 -0
- package/lib/create-new-site.js +0 -106
- package/lib/get-site.js +0 -70
- package/lib/get-user.js +0 -89
- package/lib/remove-site.js +0 -39
- package/lib/token-schema.js +0 -29
package/index.js
CHANGED
|
@@ -1,21 +1,18 @@
|
|
|
1
1
|
import path from 'path'
|
|
2
|
-
import createNewSite from './lib/create-new-site.js'
|
|
3
|
-
import removeSite from './lib/remove-site.js'
|
|
4
|
-
import getSite from './lib/get-site.js'
|
|
5
|
-
import { getUserById, getUserByToken, getUserByUsernamePassword } from './lib/get-user.js'
|
|
6
2
|
import { joiPasswordExtendCore } from 'joi-password'
|
|
7
3
|
|
|
8
4
|
const defMultiSite = {
|
|
9
5
|
enabled: false,
|
|
10
|
-
catchAll: 'default'
|
|
11
|
-
admins: []
|
|
6
|
+
catchAll: 'default'
|
|
12
7
|
}
|
|
13
8
|
|
|
14
9
|
/**
|
|
15
|
-
* Plugin factory
|
|
10
|
+
* Plugin factory.
|
|
11
|
+
*
|
|
12
|
+
* **Never** call this function directly!!! It's only-meant to be called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
|
|
16
13
|
*
|
|
17
14
|
* @param {string} pkgName - NPM package name
|
|
18
|
-
* @returns {class
|
|
15
|
+
* @returns {Sumba} Sumba class
|
|
19
16
|
*/
|
|
20
17
|
async function factory (pkgName) {
|
|
21
18
|
const me = this
|
|
@@ -23,13 +20,19 @@ async function factory (pkgName) {
|
|
|
23
20
|
const { cloneDeep, isEmpty } = this.app.lib._
|
|
24
21
|
|
|
25
22
|
/**
|
|
26
|
-
* Sumba class
|
|
23
|
+
* Sumba class definition.
|
|
27
24
|
*
|
|
28
25
|
* @class
|
|
29
26
|
*/
|
|
30
27
|
class Sumba extends this.app.baseClass.Base {
|
|
28
|
+
/**
|
|
29
|
+
* Constructor
|
|
30
|
+
*/
|
|
31
31
|
constructor () {
|
|
32
32
|
super(pkgName, me.app)
|
|
33
|
+
/**
|
|
34
|
+
* @type {TConfig}
|
|
35
|
+
*/
|
|
33
36
|
this.config = {
|
|
34
37
|
multiSite: cloneDeep(defMultiSite),
|
|
35
38
|
xSiteAdmins: [], // format: "<siteAlias>:<username>"
|
|
@@ -41,7 +44,6 @@ async function factory (pkgName) {
|
|
|
41
44
|
model: {}
|
|
42
45
|
},
|
|
43
46
|
waibuMpa: {
|
|
44
|
-
home: 'sumba:/your-stuff/profile',
|
|
45
47
|
icon: 'globe',
|
|
46
48
|
redirect: {
|
|
47
49
|
'/': 'sumba:/your-stuff/profile',
|
|
@@ -164,15 +166,21 @@ async function factory (pkgName) {
|
|
|
164
166
|
}
|
|
165
167
|
}
|
|
166
168
|
this.secureGuards = []
|
|
167
|
-
this.
|
|
169
|
+
this.actionGuards = []
|
|
170
|
+
this.queryGuards = []
|
|
168
171
|
this.attribGuards = []
|
|
169
172
|
this.secureGuards = []
|
|
170
173
|
this.anonymousGuards = []
|
|
171
174
|
|
|
172
175
|
this.unsafeUserFields = ['password']
|
|
173
|
-
this.selfBind(['createNewSite', 'removeSite', 'getSite', 'getUserById', 'getUserByToken', 'getUserByUsernamePassword'])
|
|
174
176
|
}
|
|
175
177
|
|
|
178
|
+
/**
|
|
179
|
+
* Plugin initialization method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
|
|
180
|
+
*
|
|
181
|
+
* @async
|
|
182
|
+
* @method
|
|
183
|
+
*/
|
|
176
184
|
init = async () => {
|
|
177
185
|
this.downloadDir = `${this.app.getPluginDataDir(this.ns)}/download`
|
|
178
186
|
this.app.lib.fs.ensureDirSync(this.downloadDir)
|
|
@@ -182,6 +190,12 @@ async function factory (pkgName) {
|
|
|
182
190
|
}
|
|
183
191
|
}
|
|
184
192
|
|
|
193
|
+
/**
|
|
194
|
+
* Plugin start method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin start.
|
|
195
|
+
*
|
|
196
|
+
* @async
|
|
197
|
+
* @method
|
|
198
|
+
*/
|
|
185
199
|
start = async () => {
|
|
186
200
|
await this.populateRouteGuards()
|
|
187
201
|
if (!this.config.multiSite.enabled) {
|
|
@@ -195,6 +209,13 @@ async function factory (pkgName) {
|
|
|
195
209
|
}
|
|
196
210
|
}
|
|
197
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Populate route guards at start
|
|
214
|
+
*
|
|
215
|
+
* @async
|
|
216
|
+
* @method
|
|
217
|
+
* @param {array} [sites] - List of sites to populate route guards for. If not provided, it will fetch all active sites.
|
|
218
|
+
*/
|
|
198
219
|
populateRouteGuards = async (sites) => {
|
|
199
220
|
const { isString, get, difference } = this.app.lib._
|
|
200
221
|
const { pascalCase } = this.app.lib.aneka
|
|
@@ -273,7 +294,17 @@ async function factory (pkgName) {
|
|
|
273
294
|
}
|
|
274
295
|
}
|
|
275
296
|
|
|
276
|
-
|
|
297
|
+
/**
|
|
298
|
+
* Get authentication setting based on type and source
|
|
299
|
+
*
|
|
300
|
+
* @async
|
|
301
|
+
* @method
|
|
302
|
+
* @private
|
|
303
|
+
* @param {string} type - The type of authentication setting to retrieve.
|
|
304
|
+
* @param {string} source - The source of the authentication setting.
|
|
305
|
+
* @returns {object} - The authentication setting object.
|
|
306
|
+
*/
|
|
307
|
+
_getAuthSetting = async (type, source) => {
|
|
277
308
|
const { defaultsDeep } = this.app.lib.aneka
|
|
278
309
|
const { get } = this.app.lib._
|
|
279
310
|
|
|
@@ -282,10 +313,21 @@ async function factory (pkgName) {
|
|
|
282
313
|
return setting
|
|
283
314
|
}
|
|
284
315
|
|
|
285
|
-
|
|
316
|
+
/**
|
|
317
|
+
* Get authentication token based on type, request, and source
|
|
318
|
+
*
|
|
319
|
+
* @async
|
|
320
|
+
* @method
|
|
321
|
+
* @private
|
|
322
|
+
* @param {string} type - The type of authentication setting.
|
|
323
|
+
* @param {object} req - The request object.
|
|
324
|
+
* @param {string} source - The source of the authentication setting.
|
|
325
|
+
* @returns {string|boolean} - The token if found, otherwise false.
|
|
326
|
+
*/
|
|
327
|
+
_getAuthToken = async (type, req, source) => {
|
|
286
328
|
const { isEmpty } = this.app.lib._
|
|
287
329
|
|
|
288
|
-
const setting = await this.
|
|
330
|
+
const setting = await this._getAuthSetting(type, source)
|
|
289
331
|
let token = req.headers[setting.headerKey.toLowerCase()]
|
|
290
332
|
if (!['basic'].includes(type) && isEmpty(token)) token = req.query[setting.qsKey]
|
|
291
333
|
if (isEmpty(token)) {
|
|
@@ -296,6 +338,15 @@ async function factory (pkgName) {
|
|
|
296
338
|
return token
|
|
297
339
|
}
|
|
298
340
|
|
|
341
|
+
/**
|
|
342
|
+
* Build admin menu based on locals and request
|
|
343
|
+
*
|
|
344
|
+
* @async
|
|
345
|
+
* @method
|
|
346
|
+
* @param {object} locals - The locals object.
|
|
347
|
+
* @param {object} req - The request object.
|
|
348
|
+
* @returns {array} - The admin menu items.
|
|
349
|
+
*/
|
|
299
350
|
adminMenu = async (locals, req) => {
|
|
300
351
|
if (!this.app.waibuAdmin) return
|
|
301
352
|
const { getPluginPrefix } = this.app.waibu
|
|
@@ -306,28 +357,25 @@ async function factory (pkgName) {
|
|
|
306
357
|
title: 'manageSite',
|
|
307
358
|
children: [
|
|
308
359
|
{ title: 'siteProfile', href: `waibuAdmin:/${prefix}/site` },
|
|
309
|
-
{ title: '
|
|
360
|
+
{ title: 'manageSiteSetting', href: `waibuAdmin:/${prefix}/site-setting/:action`, params }
|
|
310
361
|
]
|
|
311
362
|
}, {
|
|
312
|
-
title: '
|
|
363
|
+
title: 'manageUserTeam',
|
|
313
364
|
children: [
|
|
314
|
-
{ title: '
|
|
315
|
-
{ title: '
|
|
365
|
+
{ title: 'manageUser', href: `waibuAdmin:/${prefix}/user/:action`, params },
|
|
366
|
+
{ title: 'manageUserSetting', href: `waibuAdmin:/${prefix}/user-setting/:action`, params },
|
|
367
|
+
{ title: 'manageTeam', href: `waibuAdmin:/${prefix}/team/:action`, params },
|
|
368
|
+
{ title: 'manageTeamUser', href: `waibuAdmin:/${prefix}/team-user/:action`, params },
|
|
369
|
+
{ title: 'manageTeamSetting', href: `waibuAdmin:/${prefix}/team-setting/:action`, params },
|
|
316
370
|
{ title: 'resetUserPassword', href: `waibuAdmin:/${prefix}/reset-user-password` }
|
|
317
371
|
]
|
|
318
372
|
}, {
|
|
319
|
-
title: '
|
|
320
|
-
children: [
|
|
321
|
-
{ title: 'teamProfile', href: `waibuAdmin:/${prefix}/team/:action`, params },
|
|
322
|
-
{ title: 'teamUser', href: `waibuAdmin:/${prefix}/team-user/:action`, params },
|
|
323
|
-
{ title: 'teamSetting', href: `waibuAdmin:/${prefix}/team-setting/:action`, params }
|
|
324
|
-
]
|
|
325
|
-
}, {
|
|
326
|
-
title: 'permission',
|
|
373
|
+
title: 'permissionGuard',
|
|
327
374
|
children: [
|
|
328
375
|
{ title: 'secureGuard', href: `waibuAdmin:/${prefix}/secure-guard/:action`, params },
|
|
329
376
|
{ title: 'anonymousGuard', href: `waibuAdmin:/${prefix}/anonymous-guard/:action`, params },
|
|
330
|
-
{ title: '
|
|
377
|
+
{ title: 'actionGuard', href: `waibuAdmin:/${prefix}/action-guard/:action`, params },
|
|
378
|
+
{ title: 'queryGuard', href: `waibuAdmin:/${prefix}/query-guard/:action`, params },
|
|
331
379
|
{ title: 'attribGuard', href: `waibuAdmin:/${prefix}/attrib-guard/:action`, params }
|
|
332
380
|
]
|
|
333
381
|
}, {
|
|
@@ -366,6 +414,14 @@ async function factory (pkgName) {
|
|
|
366
414
|
return items
|
|
367
415
|
}
|
|
368
416
|
|
|
417
|
+
/**
|
|
418
|
+
* Create JWT from user record
|
|
419
|
+
*
|
|
420
|
+
* @async
|
|
421
|
+
* @method
|
|
422
|
+
* @param {object} rec - The user record object.
|
|
423
|
+
* @returns {object} - The JWT token and its expiration date.
|
|
424
|
+
*/
|
|
369
425
|
createJwtFromUserRecord = async (rec) => {
|
|
370
426
|
const { importPkg } = this.app.bajo
|
|
371
427
|
const { dayjs } = this.app.lib
|
|
@@ -384,6 +440,17 @@ async function factory (pkgName) {
|
|
|
384
440
|
return { token, expiresAt }
|
|
385
441
|
}
|
|
386
442
|
|
|
443
|
+
/**
|
|
444
|
+
* Verify user session
|
|
445
|
+
*
|
|
446
|
+
* @async
|
|
447
|
+
* @method
|
|
448
|
+
* @param {object} req - The request object.
|
|
449
|
+
* @param {object} reply - The reply object.
|
|
450
|
+
* @param {string} source - The source of the authentication setting.
|
|
451
|
+
* @param {object} payload - The payload object.
|
|
452
|
+
* @returns {boolean} - True if the session is valid, otherwise false.
|
|
453
|
+
*/
|
|
387
454
|
verifySession = async (req, reply, source, payload) => {
|
|
388
455
|
const { routePath } = this.app.waibu
|
|
389
456
|
const { query, params } = req
|
|
@@ -398,11 +465,22 @@ async function factory (pkgName) {
|
|
|
398
465
|
throw this.error('_redirect', { path: redir })
|
|
399
466
|
}
|
|
400
467
|
|
|
468
|
+
/**
|
|
469
|
+
* Verify API key
|
|
470
|
+
*
|
|
471
|
+
* @async
|
|
472
|
+
* @method
|
|
473
|
+
* @param {object} req - The request object.
|
|
474
|
+
* @param {object} reply - The reply object.
|
|
475
|
+
* @param {string} source - The source of the authentication setting.
|
|
476
|
+
* @param {object} payload - The payload object.
|
|
477
|
+
* @returns {boolean} - True if the API key is valid, otherwise false.
|
|
478
|
+
*/
|
|
401
479
|
verifyApiKey = async (req, reply, source, payload) => {
|
|
402
480
|
const { merge, camelCase } = this.app.lib._
|
|
403
481
|
const checker = this.app.bajoExtra[camelCase(`is ${this.config.auth.common.apiKey.algo}`)]
|
|
404
482
|
|
|
405
|
-
let token = await this.
|
|
483
|
+
let token = await this._getAuthToken('apiKey', req, source)
|
|
406
484
|
if (!checker(token)) return false
|
|
407
485
|
token = await this.hash(token)
|
|
408
486
|
const user = await this.getUserByToken(token, req)
|
|
@@ -412,6 +490,17 @@ async function factory (pkgName) {
|
|
|
412
490
|
return true
|
|
413
491
|
}
|
|
414
492
|
|
|
493
|
+
/**
|
|
494
|
+
* Verify basic authentication
|
|
495
|
+
*
|
|
496
|
+
* @async
|
|
497
|
+
* @method
|
|
498
|
+
* @param {object} req - The request object.
|
|
499
|
+
* @param {object} reply - The reply object.
|
|
500
|
+
* @param {string} source - The source of the authentication setting.
|
|
501
|
+
* @param {object} payload - The payload object.
|
|
502
|
+
* @returns {boolean|string} - True if the basic authentication is valid, otherwise false or an error message.
|
|
503
|
+
*/
|
|
415
504
|
verifyBasic = async (req, reply, source, payload) => {
|
|
416
505
|
const { isEmpty, merge } = this.app.lib._
|
|
417
506
|
|
|
@@ -425,7 +514,7 @@ async function factory (pkgName) {
|
|
|
425
514
|
reply.code(401)
|
|
426
515
|
}
|
|
427
516
|
|
|
428
|
-
const setting = await this.
|
|
517
|
+
const setting = await this._getAuthSetting('basic', source)
|
|
429
518
|
let authInfo
|
|
430
519
|
const parts = (req.headers.authorization ?? '').split(' ')
|
|
431
520
|
if (parts[0] === setting.type) authInfo = parts[1]
|
|
@@ -449,14 +538,25 @@ async function factory (pkgName) {
|
|
|
449
538
|
return true
|
|
450
539
|
}
|
|
451
540
|
|
|
541
|
+
/**
|
|
542
|
+
* Verify JWT authentication
|
|
543
|
+
*
|
|
544
|
+
* @async
|
|
545
|
+
* @method
|
|
546
|
+
* @param {object} req - The request object.
|
|
547
|
+
* @param {object} reply - The reply object.
|
|
548
|
+
* @param {string} source - The source of the authentication setting.
|
|
549
|
+
* @param {object} payload - The payload object.
|
|
550
|
+
* @returns {boolean} - True if the JWT authentication is valid, otherwise false.
|
|
551
|
+
*/
|
|
452
552
|
verifyJwt = async (req, reply, source, payload) => {
|
|
453
553
|
const { importPkg } = this.app.bajo
|
|
454
554
|
const { isEmpty, merge } = this.app.lib._
|
|
455
555
|
|
|
456
556
|
const fastJwt = await importPkg('bajoExtra:fast-jwt')
|
|
457
557
|
const { createVerifier } = fastJwt
|
|
458
|
-
const setting = await this.
|
|
459
|
-
const token = await this.
|
|
558
|
+
const setting = await this._getAuthSetting('jwt', source)
|
|
559
|
+
const token = await this._getAuthToken('jwt', req, source)
|
|
460
560
|
if (isEmpty(token)) return false
|
|
461
561
|
const verifier = createVerifier({
|
|
462
562
|
key: setting.secret,
|
|
@@ -476,6 +576,14 @@ async function factory (pkgName) {
|
|
|
476
576
|
return true
|
|
477
577
|
}
|
|
478
578
|
|
|
579
|
+
/**
|
|
580
|
+
* Check route guard
|
|
581
|
+
*
|
|
582
|
+
* @method
|
|
583
|
+
* @param {Array} guards - The array of guard objects.
|
|
584
|
+
* @param {Array} paths - The array of paths to check.
|
|
585
|
+
* @returns {string|undefined} - The matched path or undefined if no match is found.
|
|
586
|
+
*/
|
|
479
587
|
checkRouteGuard = (guards, paths) => {
|
|
480
588
|
const { outmatch } = this.app.lib
|
|
481
589
|
const all = guards.map(item => item.path)
|
|
@@ -483,7 +591,18 @@ async function factory (pkgName) {
|
|
|
483
591
|
return paths.find(isMatch)
|
|
484
592
|
}
|
|
485
593
|
|
|
486
|
-
|
|
594
|
+
/**
|
|
595
|
+
* Sign out user and redirect to the specified URL
|
|
596
|
+
*
|
|
597
|
+
* @async
|
|
598
|
+
* @method
|
|
599
|
+
* @param {object} options - The options object.
|
|
600
|
+
* @param {object} options.req - The request object.
|
|
601
|
+
* @param {object} options.reply - The reply object.
|
|
602
|
+
* @param {string} [options.reason] - The reason for signing out.
|
|
603
|
+
*/
|
|
604
|
+
signout = async (options = {}) => {
|
|
605
|
+
const { req, reply, reason } = options
|
|
487
606
|
const { runHook } = this.app.bajo
|
|
488
607
|
const { getSessionId } = this.app.waibuMpa
|
|
489
608
|
const sid = await getSessionId(req.headers.cookie)
|
|
@@ -496,7 +615,18 @@ async function factory (pkgName) {
|
|
|
496
615
|
return reply.redirectTo(url, { query, params })
|
|
497
616
|
}
|
|
498
617
|
|
|
499
|
-
|
|
618
|
+
/**
|
|
619
|
+
* Sign in user and redirect to the specified URL
|
|
620
|
+
*
|
|
621
|
+
* @async
|
|
622
|
+
* @method
|
|
623
|
+
* @param {object} options - The options object.
|
|
624
|
+
* @param {object} options.req - The request object.
|
|
625
|
+
* @param {object} options.reply - The reply object.
|
|
626
|
+
* @param {object} options.user - The user object.
|
|
627
|
+
*/
|
|
628
|
+
signin = async (options = {}) => {
|
|
629
|
+
const { req, reply, user } = options
|
|
500
630
|
const { getSessionId } = this.app.waibuMpa
|
|
501
631
|
const { runHook } = this.app.bajo
|
|
502
632
|
const { isEmpty, omit } = this.app.lib._
|
|
@@ -513,6 +643,13 @@ async function factory (pkgName) {
|
|
|
513
643
|
return reply.redirectTo(url, { query, params })
|
|
514
644
|
}
|
|
515
645
|
|
|
646
|
+
/**
|
|
647
|
+
* Generate a random password based on the configuration settings
|
|
648
|
+
*
|
|
649
|
+
* @method
|
|
650
|
+
* @param {object} req - The request object.
|
|
651
|
+
* @returns {string} - The generated password.
|
|
652
|
+
*/
|
|
516
653
|
generatePassword = (req = {}) => {
|
|
517
654
|
const { get } = this.app.lib._
|
|
518
655
|
const { generateId } = this.app.lib.aneka
|
|
@@ -545,12 +682,27 @@ async function factory (pkgName) {
|
|
|
545
682
|
await push(jobQueue)
|
|
546
683
|
}
|
|
547
684
|
|
|
685
|
+
/**
|
|
686
|
+
* Get API key from user ID by hashing the user's salt
|
|
687
|
+
*
|
|
688
|
+
* @async
|
|
689
|
+
* @method
|
|
690
|
+
* @param {string|number} id - The user ID.
|
|
691
|
+
* @returns {Promise<string>} - A promise that resolves to the API key.
|
|
692
|
+
*/
|
|
548
693
|
getApiKeyFromUserId = async id => {
|
|
549
694
|
const options = { forceNoHidden: true, noHook: true, noCache: true, attachment: true, mimeType: true }
|
|
550
695
|
const resp = await getModel('SumbaUser').getRecord(id, options)
|
|
551
696
|
return await this.hash(resp.salt)
|
|
552
697
|
}
|
|
553
698
|
|
|
699
|
+
/**
|
|
700
|
+
* Get a list of countries with their values and names
|
|
701
|
+
*
|
|
702
|
+
* @async
|
|
703
|
+
* @method
|
|
704
|
+
* @returns {Promise<Array<{ value: string|number, text: string }>>} - A promise that resolves to an array of country values and names.
|
|
705
|
+
*/
|
|
554
706
|
getCountriesValues = async () => {
|
|
555
707
|
const { getModel } = this.app.dobo
|
|
556
708
|
const model = getModel('CdbCountry')
|
|
@@ -568,7 +720,6 @@ async function factory (pkgName) {
|
|
|
568
720
|
* @async
|
|
569
721
|
* @param {(string|Array)} tpl - Mail's template to use. If a string is given, the same template will be used for html & plaintext versions. Otherwise, the first template will be used for html mail, and the second one is for it's plaintext version
|
|
570
722
|
* @param {Object} [params={}] - {@link https://github.com/ardhi/masohi-mail|masohi-mail}'s params object.
|
|
571
|
-
* @returns
|
|
572
723
|
*/
|
|
573
724
|
sendMail = async (tpl, { payload = {}, conn, source, options = {} } = {}) => {
|
|
574
725
|
if (!this.app.masohiMail || !this.app.waibu) return
|
|
@@ -580,6 +731,7 @@ async function factory (pkgName) {
|
|
|
580
731
|
const buildLocals = await importModule('waibu:/lib/build-locals.js')
|
|
581
732
|
|
|
582
733
|
if (isString(tpl)) tpl = [tpl]
|
|
734
|
+
options.partial = false
|
|
583
735
|
const locals = await buildLocals.call(this, { params: payload.data, opts: options })
|
|
584
736
|
payload.from = payload.from ?? get(options, 'req.site.email', payload.from)
|
|
585
737
|
const opts = {
|
|
@@ -591,6 +743,14 @@ async function factory (pkgName) {
|
|
|
591
743
|
await this.app.masohiMail.send({ payload, source: source ?? this.ns, conn })
|
|
592
744
|
}
|
|
593
745
|
|
|
746
|
+
/**
|
|
747
|
+
* Reset token by generating a new salt and hashing it twice to create a new token.
|
|
748
|
+
*
|
|
749
|
+
* @async
|
|
750
|
+
* @method
|
|
751
|
+
* @param {string} [text] - Optional text to use as the salt. If not provided, a new salt will be generated.
|
|
752
|
+
* @returns {Promise<{ salt: string, token: string }>} - A promise that resolves to an object containing the salt and token.
|
|
753
|
+
*/
|
|
594
754
|
resetToken = async (text) => {
|
|
595
755
|
const { generateId } = this.app.lib.aneka
|
|
596
756
|
const salt = text ?? generateId()
|
|
@@ -598,6 +758,14 @@ async function factory (pkgName) {
|
|
|
598
758
|
return { salt, token }
|
|
599
759
|
}
|
|
600
760
|
|
|
761
|
+
/**
|
|
762
|
+
* Generate a password validation rule based on the configuration settings.
|
|
763
|
+
*
|
|
764
|
+
* @async
|
|
765
|
+
* @method
|
|
766
|
+
* @param {object} req - The request object.
|
|
767
|
+
* @returns {object} - The Joi password validation rule.
|
|
768
|
+
*/
|
|
601
769
|
passwordRule = async (req = {}) => {
|
|
602
770
|
const { get } = this.app.lib._
|
|
603
771
|
const { importPkg } = this.app.bajo
|
|
@@ -618,11 +786,28 @@ async function factory (pkgName) {
|
|
|
618
786
|
return password
|
|
619
787
|
}
|
|
620
788
|
|
|
789
|
+
/**
|
|
790
|
+
* Hash the given item using the specified algorithm from the configuration.
|
|
791
|
+
*
|
|
792
|
+
* @async
|
|
793
|
+
* @method
|
|
794
|
+
* @param {*} item - The item to be hashed.
|
|
795
|
+
* @returns {Promise<string>} - A promise that resolves to the hashed value.
|
|
796
|
+
*/
|
|
621
797
|
hash = async (item) => {
|
|
622
798
|
const { hash } = this.app.bajoExtra
|
|
623
799
|
return await hash(item, this.config.auth.common.apiKey.algo)
|
|
624
800
|
}
|
|
625
801
|
|
|
802
|
+
/**
|
|
803
|
+
* Fetch guards of the specified type from the database.
|
|
804
|
+
*
|
|
805
|
+
* @async
|
|
806
|
+
* @method
|
|
807
|
+
* @private
|
|
808
|
+
* @param {string} type - The type of guards to fetch. Available types are 'Action', 'Attrib', 'Query', 'Secure', and 'Anonymous'.
|
|
809
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of guards.
|
|
810
|
+
*/
|
|
626
811
|
_fetchGuards = async (type) => {
|
|
627
812
|
const { getModel } = this.app.dobo
|
|
628
813
|
const options = { noMagic: true, noCache: true, noDriverHook: true, dataOnly: true }
|
|
@@ -634,6 +819,14 @@ async function factory (pkgName) {
|
|
|
634
819
|
})
|
|
635
820
|
}
|
|
636
821
|
|
|
822
|
+
/**
|
|
823
|
+
* Process and order the guards based on their path and weight.
|
|
824
|
+
*
|
|
825
|
+
* @method
|
|
826
|
+
* @private
|
|
827
|
+
* @param {Array} inputs - The array of guard inputs.
|
|
828
|
+
* @returns {Array} - The processed and ordered array of guards.
|
|
829
|
+
*/
|
|
637
830
|
_getGuards = (inputs = []) => {
|
|
638
831
|
const { routePath } = this.app.waibu
|
|
639
832
|
const { orderBy } = this.app.lib._
|
|
@@ -656,6 +849,14 @@ async function factory (pkgName) {
|
|
|
656
849
|
return [...normal, ...inverse]
|
|
657
850
|
}
|
|
658
851
|
|
|
852
|
+
/**
|
|
853
|
+
* Get anonymous guards, optionally reloading them from the database.
|
|
854
|
+
*
|
|
855
|
+
* @async
|
|
856
|
+
* @method
|
|
857
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
858
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of anonymous guards.
|
|
859
|
+
*/
|
|
659
860
|
getAnonymousGuards = async (reread) => {
|
|
660
861
|
if (!reread) return this.anonymousGuards
|
|
661
862
|
const guards = await this._fetchGuards('Anonymous')
|
|
@@ -663,6 +864,14 @@ async function factory (pkgName) {
|
|
|
663
864
|
return this.anonymousGuards
|
|
664
865
|
}
|
|
665
866
|
|
|
867
|
+
/**
|
|
868
|
+
* Get secure guards, optionally reloading them from the database.
|
|
869
|
+
*
|
|
870
|
+
* @async
|
|
871
|
+
* @method
|
|
872
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
873
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of secure guards.
|
|
874
|
+
*/
|
|
666
875
|
getSecureGuards = async (reread) => {
|
|
667
876
|
if (!reread) return this.secureGuards
|
|
668
877
|
const guards = await this._fetchGuards('Secure')
|
|
@@ -670,13 +879,44 @@ async function factory (pkgName) {
|
|
|
670
879
|
return this.secureGuards
|
|
671
880
|
}
|
|
672
881
|
|
|
673
|
-
|
|
674
|
-
|
|
882
|
+
/**
|
|
883
|
+
* Get query guards, optionally reloading them from the database.
|
|
884
|
+
*
|
|
885
|
+
* @async
|
|
886
|
+
* @method
|
|
887
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
888
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of query guards.
|
|
889
|
+
*/
|
|
890
|
+
getQueryGuards = async (reread) => {
|
|
891
|
+
if (!reread) return this.queryGuards
|
|
675
892
|
|
|
676
|
-
this.
|
|
677
|
-
return this.
|
|
893
|
+
this.queryGuards = await this._fetchGuards('Query')
|
|
894
|
+
return this.queryGuards
|
|
678
895
|
}
|
|
679
896
|
|
|
897
|
+
/**
|
|
898
|
+
* Get action guards, optionally reloading them from the database.
|
|
899
|
+
*
|
|
900
|
+
* @async
|
|
901
|
+
* @method
|
|
902
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
903
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of action guards.
|
|
904
|
+
*/
|
|
905
|
+
getActionGuards = async (reread) => {
|
|
906
|
+
if (!reread) return this.actionGuards
|
|
907
|
+
|
|
908
|
+
this.actionGuards = await this._fetchGuards('Action')
|
|
909
|
+
return this.actionGuards
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/**
|
|
913
|
+
* Get attribute guards, optionally reloading them from the database.
|
|
914
|
+
*
|
|
915
|
+
* @async
|
|
916
|
+
* @method
|
|
917
|
+
* @param {boolean} [reread] - Whether to reload the guards from the database.
|
|
918
|
+
* @returns {Promise<Array>} - A promise that resolves to an array of attribute guards.
|
|
919
|
+
*/
|
|
680
920
|
getAttribGuards = async (reread) => {
|
|
681
921
|
if (!reread) return this.attribGuards
|
|
682
922
|
|
|
@@ -684,11 +924,25 @@ async function factory (pkgName) {
|
|
|
684
924
|
return this.attribGuards
|
|
685
925
|
}
|
|
686
926
|
|
|
927
|
+
/**
|
|
928
|
+
* Get all loaded model names, optionally returning them as value-text pairs.
|
|
929
|
+
*
|
|
930
|
+
* @method
|
|
931
|
+
* @param {boolean} [asValue] - Whether to return the model names as value-text pairs.
|
|
932
|
+
* @returns {Array} - An array of model names or value-text pairs.
|
|
933
|
+
*/
|
|
687
934
|
getModelNames = (asValue) => {
|
|
688
935
|
const values = this.app.dobo.models.map(item => item.name).sort()
|
|
689
936
|
return asValue ? values.map(item => ({ value: item, text: item })) : values
|
|
690
937
|
}
|
|
691
938
|
|
|
939
|
+
/**
|
|
940
|
+
* Gather all paths to check for a request.
|
|
941
|
+
*
|
|
942
|
+
* @method
|
|
943
|
+
* @param {Object} req - The request object.
|
|
944
|
+
* @returns {Array} - An array of paths to check.
|
|
945
|
+
*/
|
|
692
946
|
pathsToCheck = (req) => {
|
|
693
947
|
const { isSet } = this.app.lib.aneka
|
|
694
948
|
const { uniq, without } = this.app.lib._
|
|
@@ -696,6 +950,15 @@ async function factory (pkgName) {
|
|
|
696
950
|
return uniq(without(items, undefined, null))
|
|
697
951
|
}
|
|
698
952
|
|
|
953
|
+
/**
|
|
954
|
+
* Check and set the iconset for a request.
|
|
955
|
+
*
|
|
956
|
+
* @async
|
|
957
|
+
* @method
|
|
958
|
+
* @param {Object} req - The request object.
|
|
959
|
+
* @param {Object} reply - The reply object.
|
|
960
|
+
* @returns {Promise<void>} - A promise that resolves when the iconset is checked and set.
|
|
961
|
+
*/
|
|
699
962
|
checkIconset = async (req, reply) => {
|
|
700
963
|
const { get, isString } = this.app.lib._
|
|
701
964
|
const mpa = this.app.waibuMpa
|
|
@@ -708,6 +971,15 @@ async function factory (pkgName) {
|
|
|
708
971
|
req.iconset = req.iconset ?? 'default'
|
|
709
972
|
}
|
|
710
973
|
|
|
974
|
+
/**
|
|
975
|
+
* Check and set the theme for a request.
|
|
976
|
+
*
|
|
977
|
+
* @async
|
|
978
|
+
* @method
|
|
979
|
+
* @param {Object} req - The request object.
|
|
980
|
+
* @param {Object} reply - The reply object.
|
|
981
|
+
* @returns {Promise<void>} - A promise that resolves when the theme is checked and set.
|
|
982
|
+
*/
|
|
711
983
|
checkTheme = async (req, reply) => {
|
|
712
984
|
const { get, isString } = this.app.lib._
|
|
713
985
|
const mpa = this.app.waibuMpa
|
|
@@ -720,6 +992,15 @@ async function factory (pkgName) {
|
|
|
720
992
|
req.theme = req.theme ?? 'default'
|
|
721
993
|
}
|
|
722
994
|
|
|
995
|
+
/**
|
|
996
|
+
* Check and set the team for a request.
|
|
997
|
+
*
|
|
998
|
+
* @async
|
|
999
|
+
* @method
|
|
1000
|
+
* @param {Object} req - The request object.
|
|
1001
|
+
* @param {Object} reply - The reply object.
|
|
1002
|
+
* @returns {Promise<void>} - A promise that resolves when the team is checked and set.
|
|
1003
|
+
*/
|
|
723
1004
|
checkTeam = async (req, reply) => {
|
|
724
1005
|
const { includes } = this.app.lib.aneka
|
|
725
1006
|
const { outmatch } = this.app.lib
|
|
@@ -742,6 +1023,16 @@ async function factory (pkgName) {
|
|
|
742
1023
|
// passed
|
|
743
1024
|
}
|
|
744
1025
|
|
|
1026
|
+
/**
|
|
1027
|
+
* Check and set the user for a request.
|
|
1028
|
+
*
|
|
1029
|
+
* @async
|
|
1030
|
+
* @method
|
|
1031
|
+
* @param {Object} req - The request object.
|
|
1032
|
+
* @param {Object} reply - The reply object.
|
|
1033
|
+
* @param {Object} source - The source object.
|
|
1034
|
+
* @returns {Promise<boolean|void>} - A promise that resolves to a boolean indicating the result of the check or void.
|
|
1035
|
+
*/
|
|
745
1036
|
checkUser = async (req, reply, source) => {
|
|
746
1037
|
const { merge, isEmpty, camelCase, get } = this.app.lib._
|
|
747
1038
|
const { routePath } = this.app.waibu
|
|
@@ -803,6 +1094,15 @@ async function factory (pkgName) {
|
|
|
803
1094
|
return secure
|
|
804
1095
|
}
|
|
805
1096
|
|
|
1097
|
+
/**
|
|
1098
|
+
* Check and set the Cross-site settings for a request.
|
|
1099
|
+
*
|
|
1100
|
+
* @async
|
|
1101
|
+
* @method
|
|
1102
|
+
* @param {Object} req - The request object.
|
|
1103
|
+
* @param {Object} reply - The reply object.
|
|
1104
|
+
* @returns {Promise<void>} - A promise that resolves when the XSite is checked and set.
|
|
1105
|
+
*/
|
|
806
1106
|
checkXSite = async (req, reply) => {
|
|
807
1107
|
const { get } = this.app.lib._
|
|
808
1108
|
if (!this.config.multiSite.enabled) return
|
|
@@ -811,6 +1111,14 @@ async function factory (pkgName) {
|
|
|
811
1111
|
if (!get(req, 'user.isXSiteAdmin')) throw this.error('accessDenied', { statusCode: 403 })
|
|
812
1112
|
}
|
|
813
1113
|
|
|
1114
|
+
/**
|
|
1115
|
+
* Check the route for a request.
|
|
1116
|
+
*
|
|
1117
|
+
* @async
|
|
1118
|
+
* @method
|
|
1119
|
+
* @param {Object} req - The request object.
|
|
1120
|
+
* @returns {Promise<void>} - A promise that resolves when the route is checked.
|
|
1121
|
+
*/
|
|
814
1122
|
checkRoute = async (req) => {
|
|
815
1123
|
const { routePath } = this.app.waibu
|
|
816
1124
|
const { outmatch } = this.app.lib
|
|
@@ -821,6 +1129,14 @@ async function factory (pkgName) {
|
|
|
821
1129
|
if (paths.find(isMatch)) throw this.error('_notFound')
|
|
822
1130
|
}
|
|
823
1131
|
|
|
1132
|
+
/**
|
|
1133
|
+
* Parse namespace settings for a request.
|
|
1134
|
+
*
|
|
1135
|
+
* @method
|
|
1136
|
+
* @param {string} ns - The namespace.
|
|
1137
|
+
* @param {Object} setting - The setting object.
|
|
1138
|
+
* @param {Array} items - The items to parse.
|
|
1139
|
+
*/
|
|
824
1140
|
parseNsSettings = (ns, setting, items) => {
|
|
825
1141
|
const { trim, set, isPlainObject, isArray, isEmpty, find } = this.app.lib._
|
|
826
1142
|
const { parseObject, dayjs } = this.app.lib
|
|
@@ -848,13 +1164,713 @@ async function factory (pkgName) {
|
|
|
848
1164
|
}
|
|
849
1165
|
}
|
|
850
1166
|
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1167
|
+
/**
|
|
1168
|
+
* Get all fixtures for the specified alias, replacing any occurrences of '{alias}' in the fixture data with the provided alias.
|
|
1169
|
+
*
|
|
1170
|
+
* @async
|
|
1171
|
+
* @method
|
|
1172
|
+
* @param {string} [alias] - The alias for the fixtures.
|
|
1173
|
+
* @returns {Promise<object>} - A promise that resolves to the fixtures data.
|
|
1174
|
+
*/
|
|
1175
|
+
getAllFixtures = async (alias) => {
|
|
1176
|
+
const { readConfig } = this.app.bajo
|
|
1177
|
+
const { isEmpty, omit, kebabCase, isString } = this.app.lib._
|
|
1178
|
+
const { getModel } = this.app.dobo
|
|
1179
|
+
const { fastGlob } = this.app.lib
|
|
1180
|
+
const data = {}
|
|
1181
|
+
|
|
1182
|
+
function replaceAlias (alias, items) {
|
|
1183
|
+
for (const item of items) {
|
|
1184
|
+
for (const key in item) {
|
|
1185
|
+
const val = item[key]
|
|
1186
|
+
if (isString(val)) item[key] = val.replaceAll('{alias}', alias)
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
const formats = this.app.configHandlers.map(item => item.ext.slice(1))
|
|
1192
|
+
const overrideBase = `${this.app.getPluginDataDir('sumba')}/create-new-site-fixtures/${alias}`
|
|
1193
|
+
const models = this.app.dobo.models.filter(m => {
|
|
1194
|
+
const prop = m.properties.find(p => p.name === 'siteId')
|
|
1195
|
+
return !!prop
|
|
1196
|
+
}).map(m => m.name)
|
|
1197
|
+
models.unshift('SumbaSite')
|
|
1198
|
+
const files = (await fastGlob(`${overrideBase}/*.{${formats.join(',')}}`)).map(file => {
|
|
1199
|
+
const ext = path.extname(file)
|
|
1200
|
+
return file.slice(0, file.length - ext.length)
|
|
1201
|
+
})
|
|
1202
|
+
for (const m of models) {
|
|
1203
|
+
const model = getModel(m)
|
|
1204
|
+
const file = `${overrideBase}/${kebabCase(m)}`
|
|
1205
|
+
let fixtures = (await model.loadFixtures({ collectItems: true, noLookup: true })) ?? []
|
|
1206
|
+
if (files.includes(file)) {
|
|
1207
|
+
const items = await readConfig(file, { defValue: [] })
|
|
1208
|
+
if (!isEmpty(items)) fixtures = items
|
|
1209
|
+
}
|
|
1210
|
+
if (!Array.isArray(fixtures)) fixtures = [fixtures]
|
|
1211
|
+
if (fixtures.length === 0) continue
|
|
1212
|
+
replaceAlias(alias, fixtures)
|
|
1213
|
+
if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
|
|
1214
|
+
const omitted = ['_attachments', 'siteId']
|
|
1215
|
+
for (const item of ['createdAt', 'updatedAt', 'immutable']) {
|
|
1216
|
+
const props = model.properties.filter(prop => prop.feature === ('dobo:' + item)).map(prop => prop.name)
|
|
1217
|
+
if (props.length > 0) omitted.push(...props)
|
|
1218
|
+
}
|
|
1219
|
+
for (const idx in fixtures) {
|
|
1220
|
+
fixtures[idx] = omit(fixtures[idx], omitted)
|
|
1221
|
+
}
|
|
1222
|
+
data[m] = m === 'SumbaSite' ? fixtures[0] : fixtures
|
|
1223
|
+
}
|
|
1224
|
+
return data
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* Create references for the specified site using the provided data, options, and verbosity settings.
|
|
1229
|
+
*
|
|
1230
|
+
* @async
|
|
1231
|
+
* @method
|
|
1232
|
+
* @param {object} site - The site object for which to create references.
|
|
1233
|
+
* @param {object} data - The data object containing fixtures for the site.
|
|
1234
|
+
* @param {object} options - Options to pass to the createRecord method.
|
|
1235
|
+
* @param {boolean} verbose - Whether to log verbose output.
|
|
1236
|
+
*/
|
|
1237
|
+
createRefs = async (site, data, options, verbose) => {
|
|
1238
|
+
const { isString } = this.app.lib._
|
|
1239
|
+
const { getModel } = this.app.dobo
|
|
1240
|
+
for (const m in data) {
|
|
1241
|
+
if (m === 'SumbaSite') continue
|
|
1242
|
+
const mdl = getModel(m)
|
|
1243
|
+
const fixtures = data[m]
|
|
1244
|
+
for (const f of fixtures) {
|
|
1245
|
+
f.siteId = site.id + ''
|
|
1246
|
+
const lv = { siteId: f.siteId }
|
|
1247
|
+
for (const key in f) {
|
|
1248
|
+
const val = f[key]
|
|
1249
|
+
if (isString(val) && val.slice(0, 2) === '?:') f[key] = await mdl._simpleLookup(val.slice(2), lv, options)
|
|
1250
|
+
}
|
|
1251
|
+
await mdl.createRecord(f, { ...options, noFlash: true })
|
|
1252
|
+
}
|
|
1253
|
+
if (verbose) this.print.succeed('writingModel%s%s', mdl.name, fixtures.length)
|
|
1254
|
+
}
|
|
1255
|
+
if (verbose) this.print.succeed('populateRouteGuard')
|
|
1256
|
+
await this.populateRouteGuards([site])
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/**
|
|
1260
|
+
* Create a new site with the specified alias and optional hostname, using fixtures for initial data.
|
|
1261
|
+
*
|
|
1262
|
+
* @async
|
|
1263
|
+
* @method
|
|
1264
|
+
* @param {string} alias - The alias for the new site.
|
|
1265
|
+
* @param {string} [hostname] - The hostname for the new site.
|
|
1266
|
+
* @param {boolean} [verbose=false] - Whether to log verbose output.
|
|
1267
|
+
*/
|
|
1268
|
+
createNewSite = async (alias, hostname, verbose) => {
|
|
1269
|
+
const { isEmpty } = this.app.lib._
|
|
1270
|
+
const { getModel } = this.app.dobo
|
|
1271
|
+
|
|
1272
|
+
if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
|
|
1273
|
+
let spin
|
|
1274
|
+
if (verbose) spin = this.print.spinner().start('processing...')
|
|
1275
|
+
const query = { $or: [{ alias }] }
|
|
1276
|
+
if (!isEmpty(hostname)) query.$or.push({ hostname })
|
|
1277
|
+
const model = getModel('SumbaSite')
|
|
1278
|
+
const site = await model.findOneRecord({ query })
|
|
1279
|
+
if (!isEmpty(site)) {
|
|
1280
|
+
if (verbose) spin.stop()
|
|
1281
|
+
throw this.error('aliasOrHostnameExists%s%s', alias, hostname ?? '')
|
|
1282
|
+
}
|
|
1283
|
+
// lets go
|
|
1284
|
+
const fixtures = await this.getAllFixtures(alias)
|
|
1285
|
+
if (verbose) spin.stop()
|
|
1286
|
+
fixtures.SumbaSite.alias = alias
|
|
1287
|
+
if (!isEmpty(hostname)) fixtures.SumbaSite.hostname = hostname
|
|
1288
|
+
await model.transaction(async (trx) => {
|
|
1289
|
+
const newSite = await model.createRecord(fixtures.SumbaSite, { trx, noHook: true })
|
|
1290
|
+
if (verbose) this.print.succeed('writingModel%s%s', model.name, 1)
|
|
1291
|
+
const options = { trx }
|
|
1292
|
+
await this.createRefs(newSite, fixtures, options, verbose)
|
|
1293
|
+
})
|
|
1294
|
+
if (verbose) this.print.info('done')
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
/**
|
|
1298
|
+
* Remove references for the specified site using the provided options and verbosity settings.
|
|
1299
|
+
*
|
|
1300
|
+
* @async
|
|
1301
|
+
* @method
|
|
1302
|
+
* @param {object} site - The site object for which to remove references.
|
|
1303
|
+
* @param {object} options - Options to pass to the removeRecord method.
|
|
1304
|
+
* @param {boolean} verbose - Whether to log verbose output.
|
|
1305
|
+
*/
|
|
1306
|
+
removeRefs = async (site, options, verbose) => {
|
|
1307
|
+
const { orderBy } = this.app.lib._
|
|
1308
|
+
const { getModel } = this.app.dobo
|
|
1309
|
+
const models = orderBy(this.app.dobo.models, ['buildLevel'], ['desc']).filter(m => {
|
|
1310
|
+
const prop = m.properties.find(p => p.name === 'siteId')
|
|
1311
|
+
return !!prop
|
|
1312
|
+
}).map(m => m.name)
|
|
1313
|
+
for (const m of models) {
|
|
1314
|
+
const mdl = getModel(m)
|
|
1315
|
+
const rows = await mdl.findAllRecord({ query: { siteId: site.id + '' } }, { ...options, dataOnly: true })
|
|
1316
|
+
const ids = rows.map(item => item.id)
|
|
1317
|
+
// TODO: backup
|
|
1318
|
+
if (ids.length === 0) continue
|
|
1319
|
+
for (const id of ids) {
|
|
1320
|
+
await mdl.removeRecord(id, { noReturn: true, ...options, noFlash: true })
|
|
1321
|
+
}
|
|
1322
|
+
if (verbose) this.print.succeed('removedFrom%s%s', mdl.name, ids.length)
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
/**
|
|
1327
|
+
* Remove a site with the specified alias, along with its references, using the provided verbosity settings.
|
|
1328
|
+
*
|
|
1329
|
+
* @async
|
|
1330
|
+
* @method
|
|
1331
|
+
* @param {string} alias - The alias of the site to remove.
|
|
1332
|
+
* @param {boolean} [verbose=false] - Whether to log verbose output.
|
|
1333
|
+
*/
|
|
1334
|
+
removeSite = async (alias, verbose) => {
|
|
1335
|
+
const { isEmpty } = this.app.lib._
|
|
1336
|
+
const { getModel } = this.app.dobo
|
|
1337
|
+
|
|
1338
|
+
if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
|
|
1339
|
+
const model = getModel('SumbaSite')
|
|
1340
|
+
const query = { alias }
|
|
1341
|
+
const site = await model.findOneRecord({ query })
|
|
1342
|
+
if (isEmpty(site)) throw this.error('aliasNotFound%s', alias)
|
|
1343
|
+
await model.transaction(async (trx) => {
|
|
1344
|
+
const options = { trx, noHook: true }
|
|
1345
|
+
await this.removeRefs(site, options, verbose)
|
|
1346
|
+
await model.removeRecord(site.id, { noReturn: true, trx, noHook: true })
|
|
1347
|
+
if (verbose) this.print.succeed('removedFrom%s%s', model.name, 1)
|
|
1348
|
+
})
|
|
1349
|
+
if (verbose) this.print.info('done')
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
/**
|
|
1353
|
+
* Get site information based on the provided input, which can be either a hostname or an ID. If multi-site is enabled, it will fetch the site based on the hostname or ID; otherwise, it will return the default site.
|
|
1354
|
+
*
|
|
1355
|
+
* @async
|
|
1356
|
+
* @method
|
|
1357
|
+
* @param {string|number} input - The input value, which can be either a hostname or an ID.
|
|
1358
|
+
* @param {boolean} [byId=false] - Whether to fetch the site by ID.
|
|
1359
|
+
* @returns {object} The site information.
|
|
1360
|
+
*/
|
|
1361
|
+
getSite = async (input, byId = false) => {
|
|
1362
|
+
const { omit } = this.app.lib._
|
|
1363
|
+
const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
|
|
1364
|
+
const omitted = ['status']
|
|
1365
|
+
|
|
1366
|
+
let site = {}
|
|
1367
|
+
const mergeSetting = async (site) => {
|
|
1368
|
+
const { defaultsDeep, isSet } = this.app.lib.aneka
|
|
1369
|
+
const { get, filter } = this.app.lib._
|
|
1370
|
+
const defSetting = {}
|
|
1371
|
+
const nsSetting = {}
|
|
1372
|
+
const names = this.app.getAllNs()
|
|
1373
|
+
const query = {
|
|
1374
|
+
ns: { $in: names },
|
|
1375
|
+
siteId: site.id + ''
|
|
1376
|
+
}
|
|
1377
|
+
const all = await this.app.dobo.getModel('SumbaSiteSetting').findAllRecord({ query })
|
|
1378
|
+
for (const ns of names) {
|
|
1379
|
+
const item = get(this, `app.${ns}.config.siteSetting`)
|
|
1380
|
+
if (isSet(item)) defSetting[ns] = item
|
|
1381
|
+
const items = filter(all, { ns })
|
|
1382
|
+
this.parseNsSettings(ns, nsSetting, items)
|
|
1383
|
+
}
|
|
1384
|
+
site.setting = defaultsDeep({}, nsSetting, defSetting)
|
|
1385
|
+
// additional fields
|
|
1386
|
+
const country = await this.app.dobo.getModel('CdbCountry').getRecord(site.country, { noMagic: true })
|
|
1387
|
+
site.countryName = (country ?? {}).name ?? site.country
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
if (!this.config.multiSite.enabled) {
|
|
1391
|
+
const filter = { query: { alias: 'default' } }
|
|
1392
|
+
const key = 'dobo|SumbaSite|getSite|default'
|
|
1393
|
+
if (getCache) {
|
|
1394
|
+
site = await getCache({ key })
|
|
1395
|
+
if (site) return site
|
|
1396
|
+
}
|
|
1397
|
+
const resp = await this.app.dobo.getModel('SumbaSite').findOneRecord(filter, { noHook: true })
|
|
1398
|
+
site = omit(resp, omitted)
|
|
1399
|
+
await mergeSetting(site)
|
|
1400
|
+
if (setCache) {
|
|
1401
|
+
await setCache({ key, value: site, ttl: this.config.cacheTtl.getSiteDur })
|
|
1402
|
+
}
|
|
1403
|
+
return site
|
|
1404
|
+
}
|
|
1405
|
+
let query
|
|
1406
|
+
if (byId) query = { id: input }
|
|
1407
|
+
else query = { hostname: input }
|
|
1408
|
+
const key = `dobo|SumbaSite|getSite|multiSite|${input}`
|
|
1409
|
+
if (getCache) {
|
|
1410
|
+
site = await getCache({ key })
|
|
1411
|
+
if (site) return JSON.parse(site)
|
|
1412
|
+
}
|
|
1413
|
+
let row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
|
|
1414
|
+
if (!row) {
|
|
1415
|
+
if (this.config.multiSite.catchAll) {
|
|
1416
|
+
query = { alias: this.config.multiSite.catchAll === true ? 'default' : this.config.multiSite.catchAll }
|
|
1417
|
+
row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
|
|
1418
|
+
}
|
|
1419
|
+
if (!row) throw this.error('unknownSite')
|
|
1420
|
+
}
|
|
1421
|
+
if (row.status !== 'ACTIVE') throw this.error('siteInactiveInfo')
|
|
1422
|
+
site = omit(row, omitted)
|
|
1423
|
+
await mergeSetting(site)
|
|
1424
|
+
if (setCache) {
|
|
1425
|
+
await setCache({ key, value: JSON.stringify(site), ttl: this.config.cacheTtl.getSiteDur })
|
|
1426
|
+
}
|
|
1427
|
+
return site
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
/**
|
|
1431
|
+
* Merge team information into the user object.
|
|
1432
|
+
*
|
|
1433
|
+
* @async
|
|
1434
|
+
* @method
|
|
1435
|
+
* @param {object} user - The user object to merge team information into.
|
|
1436
|
+
* @param {object} req - The request object.
|
|
1437
|
+
*/
|
|
1438
|
+
mergeTeam = async (user, req) => {
|
|
1439
|
+
const { map, pick } = this.app.lib._
|
|
1440
|
+
const { getModel } = this.app.dobo
|
|
1441
|
+
user.teams = []
|
|
1442
|
+
const query = { userId: user.id + '', siteId: user.siteId, status: 'ACTIVE' }
|
|
1443
|
+
let mdl = getModel('SumbaTeamUser')
|
|
1444
|
+
const userTeam = await mdl.findAllRecord({ query })
|
|
1445
|
+
if (userTeam.length === 0) return
|
|
1446
|
+
delete query.userId
|
|
1447
|
+
const idProp = mdl.getProperty('id')
|
|
1448
|
+
const $in = userTeam.map(item => ['integer', 'smallint'].includes(idProp.type) ? parseInt(item.teamId) : item.teamId)
|
|
1449
|
+
query.id = { $in }
|
|
1450
|
+
mdl = getModel('SumbaTeam')
|
|
1451
|
+
const teams = await mdl.findAllRecord({ query })
|
|
1452
|
+
if (teams.length > 0) {
|
|
1453
|
+
delete query.id
|
|
1454
|
+
delete query.status
|
|
1455
|
+
query.teamId = { $in: teams.map(t => t.id + '') }
|
|
1456
|
+
mdl = getModel('SumbaTeamSetting')
|
|
1457
|
+
const items = await mdl.findAllRecord({ query })
|
|
1458
|
+
for (const team of teams) {
|
|
1459
|
+
const names = map(items, 'ns')
|
|
1460
|
+
const item = pick(team, ['id', 'alias'])
|
|
1461
|
+
item.setting = {}
|
|
1462
|
+
for (const ns of names) {
|
|
1463
|
+
this.parseNsSettings(ns, item.setting, items.filter(s => s.teamId === (team.id + '')))
|
|
1464
|
+
}
|
|
1465
|
+
user.teams.push(item)
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
user.isXSiteAdmin = this.config.xSiteAdmins.includes(`${req.site.alias}:${user.username}`)
|
|
1469
|
+
user.isAdmin = user.teams.some(t => t.alias === 'administrator')
|
|
1470
|
+
for (const field of this.unsafeUserFields) {
|
|
1471
|
+
delete user[field]
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/**
|
|
1476
|
+
* Get a user by their ID.
|
|
1477
|
+
*
|
|
1478
|
+
* @async
|
|
1479
|
+
* @method
|
|
1480
|
+
* @param {string|number} id - The ID of the user to retrieve.
|
|
1481
|
+
* @param {object} req - The request object.
|
|
1482
|
+
* @returns {object|null} The user object if found, otherwise null.
|
|
1483
|
+
*/
|
|
1484
|
+
getUserById = async (id, req) => {
|
|
1485
|
+
const { getModel } = this.app.dobo
|
|
1486
|
+
const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
|
|
1487
|
+
const key = `dobo|SumbaUser|getUserById|${id}`
|
|
1488
|
+
let user
|
|
1489
|
+
if (getCache) {
|
|
1490
|
+
user = await getCache({ key })
|
|
1491
|
+
if (user) return JSON.parse(user)
|
|
1492
|
+
}
|
|
1493
|
+
user = await getModel('SumbaUser').getRecord(id, { noHook: true, noDriverHook: true, throwNotFound: false, req })
|
|
1494
|
+
if (!user) return
|
|
1495
|
+
await this.mergeTeam(user, req)
|
|
1496
|
+
if (setCache) {
|
|
1497
|
+
await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByIdDur })
|
|
1498
|
+
}
|
|
1499
|
+
return user
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
/**
|
|
1503
|
+
* Get a user by their token.
|
|
1504
|
+
*
|
|
1505
|
+
* @async
|
|
1506
|
+
* @method
|
|
1507
|
+
* @param {string} token - The token of the user to retrieve.
|
|
1508
|
+
* @param {object} req - The request object.
|
|
1509
|
+
* @returns {object|null} The user object if found, otherwise null.
|
|
1510
|
+
*/
|
|
1511
|
+
getUserByToken = async (token, req) => {
|
|
1512
|
+
const { getModel } = this.app.dobo
|
|
1513
|
+
const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
|
|
1514
|
+
const key = `dobo|SumbaUser|getUserByToken|${token}`
|
|
1515
|
+
let user
|
|
1516
|
+
if (getCache) {
|
|
1517
|
+
user = await getCache({ key })
|
|
1518
|
+
if (user) return JSON.parse(user)
|
|
1519
|
+
}
|
|
1520
|
+
user = await getModel('SumbaUser').findOneRecord({ query: { token } }, { noHook: true, noDriverHook: true, throwNotFound: false, req })
|
|
1521
|
+
if (!user) return
|
|
1522
|
+
await this.mergeTeam(user, req)
|
|
1523
|
+
if (setCache) {
|
|
1524
|
+
await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByTokenDur })
|
|
1525
|
+
}
|
|
1526
|
+
return user
|
|
1527
|
+
}
|
|
1528
|
+
|
|
1529
|
+
getUserByUsernamePassword = async (username = '', password = '', req) => {
|
|
1530
|
+
const { getModel } = this.app.dobo
|
|
1531
|
+
const { importPkg } = this.app.bajo
|
|
1532
|
+
const model = getModel('SumbaUser')
|
|
1533
|
+
await model.validate({ username, password }, null, { partial: true, ns: ['sumba', 'dobo'], fields: ['username', 'password'] })
|
|
1534
|
+
const bcrypt = await importPkg('bajoExtra:bcrypt')
|
|
1535
|
+
|
|
1536
|
+
const query = { username, provider: 'local', siteId: req.site.id + '' }
|
|
1537
|
+
const user = await model.findOneRecord({ query }, { req, forceNoHidden: true, noHook: true, noDriverHook: true })
|
|
1538
|
+
if (!user) throw this.error('validationError', { details: [{ field: 'username', error: 'Unknown username' }], statusCode: 401 })
|
|
1539
|
+
if (user.status !== 'ACTIVE') throw this.error('validationError', { details: ['User is inactive or temporarily disabled'], statusCode: 401 })
|
|
1540
|
+
const verified = await bcrypt.compare(password, user.password)
|
|
1541
|
+
if (!verified) throw this.error('validationError', { details: [{ field: 'password', error: 'invalidPassword' }], statusCode: 401 })
|
|
1542
|
+
await this.mergeTeam(user, req)
|
|
1543
|
+
return user
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
/**
|
|
1547
|
+
* Clear the cache for a specific site.
|
|
1548
|
+
*
|
|
1549
|
+
* @async
|
|
1550
|
+
* @method
|
|
1551
|
+
* @param {string|number} id - The ID of the site.
|
|
1552
|
+
* @param {object} result - The result object containing site data.
|
|
1553
|
+
*/
|
|
1554
|
+
clearCacheSite = async (id, result) => {
|
|
1555
|
+
if (!this.app.bajoCache) return
|
|
1556
|
+
const { clear } = this.app.bajoCache ?? {}
|
|
1557
|
+
const { get } = this.app.lib._
|
|
1558
|
+
await clear({ key: 'dobo|SumbaSite|getSite|default' })
|
|
1559
|
+
await clear({ key: `dobo|SumbaSite|getSite|multiSite|${id}` })
|
|
1560
|
+
await clear({ key: `dobo|SumbaSite|getSite|multiSite|${get(result, 'data.hostname', get(result, 'oldData.hostname'))}` })
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
/**
|
|
1564
|
+
* Clear the cache for a specific user.
|
|
1565
|
+
*
|
|
1566
|
+
* @async
|
|
1567
|
+
* @method
|
|
1568
|
+
* @param {string|number} id - The ID of the user.
|
|
1569
|
+
* @param {object} result - The result object containing user data.
|
|
1570
|
+
*/
|
|
1571
|
+
clearCacheUser = async (id, result) => {
|
|
1572
|
+
if (!this.app.bajoCache) return
|
|
1573
|
+
const { clear } = this.app.bajoCache ?? {}
|
|
1574
|
+
const { get } = this.app.lib._
|
|
1575
|
+
const token = get(result, 'data.token', get(result, 'oldData.token', ''))
|
|
1576
|
+
await clear({ key: `dobo|SumbaUser|getUserById|${id}` })
|
|
1577
|
+
await clear({ key: `dobo|SumbaUser|getUserByToken|${token}` })
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
/**
|
|
1581
|
+
* Filter model data based on settings.
|
|
1582
|
+
*
|
|
1583
|
+
* @method
|
|
1584
|
+
* @param {object} opts - The options object.
|
|
1585
|
+
* @param {object} opts.model - The model object.
|
|
1586
|
+
* @param {string} opts.field - The field to filter.
|
|
1587
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1588
|
+
* @returns {object} The filtered results and operation values.
|
|
1589
|
+
*/
|
|
1590
|
+
filterModelFromSetting = (opts = {}) => {
|
|
1591
|
+
const { model, field, options = {} } = opts
|
|
1592
|
+
const { isEmpty, isArray, set } = this.app.lib._
|
|
1593
|
+
const { isSet } = this.app.lib.aneka
|
|
1594
|
+
const { req } = options
|
|
1595
|
+
const opValue = req.getSetting(`sumba:queryGuard.${field}`, {})
|
|
1596
|
+
const results = []
|
|
1597
|
+
const prop = model.getProperty(field)
|
|
1598
|
+
for (const op of ['in', 'nin', 'inOrEmpty']) {
|
|
1599
|
+
if (isEmpty(opValue[op]) || !isArray(opValue[op])) continue
|
|
1600
|
+
if (op === 'inOrEmpty') {
|
|
1601
|
+
const val = set({}, field, set({}, '$in', opValue[op]))
|
|
1602
|
+
const nl = set({}, field, { $eq: null })
|
|
1603
|
+
const item = { $or: [val, nl] }
|
|
1604
|
+
let v
|
|
1605
|
+
if (['string', 'text'].includes(prop.type)) v = ''
|
|
1606
|
+
else if (['integer', 'smallint', 'float', 'double'].includes(prop.type)) v = 0
|
|
1607
|
+
if (isSet(v)) {
|
|
1608
|
+
const bl = set({}, field, { $eq: v })
|
|
1609
|
+
item.$or.push(bl)
|
|
1610
|
+
}
|
|
1611
|
+
results.push(item)
|
|
1612
|
+
} else results.push(set({}, field, set({}, '$' + op, opValue[op])))
|
|
1613
|
+
}
|
|
1614
|
+
return { results, opValue }
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
/**
|
|
1618
|
+
* Apply query guards to the provided query.
|
|
1619
|
+
*
|
|
1620
|
+
* @async
|
|
1621
|
+
* @method
|
|
1622
|
+
* @param {object} [opts={}] - The options object.
|
|
1623
|
+
* @param {object} opts.model - The model object.
|
|
1624
|
+
* @param {object} [opts.q={}] - The query object.
|
|
1625
|
+
* @param {array} [opts.teamIds=[]] - The team IDs.
|
|
1626
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1627
|
+
*/
|
|
1628
|
+
runQueryGuard = async (opts = {}) => {
|
|
1629
|
+
const { model, q = {}, teamIds = [], options = {} } = opts
|
|
1630
|
+
const { set, orderBy, isEmpty, isArray } = this.app.lib._
|
|
1631
|
+
const { includes } = this.app.lib.aneka
|
|
1632
|
+
const { sanitizeByType } = this.app.dobo
|
|
1633
|
+
const { req } = options
|
|
1634
|
+
const results = []
|
|
1635
|
+
|
|
1636
|
+
const guards = await this.getQueryGuards()
|
|
1637
|
+
const fields = model.getNonVirtualProperties().map(prop => prop.name)
|
|
1638
|
+
const filterFn = item => {
|
|
1639
|
+
const bySiteId = item.siteId === req.site.id + ''
|
|
1640
|
+
const byModel = item.models.includes(model.name)
|
|
1641
|
+
const byFields = fields.includes(item.field)
|
|
1642
|
+
return bySiteId && byModel && byFields
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
const rules = orderBy(guards.filter(filterFn), ['field'])
|
|
1646
|
+
for (const field of fields) {
|
|
1647
|
+
if (!model.getNonVirtualProperties(true).includes(field)) continue // or, should it throws exception instead?
|
|
1648
|
+
const inSetting = this.filterModelFromSetting({ model, field, options })
|
|
1649
|
+
if (inSetting.results.length > 0) inSetting.results.push(...inSetting.results)
|
|
1650
|
+
const prop = model.getProperty(field)
|
|
1651
|
+
const items = rules.filter(item => item.field === field)
|
|
1652
|
+
for (const item of items) {
|
|
1653
|
+
let values = item.value.map(val => {
|
|
1654
|
+
return sanitizeByType(val, prop.type, { strict: true, inputFormat: 'string', model: model.name })
|
|
1655
|
+
})
|
|
1656
|
+
const op = item.condition.toLowerCase()
|
|
1657
|
+
if (['in', 'nin'].includes(op) && !isEmpty(inSetting.opValue[op]) && isArray(inSetting.opValue[op])) values = values.filter(val => inSetting.opValue[op].includes(val))
|
|
1658
|
+
if (isEmpty(values)) continue
|
|
1659
|
+
let value
|
|
1660
|
+
if (['in', 'nin'].includes(op)) value = set({}, '$' + op, values)
|
|
1661
|
+
else if (op === 'between') value = { $gte: values[0], $lte: values[1] }
|
|
1662
|
+
else value = set({}, '$' + op, values[0])
|
|
1663
|
+
const teamOk = item.allTeams ? true : (item.teamIds.length === 0 ? false : includes(item.teamIds, teamIds))
|
|
1664
|
+
if (!teamOk) throw this.error('_abortAction')
|
|
1665
|
+
results.push(set({}, field, value))
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
q.$and.push(...results)
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
/**
|
|
1672
|
+
* Apply attribute guards to the provided model.
|
|
1673
|
+
*
|
|
1674
|
+
* @async
|
|
1675
|
+
* @method
|
|
1676
|
+
* @param {object} [opts={}] - The options object.
|
|
1677
|
+
* @param {object} opts.model - The model object.
|
|
1678
|
+
* @param {array} [opts.teamIds=[]] - The team IDs.
|
|
1679
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1680
|
+
*/
|
|
1681
|
+
runAttribGuard = async (opts = {}) => {
|
|
1682
|
+
const { model, teamIds = [], options = {} } = opts
|
|
1683
|
+
const { uniq } = this.app.lib._
|
|
1684
|
+
const { includes } = this.app.lib.aneka
|
|
1685
|
+
const { req } = options
|
|
1686
|
+
const results = []
|
|
1687
|
+
|
|
1688
|
+
const guards = await this.getAttribGuards()
|
|
1689
|
+
const filterFn = item => {
|
|
1690
|
+
const bySiteId = item.siteId === req.site.id + ''
|
|
1691
|
+
const byModel = item.models.includes(model.name)
|
|
1692
|
+
const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
|
|
1693
|
+
return bySiteId && byModel && byTeamId
|
|
1694
|
+
}
|
|
1695
|
+
guards.filter(filterFn).forEach(item => results.push(...item.hiddenFields))
|
|
1696
|
+
options.hidden = options.hidden ?? []
|
|
1697
|
+
options.hidden.push(...results)
|
|
1698
|
+
options.hidden = uniq(options.hidden)
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
/**
|
|
1702
|
+
* Get the team IDs and aliases for the user in the request.
|
|
1703
|
+
*
|
|
1704
|
+
* @method
|
|
1705
|
+
* @param {object} req - The request object.
|
|
1706
|
+
* @returns {object} An object containing the team IDs and aliases.
|
|
1707
|
+
*/
|
|
1708
|
+
getTeamIdsAndAliases = (req) => {
|
|
1709
|
+
const { get } = this.app.lib._
|
|
1710
|
+
const teams = get(req, 'user.teams', [])
|
|
1711
|
+
const teamIds = teams.map(team => team.id + '')
|
|
1712
|
+
const aliases = teams.map(team => team.alias)
|
|
1713
|
+
return { teamIds, aliases }
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
/**
|
|
1717
|
+
* Rebuild the filter for the provided model.
|
|
1718
|
+
*
|
|
1719
|
+
* @async
|
|
1720
|
+
* @method
|
|
1721
|
+
* @param {object} model - The model object.
|
|
1722
|
+
* @param {object} [filter={}] - The filter object.
|
|
1723
|
+
* @param {object} [options={}] - Additional options.
|
|
1724
|
+
* @returns {Promise<object>} The rebuilt filter.
|
|
1725
|
+
*/
|
|
1726
|
+
rebuildFilter = async (model, filter = {}, options = {}) => {
|
|
1727
|
+
const { isEmpty, get, keys } = this.app.lib._
|
|
1728
|
+
const { req } = options
|
|
1729
|
+
const allowEmpty = !get(this, `app.${model.ns}.config.sumba.noEmptyQuery`, []).includes(model.name)
|
|
1730
|
+
const hasSiteId = model.hasProperty('siteId')
|
|
1731
|
+
const hasUserId = model.hasProperty('userId')
|
|
1732
|
+
const hasTeamId = model.hasProperty('teamId')
|
|
1733
|
+
const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
|
|
1734
|
+
const q = { $and: [] }
|
|
1735
|
+
|
|
1736
|
+
filter.query = filter.query ?? {}
|
|
1737
|
+
if (!isEmpty(filter.query)) {
|
|
1738
|
+
if (filter.query.$and) q.$and.push(...filter.query.$and)
|
|
1739
|
+
else q.$and.push(filter.query)
|
|
1740
|
+
}
|
|
1741
|
+
if (req.routeOptions.config.xSite) {
|
|
1742
|
+
filter.query = q
|
|
1743
|
+
return
|
|
1744
|
+
}
|
|
1745
|
+
if (hasSiteId) q.$and.push({ siteId: req.site.id + '' })
|
|
1746
|
+
if (aliases.includes('administrator')) {
|
|
1747
|
+
if (get(req, 'site.alias') === 'default') {
|
|
1748
|
+
filter.query = q
|
|
1749
|
+
return
|
|
1750
|
+
}
|
|
1751
|
+
const fields = keys(req.getSetting('sumba:queryGuard', {}))
|
|
1752
|
+
const results = []
|
|
1753
|
+
for (const field of fields) {
|
|
1754
|
+
if (!model.hasProperty(field)) continue
|
|
1755
|
+
const inSetting = this.filterModelFromSetting({ model, field, options })
|
|
1756
|
+
if (inSetting.results.length > 0) results.push(...inSetting.results)
|
|
1757
|
+
}
|
|
1758
|
+
if (results.length > 0) q.$and.push(...results)
|
|
1759
|
+
filter.query = q
|
|
1760
|
+
return
|
|
1761
|
+
}
|
|
1762
|
+
if (isEmpty(req.user)) {
|
|
1763
|
+
if (q.$and.length === 0 && !allowEmpty) throw this.error('_emptyColumnQuery')
|
|
1764
|
+
filter.query = q
|
|
1765
|
+
return
|
|
1766
|
+
}
|
|
1767
|
+
|
|
1768
|
+
const condUserId = {
|
|
1769
|
+
$or: [
|
|
1770
|
+
{ userId: req.user.id + '' },
|
|
1771
|
+
{ userId: { $eq: null } }
|
|
1772
|
+
]
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
const condTeamId = {
|
|
1776
|
+
$or: [
|
|
1777
|
+
{ teamId: { $in: teamIds } },
|
|
1778
|
+
{ teamId: { $eq: null } }
|
|
1779
|
+
]
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
if (hasTeamId) {
|
|
1783
|
+
if (hasUserId) q.$and.push({ $or: [condTeamId, condUserId] })
|
|
1784
|
+
else q.$and.push(condTeamId)
|
|
1785
|
+
} else if (hasUserId) q.$and.push(condUserId)
|
|
1786
|
+
|
|
1787
|
+
await this.runQueryGuard({ model, q, teamIds, options, allowEmpty })
|
|
1788
|
+
await this.runAttribGuard({ model, teamIds, options })
|
|
1789
|
+
if (q.$and.length === 0 && !allowEmpty) throw this.error('_emptyColumnQuery')
|
|
1790
|
+
filter.query = q
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
/**
|
|
1794
|
+
* Apply query hook to the provided model.
|
|
1795
|
+
*
|
|
1796
|
+
* @async
|
|
1797
|
+
* @method
|
|
1798
|
+
* @param {object} model - The model object.
|
|
1799
|
+
* @param {string|number} id - The ID of the model.
|
|
1800
|
+
* @param {object} options - Additional options.
|
|
1801
|
+
* @returns {object} The result of the model hook.
|
|
1802
|
+
*/
|
|
1803
|
+
applyQueryHook = async (model, id, options = {}) => {
|
|
1804
|
+
const { isEmpty } = this.app.lib._
|
|
1805
|
+
const { req = {} } = options
|
|
1806
|
+
if (options.noAutoFilter || isEmpty(req) || isEmpty(req.site)) return
|
|
1807
|
+
|
|
1808
|
+
const filter = {}
|
|
1809
|
+
await this.rebuildFilter(model, filter, options)
|
|
1810
|
+
if (filter.query.$and) filter.query.$and.push({ id })
|
|
1811
|
+
else filter.query.id = id
|
|
1812
|
+
const row = await model.findOneRecord(filter, { count: false })
|
|
1813
|
+
if (!row) throw this.app.dobo.error('recordNotFound%s%s', id, this.name, { statusCode: 404 })
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
/**
|
|
1817
|
+
* Apply action hook to the provided model.
|
|
1818
|
+
*
|
|
1819
|
+
* @async
|
|
1820
|
+
* @method
|
|
1821
|
+
* @param {object} [opts={}] - The options object.
|
|
1822
|
+
* @param {object} opts.model - The model object.
|
|
1823
|
+
* @param {array} [opts.teamIds=[]] - The team IDs.
|
|
1824
|
+
* @param {object} [opts.options={}] - Additional options.
|
|
1825
|
+
*/
|
|
1826
|
+
applyActionHook = async (opts = {}) => {
|
|
1827
|
+
const { model, options = {} } = opts
|
|
1828
|
+
const { req } = options
|
|
1829
|
+
if (!req) return
|
|
1830
|
+
if (!req.site) return
|
|
1831
|
+
|
|
1832
|
+
let action
|
|
1833
|
+
if (['findOneRecord', 'findRecord', 'countRecord', 'getRecord'].includes(options.action)) action = 'READ'
|
|
1834
|
+
else if (['createRecord', 'bulkCreateRecord'].includes(options.action)) action = 'CREATE'
|
|
1835
|
+
else if (['updateRecord', 'upsertRecord'].includes(options.action)) action = 'UPDATE'
|
|
1836
|
+
else if (['removeRecord'].includes(options.action)) action = 'REMOVE'
|
|
1837
|
+
else if (['findAllRecord'].includes(options.action)) action = 'EXPORT'
|
|
1838
|
+
if (!action) return
|
|
855
1839
|
|
|
856
|
-
|
|
857
|
-
|
|
1840
|
+
const allowed = await this.isActionAllowed(action, model, req)
|
|
1841
|
+
if (!allowed) throw this.error('accessDenied', { statusCode: 403 })
|
|
1842
|
+
}
|
|
1843
|
+
|
|
1844
|
+
/**
|
|
1845
|
+
* Check if the specified action is allowed for the given model and request. It retrieves the action guards, filters them based on the site ID, model name, and team IDs, and checks if the action is included in the allowed values. If any guard denies the action, it returns false; otherwise, it returns true.
|
|
1846
|
+
*
|
|
1847
|
+
* @async
|
|
1848
|
+
* @method
|
|
1849
|
+
* @param {string} action - The action to check. Available actions are: 'READ', 'CREATE', 'UPDATE', 'REMOVE' and 'EXPORT'.
|
|
1850
|
+
* @param {object} model - The model object.
|
|
1851
|
+
* @param {object} req - The request object.
|
|
1852
|
+
* @returns {Promise<boolean>} - Returns true if the action is allowed, otherwise false.
|
|
1853
|
+
*/
|
|
1854
|
+
isActionAllowed = async (action, model, req) => {
|
|
1855
|
+
const { includes } = this.app.lib.aneka
|
|
1856
|
+
if (!req) return true
|
|
1857
|
+
if (!req.site) return true
|
|
1858
|
+
const guards = await this.getActionGuards()
|
|
1859
|
+
const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
|
|
1860
|
+
if (aliases.includes('administrator')) return true
|
|
1861
|
+
const filterFn = item => {
|
|
1862
|
+
const bySiteId = item.siteId === req.site.id + ''
|
|
1863
|
+
const byModel = item.models.includes(model.name)
|
|
1864
|
+
const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
|
|
1865
|
+
return bySiteId && byModel && byTeamId
|
|
1866
|
+
}
|
|
1867
|
+
let denied = false
|
|
1868
|
+
for (const item of guards.filter(filterFn)) {
|
|
1869
|
+
if (item.value.includes('*')) continue
|
|
1870
|
+
if (!item.value.includes(action)) denied = true
|
|
1871
|
+
}
|
|
1872
|
+
return !denied
|
|
1873
|
+
}
|
|
858
1874
|
}
|
|
859
1875
|
|
|
860
1876
|
return Sumba
|