sumba 2.34.4 → 2.36.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.
Files changed (34) hide show
  1. package/docs/Sumba.html +1 -1
  2. package/docs/data/search.json +1 -1
  3. package/docs/global.html +1 -1
  4. package/docs/index.html +1 -1
  5. package/docs/index.js.html +1544 -331
  6. package/docs/lib_config.js.html +201 -0
  7. package/docs/lib_constant.js.html +47 -0
  8. package/docs/lib_token-schema.js.html +47 -0
  9. package/extend/bajo/hook.js +27 -192
  10. package/extend/bajo/intl/en-US.json +14 -13
  11. package/extend/bajo/intl/id.json +15 -14
  12. package/extend/dobo/model.js +27 -1
  13. package/extend/waibuDb/schema/model-guard.js +2 -2
  14. package/extend/waibuMpa/extend/waibuAdmin/route/action-guard/@action.js +11 -0
  15. package/extend/waibuMpa/extend/waibuAdmin/route/{model-guard → query-guard}/@action.js +2 -2
  16. package/extend/waibuMpa/extend/waibuAdmin/route/team/@action.js +1 -1
  17. package/extend/waibuMpa/extend/waibuAdmin/route/team-setting/@action.js +1 -1
  18. package/extend/waibuMpa/extend/waibuAdmin/route/team-user/@action.js +1 -1
  19. package/extend/waibuMpa/extend/waibuAdmin/route/user/@action.js +1 -1
  20. package/extend/waibuMpa/extend/waibuAdmin/route/user-setting/@action.js +1 -1
  21. package/extend/waibuMpa/extend/waibuAdmin/route/x/site-setting/@action.js +1 -1
  22. package/extend/waibuRestApi/route/user/access-token/@type/create.js +1 -1
  23. package/extend/waibuRestApi/route/user/api-key/get.js +1 -1
  24. package/extend/waibuRestApi/route/your-stuff/api-key/update.js +1 -1
  25. package/index.js +1077 -192
  26. package/lib/config.js +198 -0
  27. package/lib/constant.js +44 -0
  28. package/package.json +9 -3
  29. package/wiki/CHANGES.md +12 -0
  30. package/lib/create-new-site.js +0 -106
  31. package/lib/get-site.js +0 -70
  32. package/lib/get-user.js +0 -89
  33. package/lib/remove-site.js +0 -39
  34. package/lib/token-schema.js +0 -29
package/index.js CHANGED
@@ -1,178 +1,49 @@
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'
2
+ import configFactory, { defMultiSite } from './lib/config.js'
6
3
  import { joiPasswordExtendCore } from 'joi-password'
7
4
 
8
- const defMultiSite = {
9
- enabled: false,
10
- catchAll: 'default',
11
- admins: []
12
- }
13
-
14
5
  /**
15
- * Plugin factory
6
+ * Plugin factory.
7
+ *
8
+ * **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
9
  *
17
10
  * @param {string} pkgName - NPM package name
18
- * @returns {class}
11
+ * @returns {Sumba} Sumba class
19
12
  */
20
13
  async function factory (pkgName) {
21
14
  const me = this
22
15
  const { getModel } = this.app.dobo
23
16
  const { cloneDeep, isEmpty } = this.app.lib._
17
+ const config = await configFactory.call(this)
24
18
 
25
19
  /**
26
- * Sumba class
20
+ * Sumba class definition.
27
21
  *
28
22
  * @class
29
23
  */
30
24
  class Sumba extends this.app.baseClass.Base {
25
+ /**
26
+ * Constructor
27
+ */
31
28
  constructor () {
32
29
  super(pkgName, me.app)
33
- this.config = {
34
- multiSite: cloneDeep(defMultiSite),
35
- xSiteAdmins: [], // format: "<siteAlias>:<username>"
36
- waibu: {
37
- title: 'site',
38
- prefix: 'site'
39
- },
40
- dobo: {
41
- model: {}
42
- },
43
- waibuMpa: {
44
- home: 'sumba:/your-stuff/profile',
45
- icon: 'globe',
46
- redirect: {
47
- '/': 'sumba:/your-stuff/profile',
48
- '/your-stuff': 'sumba:/your-stuff/profile',
49
- '/info': 'sumba:/info/about-us',
50
- '/user': 'sumba:/your-stuff/profile',
51
- '/db/export': 'sumba:/db/export/list',
52
- '/help': 'sumba:/help/contact-form',
53
- '/help/trouble-tickets': 'sumba:/help/trouble-tickets/list'
54
- },
55
- redirectSubRoute: {
56
- waibuAdmin: {
57
- '/': 'waibuAdmin:/site/site',
58
- '/x': 'waibuAdmin:/site/x/site/list',
59
- '/x/*': 'waibuAdmin:/site/x/{2}/list',
60
- '/*': 'waibuAdmin:/site/{1}/list'
61
- }
62
- },
63
- menuHandler: [{
64
- title: 'account',
65
- icon: 'person',
66
- level: 9998,
67
- children: [
68
- // anonymous only
69
- { title: 'signin', href: 'sumba:/signin', visible: 'anon' },
70
- { title: 'forgotPassword', href: 'sumba:/user/forgot-password', visible: 'anon' },
71
- { title: 'newUserSignup', href: 'sumba:/user/signup', visible: 'anon' },
72
- { title: '-', visible: 'anon' },
73
- { title: 'activation', href: 'sumba:/user/activation', visible: 'anon' },
74
- // authenticated only
75
- { title: 'yourProfile', href: 'sumba:/your-stuff/profile', visible: 'auth' },
76
- { title: 'changePassword', href: 'sumba:/your-stuff/change-password', visible: 'auth' },
77
- { title: 'downloadList', href: 'sumba:/your-stuff/download/list', visible: 'auth' },
78
- { title: '-', visible: 'auth' },
79
- { title: 'signout', href: 'sumba:/signout', visible: 'auth' }
80
- ]
81
- }, {
82
- title: 'help',
83
- icon: 'signInfo',
84
- level: 9999,
85
- children: [
86
- { title: 'contactForm', href: 'sumba:/help/contact-form' },
87
- { title: 'troubleTickets', href: 'sumba:/help/trouble-tickets', visible: 'auth' },
88
- { title: '-' },
89
- { title: 'cookiePolicy', href: 'sumba:/info/cookie-policy' },
90
- { title: 'privacy', href: 'sumba:/info/privacy' },
91
- { title: 'termsConditions', href: 'sumba:/info/terms-conditions' }
92
- ]
93
- }]
94
- },
95
- waibuAdmin: {
96
- menuHandler: 'sumba:adminMenu',
97
- menuCollapsible: true,
98
- modelDisabled: 'all'
99
- },
100
- auth: {
101
- common: {
102
- apiKey: {
103
- type: 'Bearer',
104
- qsKey: 'apiKey',
105
- headerKey: 'X-Auth-ApiKey',
106
- algo: 'sha256' // changing this require each and every user to reset their apiKey
107
- },
108
- basic: {
109
- },
110
- jwt: {
111
- type: 'Bearer',
112
- qsKey: 'token',
113
- headerKey: 'X-Auth-Jwt',
114
- secret: '668de9cf57316c7dbf52f7ff7611c299',
115
- expiresInDur: '7d'
116
- }
117
- },
118
- waibuRestApi: {
119
- methods: ['basic', 'apiKey', 'jwt'],
120
- silentOnError: false
121
- },
122
- waibuMpa: {
123
- methods: ['session'],
124
- silentOnError: false
125
- },
126
- waibuStatic: {
127
- methods: ['basic', 'apiKey', 'jwt'],
128
- basic: {
129
- useUtf8: true,
130
- realm: true,
131
- warningMessage: 'pleaseAuthenticate'
132
- },
133
- silentOnError: false
134
- }
135
- },
136
- redirect: {
137
- signin: 'sumba:/signin',
138
- afterSignin: '/',
139
- signout: 'sumba:/signout',
140
- afterSignout: '/'
141
- },
142
- siteSetting: {
143
- forgotPasswordExpDur: '5m',
144
- timeZone: 'UTC',
145
- userPassword: {
146
- minUpperCase: 1,
147
- minLowerCase: 1,
148
- minSpecialChar: 1,
149
- minNumeric: 1,
150
- noWhitespace: false,
151
- latinOnlyChars: false,
152
- pattern: {
153
- lowerCase: 'abcdefghijklmnopqrstuvwxyz',
154
- upperCase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
155
- specialChar: '!@#$%*',
156
- numeric: '0123456789'
157
- }
158
- }
159
- },
160
- cacheTtl: {
161
- getSiteDur: '1m',
162
- getUserByIdDur: '1m',
163
- getUserByTokenDur: '1m'
164
- }
165
- }
30
+ this.config = config
166
31
  this.secureGuards = []
167
- this.modelGuards = []
32
+ this.actionGuards = []
33
+ this.queryGuards = []
168
34
  this.attribGuards = []
169
35
  this.secureGuards = []
170
36
  this.anonymousGuards = []
171
37
 
172
38
  this.unsafeUserFields = ['password']
173
- this.selfBind(['createNewSite', 'removeSite', 'getSite', 'getUserById', 'getUserByToken', 'getUserByUsernamePassword'])
174
39
  }
175
40
 
41
+ /**
42
+ * Plugin initialization method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin initialization.
43
+ *
44
+ * @async
45
+ * @method
46
+ */
176
47
  init = async () => {
177
48
  this.downloadDir = `${this.app.getPluginDataDir(this.ns)}/download`
178
49
  this.app.lib.fs.ensureDirSync(this.downloadDir)
@@ -182,6 +53,12 @@ async function factory (pkgName) {
182
53
  }
183
54
  }
184
55
 
56
+ /**
57
+ * Plugin start method. This method is called by the {@link https://ardhi.github.io/bajo|Bajo framework} during plugin start.
58
+ *
59
+ * @async
60
+ * @method
61
+ */
185
62
  start = async () => {
186
63
  await this.populateRouteGuards()
187
64
  if (!this.config.multiSite.enabled) {
@@ -195,6 +72,13 @@ async function factory (pkgName) {
195
72
  }
196
73
  }
197
74
 
75
+ /**
76
+ * Populate route guards at start
77
+ *
78
+ * @async
79
+ * @method
80
+ * @param {array} [sites] - List of sites to populate route guards for. If not provided, it will fetch all active sites.
81
+ */
198
82
  populateRouteGuards = async (sites) => {
199
83
  const { isString, get, difference } = this.app.lib._
200
84
  const { pascalCase } = this.app.lib.aneka
@@ -273,19 +157,41 @@ async function factory (pkgName) {
273
157
  }
274
158
  }
275
159
 
276
- _getSetting = async (type, source) => {
160
+ /**
161
+ * Get authentication setting based on type and source
162
+ *
163
+ * @method
164
+ * @private
165
+ * @param {string} type - The type of authentication setting to retrieve. If not provided, it will use parent setting.
166
+ * @param {string} [source] - The source of the authentication setting. If not provided, it will use the default setting.
167
+ * @returns {object} - The authentication setting object.
168
+ */
169
+ _getAuthSetting = (type, source) => {
277
170
  const { defaultsDeep } = this.app.lib.aneka
278
171
  const { get } = this.app.lib._
279
172
 
280
- const setting = defaultsDeep(get(this.config, `auth.${source}.${type}`, {}), get(this.config, `auth.common.${type}`, {}))
173
+ let setting
174
+ const withType = type ? `.${type}` : ''
175
+ if (source) setting = defaultsDeep(get(this.config, `${source}.auth${withType}`, {}), get(this.config, `auth${withType}`, {}))
176
+ else setting = get(this.config, `auth${withType}`, {})
281
177
  if (type === 'basic') setting.type = 'Basic'
282
178
  return setting
283
179
  }
284
180
 
285
- _getToken = async (type, req, source) => {
181
+ /**
182
+ * Get authentication token based on type, request, and source
183
+ *
184
+ * @method
185
+ * @private
186
+ * @param {string} type - The type of authentication setting.
187
+ * @param {object} req - The request object.
188
+ * @param {string} [source] - The source of the authentication setting. If not provided, it will use the default setting.
189
+ * @returns {string|boolean} - The token if found, otherwise false.
190
+ */
191
+ _getAuthToken = (type, req, source) => {
286
192
  const { isEmpty } = this.app.lib._
287
193
 
288
- const setting = await this._getSetting(type, source)
194
+ const setting = this._getAuthSetting(type, source)
289
195
  let token = req.headers[setting.headerKey.toLowerCase()]
290
196
  if (!['basic'].includes(type) && isEmpty(token)) token = req.query[setting.qsKey]
291
197
  if (isEmpty(token)) {
@@ -296,6 +202,19 @@ async function factory (pkgName) {
296
202
  return token
297
203
  }
298
204
 
205
+ /**
206
+ * Build admin menu based on locals and request.
207
+ *
208
+ * - If multi-site is enabled, it will include the cross-site menu with options to manage all sites and site settings.
209
+ * - If caching is enabled, it will include the cache storage menu in the appropriate section.
210
+ * - Session management menu is also included in the appropriate section.
211
+ *
212
+ * @async
213
+ * @method
214
+ * @param {object} locals - The locals object.
215
+ * @param {object} req - The request object.
216
+ * @returns {array} - The admin menu items.
217
+ */
299
218
  adminMenu = async (locals, req) => {
300
219
  if (!this.app.waibuAdmin) return
301
220
  const { getPluginPrefix } = this.app.waibu
@@ -306,28 +225,25 @@ async function factory (pkgName) {
306
225
  title: 'manageSite',
307
226
  children: [
308
227
  { title: 'siteProfile', href: `waibuAdmin:/${prefix}/site` },
309
- { title: 'siteSetting', href: `waibuAdmin:/${prefix}/site-setting/:action`, params }
228
+ { title: 'manageSiteSetting', href: `waibuAdmin:/${prefix}/site-setting/:action`, params }
310
229
  ]
311
230
  }, {
312
- title: 'manageUser',
231
+ title: 'manageUserTeam',
313
232
  children: [
314
- { title: 'userProfile', href: `waibuAdmin:/${prefix}/user/:action`, params },
315
- { title: 'userSetting', href: `waibuAdmin:/${prefix}/user-setting/:action`, params },
233
+ { title: 'manageUser', href: `waibuAdmin:/${prefix}/user/:action`, params },
234
+ { title: 'manageUserSetting', href: `waibuAdmin:/${prefix}/user-setting/:action`, params },
235
+ { title: 'manageTeam', href: `waibuAdmin:/${prefix}/team/:action`, params },
236
+ { title: 'manageTeamUser', href: `waibuAdmin:/${prefix}/team-user/:action`, params },
237
+ { title: 'manageTeamSetting', href: `waibuAdmin:/${prefix}/team-setting/:action`, params },
316
238
  { title: 'resetUserPassword', href: `waibuAdmin:/${prefix}/reset-user-password` }
317
239
  ]
318
240
  }, {
319
- title: 'manageTeam',
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',
241
+ title: 'permissionGuard',
327
242
  children: [
328
243
  { title: 'secureGuard', href: `waibuAdmin:/${prefix}/secure-guard/:action`, params },
329
244
  { title: 'anonymousGuard', href: `waibuAdmin:/${prefix}/anonymous-guard/:action`, params },
330
- { title: 'modelGuard', href: `waibuAdmin:/${prefix}/model-guard/:action`, params },
245
+ { title: 'actionGuard', href: `waibuAdmin:/${prefix}/action-guard/:action`, params },
246
+ { title: 'queryGuard', href: `waibuAdmin:/${prefix}/query-guard/:action`, params },
331
247
  { title: 'attribGuard', href: `waibuAdmin:/${prefix}/attrib-guard/:action`, params }
332
248
  ]
333
249
  }, {
@@ -350,8 +266,8 @@ async function factory (pkgName) {
350
266
  items.unshift({
351
267
  title: 'xSite',
352
268
  children: [
353
- { title: 'allSites', href: `waibuAdmin:/${prefix}/x/site/:action`, params },
354
- { title: 'siteSetting', href: `waibuAdmin:/${prefix}/x/site-setting/:action`, params },
269
+ { title: 'manageAllSites', href: `waibuAdmin:/${prefix}/x/site/:action`, params },
270
+ { title: 'manageAllSiteSettings', href: `waibuAdmin:/${prefix}/x/site-setting/:action`, params },
355
271
  sessionMenu
356
272
  ]
357
273
  })
@@ -366,6 +282,14 @@ async function factory (pkgName) {
366
282
  return items
367
283
  }
368
284
 
285
+ /**
286
+ * Create JWT from user record
287
+ *
288
+ * @async
289
+ * @method
290
+ * @param {object} rec - The user record object.
291
+ * @returns {Promise<object>} - The JWT token and its expiration date.
292
+ */
369
293
  createJwtFromUserRecord = async (rec) => {
370
294
  const { importPkg } = this.app.bajo
371
295
  const { dayjs } = this.app.lib
@@ -374,8 +298,9 @@ async function factory (pkgName) {
374
298
  const fastJwt = await importPkg('bajoExtra:fast-jwt')
375
299
  const { createSigner } = fastJwt
376
300
 
377
- const opts = pick(this.config.auth.common.jwt, ['expiresInDur'])
378
- opts.key = get(this.config, 'auth.common.jwt.secret')
301
+ const setting = this._getAuthSetting('jwt')
302
+ const opts = pick(setting, ['expiresInDur'])
303
+ opts.key = get(setting, 'secret')
379
304
  const sign = createSigner(opts)
380
305
  const apiKey = await this.hash(rec.token)
381
306
  const payload = { uid: rec.id, apiKey }
@@ -384,6 +309,17 @@ async function factory (pkgName) {
384
309
  return { token, expiresAt }
385
310
  }
386
311
 
312
+ /**
313
+ * Verify user session
314
+ *
315
+ * @async
316
+ * @method
317
+ * @param {object} req - The request object.
318
+ * @param {object} reply - The reply object.
319
+ * @param {string} source - The source of the authentication setting.
320
+ * @param {object} payload - The payload object.
321
+ * @returns {boolean} - True if the session is valid, otherwise false.
322
+ */
387
323
  verifySession = async (req, reply, source, payload) => {
388
324
  const { routePath } = this.app.waibu
389
325
  const { query, params } = req
@@ -398,11 +334,23 @@ async function factory (pkgName) {
398
334
  throw this.error('_redirect', { path: redir })
399
335
  }
400
336
 
337
+ /**
338
+ * Verify API key
339
+ *
340
+ * @async
341
+ * @method
342
+ * @param {object} req - The request object.
343
+ * @param {object} reply - The reply object.
344
+ * @param {string} source - The source of the authentication setting.
345
+ * @param {object} payload - The payload object.
346
+ * @returns {boolean} - True if the API key is valid, otherwise false.
347
+ */
401
348
  verifyApiKey = async (req, reply, source, payload) => {
402
349
  const { merge, camelCase } = this.app.lib._
403
- const checker = this.app.bajoExtra[camelCase(`is ${this.config.auth.common.apiKey.algo}`)]
350
+ const setting = this._getAuthSetting(null, source)
351
+ const checker = this.app.bajoExtra[camelCase(`is ${setting.apiKey.algo}`)]
404
352
 
405
- let token = await this._getToken('apiKey', req, source)
353
+ let token = await this._getAuthToken('apiKey', req, source)
406
354
  if (!checker(token)) return false
407
355
  token = await this.hash(token)
408
356
  const user = await this.getUserByToken(token, req)
@@ -412,6 +360,17 @@ async function factory (pkgName) {
412
360
  return true
413
361
  }
414
362
 
363
+ /**
364
+ * Verify basic authentication
365
+ *
366
+ * @async
367
+ * @method
368
+ * @param {object} req - The request object.
369
+ * @param {object} reply - The reply object.
370
+ * @param {string} source - The source of the authentication setting.
371
+ * @param {object} payload - The payload object.
372
+ * @returns {boolean|string} - True if the basic authentication is valid, otherwise false or an error message.
373
+ */
415
374
  verifyBasic = async (req, reply, source, payload) => {
416
375
  const { isEmpty, merge } = this.app.lib._
417
376
 
@@ -425,7 +384,7 @@ async function factory (pkgName) {
425
384
  reply.code(401)
426
385
  }
427
386
 
428
- const setting = await this._getSetting('basic', source)
387
+ const setting = this._getAuthSetting('basic', source)
429
388
  let authInfo
430
389
  const parts = (req.headers.authorization ?? '').split(' ')
431
390
  if (parts[0] === setting.type) authInfo = parts[1]
@@ -449,14 +408,25 @@ async function factory (pkgName) {
449
408
  return true
450
409
  }
451
410
 
411
+ /**
412
+ * Verify JWT authentication
413
+ *
414
+ * @async
415
+ * @method
416
+ * @param {object} req - The request object.
417
+ * @param {object} reply - The reply object.
418
+ * @param {string} source - The source of the authentication setting.
419
+ * @param {object} payload - The payload object.
420
+ * @returns {boolean} - True if the JWT authentication is valid, otherwise false.
421
+ */
452
422
  verifyJwt = async (req, reply, source, payload) => {
453
423
  const { importPkg } = this.app.bajo
454
424
  const { isEmpty, merge } = this.app.lib._
455
425
 
456
426
  const fastJwt = await importPkg('bajoExtra:fast-jwt')
457
427
  const { createVerifier } = fastJwt
458
- const setting = await this._getSetting('jwt', source)
459
- const token = await this._getToken('jwt', req, source)
428
+ const setting = this._getAuthSetting('jwt', source)
429
+ const token = this._getAuthToken('jwt', req, source)
460
430
  if (isEmpty(token)) return false
461
431
  const verifier = createVerifier({
462
432
  key: setting.secret,
@@ -476,6 +446,14 @@ async function factory (pkgName) {
476
446
  return true
477
447
  }
478
448
 
449
+ /**
450
+ * Check route guard
451
+ *
452
+ * @method
453
+ * @param {Array} guards - The array of guard objects.
454
+ * @param {Array} paths - The array of paths to check.
455
+ * @returns {string|undefined} - The matched path or undefined if no match is found.
456
+ */
479
457
  checkRouteGuard = (guards, paths) => {
480
458
  const { outmatch } = this.app.lib
481
459
  const all = guards.map(item => item.path)
@@ -483,7 +461,18 @@ async function factory (pkgName) {
483
461
  return paths.find(isMatch)
484
462
  }
485
463
 
486
- signout = async ({ req, reply, reason }) => {
464
+ /**
465
+ * Sign out user and redirect to the specified URL
466
+ *
467
+ * @async
468
+ * @method
469
+ * @param {object} options - The options object.
470
+ * @param {object} options.req - The request object.
471
+ * @param {object} options.reply - The reply object.
472
+ * @param {string} [options.reason] - The reason for signing out.
473
+ */
474
+ signout = async (options = {}) => {
475
+ const { req, reply, reason } = options
487
476
  const { runHook } = this.app.bajo
488
477
  const { getSessionId } = this.app.waibuMpa
489
478
  const sid = await getSessionId(req.headers.cookie)
@@ -496,7 +485,18 @@ async function factory (pkgName) {
496
485
  return reply.redirectTo(url, { query, params })
497
486
  }
498
487
 
499
- signin = async ({ user, req, reply }) => {
488
+ /**
489
+ * Sign in user and redirect to the specified URL
490
+ *
491
+ * @async
492
+ * @method
493
+ * @param {object} options - The options object.
494
+ * @param {object} options.req - The request object.
495
+ * @param {object} options.reply - The reply object.
496
+ * @param {object} options.user - The user object.
497
+ */
498
+ signin = async (options = {}) => {
499
+ const { req, reply, user } = options
500
500
  const { getSessionId } = this.app.waibuMpa
501
501
  const { runHook } = this.app.bajo
502
502
  const { isEmpty, omit } = this.app.lib._
@@ -513,6 +513,13 @@ async function factory (pkgName) {
513
513
  return reply.redirectTo(url, { query, params })
514
514
  }
515
515
 
516
+ /**
517
+ * Generate a random password based on the configuration settings
518
+ *
519
+ * @method
520
+ * @param {object} req - The request object.
521
+ * @returns {string} - The generated password.
522
+ */
516
523
  generatePassword = (req = {}) => {
517
524
  const { get } = this.app.lib._
518
525
  const { generateId } = this.app.lib.aneka
@@ -545,12 +552,27 @@ async function factory (pkgName) {
545
552
  await push(jobQueue)
546
553
  }
547
554
 
555
+ /**
556
+ * Get API key from user ID by hashing the user's salt
557
+ *
558
+ * @async
559
+ * @method
560
+ * @param {string|number} id - The user ID.
561
+ * @returns {Promise<string>} - A promise that resolves to the API key.
562
+ */
548
563
  getApiKeyFromUserId = async id => {
549
564
  const options = { forceNoHidden: true, noHook: true, noCache: true, attachment: true, mimeType: true }
550
565
  const resp = await getModel('SumbaUser').getRecord(id, options)
551
566
  return await this.hash(resp.salt)
552
567
  }
553
568
 
569
+ /**
570
+ * Get a list of countries with their values and names
571
+ *
572
+ * @async
573
+ * @method
574
+ * @returns {Promise<Array<{ value: string|number, text: string }>>} - A promise that resolves to an array of country values and names.
575
+ */
554
576
  getCountriesValues = async () => {
555
577
  const { getModel } = this.app.dobo
556
578
  const model = getModel('CdbCountry')
@@ -568,7 +590,6 @@ async function factory (pkgName) {
568
590
  * @async
569
591
  * @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
592
  * @param {Object} [params={}] - {@link https://github.com/ardhi/masohi-mail|masohi-mail}'s params object.
571
- * @returns
572
593
  */
573
594
  sendMail = async (tpl, { payload = {}, conn, source, options = {} } = {}) => {
574
595
  if (!this.app.masohiMail || !this.app.waibu) return
@@ -580,6 +601,7 @@ async function factory (pkgName) {
580
601
  const buildLocals = await importModule('waibu:/lib/build-locals.js')
581
602
 
582
603
  if (isString(tpl)) tpl = [tpl]
604
+ options.partial = false
583
605
  const locals = await buildLocals.call(this, { params: payload.data, opts: options })
584
606
  payload.from = payload.from ?? get(options, 'req.site.email', payload.from)
585
607
  const opts = {
@@ -591,6 +613,14 @@ async function factory (pkgName) {
591
613
  await this.app.masohiMail.send({ payload, source: source ?? this.ns, conn })
592
614
  }
593
615
 
616
+ /**
617
+ * Reset token by generating a new salt and hashing it twice to create a new token.
618
+ *
619
+ * @async
620
+ * @method
621
+ * @param {string} [text] - Optional text to use as the salt. If not provided, a new salt will be generated.
622
+ * @returns {Promise<{ salt: string, token: string }>} - A promise that resolves to an object containing the salt and token.
623
+ */
594
624
  resetToken = async (text) => {
595
625
  const { generateId } = this.app.lib.aneka
596
626
  const salt = text ?? generateId()
@@ -598,6 +628,14 @@ async function factory (pkgName) {
598
628
  return { salt, token }
599
629
  }
600
630
 
631
+ /**
632
+ * Generate a password validation rule based on the configuration settings.
633
+ *
634
+ * @async
635
+ * @method
636
+ * @param {object} req - The request object.
637
+ * @returns {object} - The Joi password validation rule.
638
+ */
601
639
  passwordRule = async (req = {}) => {
602
640
  const { get } = this.app.lib._
603
641
  const { importPkg } = this.app.bajo
@@ -618,11 +656,29 @@ async function factory (pkgName) {
618
656
  return password
619
657
  }
620
658
 
659
+ /**
660
+ * Hash the given item using the specified algorithm from the configuration.
661
+ *
662
+ * @async
663
+ * @method
664
+ * @param {*} item - The item to be hashed.
665
+ * @returns {Promise<string>} - A promise that resolves to the hashed value.
666
+ */
621
667
  hash = async (item) => {
622
668
  const { hash } = this.app.bajoExtra
623
- return await hash(item, this.config.auth.common.apiKey.algo)
669
+ const setting = this._getAuthSetting('apiKey')
670
+ return await hash(item, setting.algo)
624
671
  }
625
672
 
673
+ /**
674
+ * Fetch guards of the specified type from the database.
675
+ *
676
+ * @async
677
+ * @method
678
+ * @private
679
+ * @param {string} type - The type of guards to fetch. Available types are 'Action', 'Attrib', 'Query', 'Secure', and 'Anonymous'.
680
+ * @returns {Promise<Array>} - A promise that resolves to an array of guards.
681
+ */
626
682
  _fetchGuards = async (type) => {
627
683
  const { getModel } = this.app.dobo
628
684
  const options = { noMagic: true, noCache: true, noDriverHook: true, dataOnly: true }
@@ -634,6 +690,14 @@ async function factory (pkgName) {
634
690
  })
635
691
  }
636
692
 
693
+ /**
694
+ * Process and order the guards based on their path and weight.
695
+ *
696
+ * @method
697
+ * @private
698
+ * @param {Array} inputs - The array of guard inputs.
699
+ * @returns {Array} - The processed and ordered array of guards.
700
+ */
637
701
  _getGuards = (inputs = []) => {
638
702
  const { routePath } = this.app.waibu
639
703
  const { orderBy } = this.app.lib._
@@ -656,6 +720,14 @@ async function factory (pkgName) {
656
720
  return [...normal, ...inverse]
657
721
  }
658
722
 
723
+ /**
724
+ * Get anonymous guards, optionally reloading them from the database.
725
+ *
726
+ * @async
727
+ * @method
728
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
729
+ * @returns {Promise<Array>} - A promise that resolves to an array of anonymous guards.
730
+ */
659
731
  getAnonymousGuards = async (reread) => {
660
732
  if (!reread) return this.anonymousGuards
661
733
  const guards = await this._fetchGuards('Anonymous')
@@ -663,6 +735,14 @@ async function factory (pkgName) {
663
735
  return this.anonymousGuards
664
736
  }
665
737
 
738
+ /**
739
+ * Get secure guards, optionally reloading them from the database.
740
+ *
741
+ * @async
742
+ * @method
743
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
744
+ * @returns {Promise<Array>} - A promise that resolves to an array of secure guards.
745
+ */
666
746
  getSecureGuards = async (reread) => {
667
747
  if (!reread) return this.secureGuards
668
748
  const guards = await this._fetchGuards('Secure')
@@ -670,13 +750,44 @@ async function factory (pkgName) {
670
750
  return this.secureGuards
671
751
  }
672
752
 
673
- getModelGuards = async (reread) => {
674
- if (!reread) return this.modelGuards
753
+ /**
754
+ * Get query guards, optionally reloading them from the database.
755
+ *
756
+ * @async
757
+ * @method
758
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
759
+ * @returns {Promise<Array>} - A promise that resolves to an array of query guards.
760
+ */
761
+ getQueryGuards = async (reread) => {
762
+ if (!reread) return this.queryGuards
763
+
764
+ this.queryGuards = await this._fetchGuards('Query')
765
+ return this.queryGuards
766
+ }
767
+
768
+ /**
769
+ * Get action guards, optionally reloading them from the database.
770
+ *
771
+ * @async
772
+ * @method
773
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
774
+ * @returns {Promise<Array>} - A promise that resolves to an array of action guards.
775
+ */
776
+ getActionGuards = async (reread) => {
777
+ if (!reread) return this.actionGuards
675
778
 
676
- this.modelGuards = await this._fetchGuards('Model')
677
- return this.modelGuards
779
+ this.actionGuards = await this._fetchGuards('Action')
780
+ return this.actionGuards
678
781
  }
679
782
 
783
+ /**
784
+ * Get attribute guards, optionally reloading them from the database.
785
+ *
786
+ * @async
787
+ * @method
788
+ * @param {boolean} [reread] - Whether to reload the guards from the database.
789
+ * @returns {Promise<Array>} - A promise that resolves to an array of attribute guards.
790
+ */
680
791
  getAttribGuards = async (reread) => {
681
792
  if (!reread) return this.attribGuards
682
793
 
@@ -684,11 +795,25 @@ async function factory (pkgName) {
684
795
  return this.attribGuards
685
796
  }
686
797
 
798
+ /**
799
+ * Get all loaded model names, optionally returning them as value-text pairs.
800
+ *
801
+ * @method
802
+ * @param {boolean} [asValue] - Whether to return the model names as value-text pairs.
803
+ * @returns {Array} - An array of model names or value-text pairs.
804
+ */
687
805
  getModelNames = (asValue) => {
688
806
  const values = this.app.dobo.models.map(item => item.name).sort()
689
807
  return asValue ? values.map(item => ({ value: item, text: item })) : values
690
808
  }
691
809
 
810
+ /**
811
+ * Gather all paths to check for a request.
812
+ *
813
+ * @method
814
+ * @param {Object} req - The request object.
815
+ * @returns {Array} - An array of paths to check.
816
+ */
692
817
  pathsToCheck = (req) => {
693
818
  const { isSet } = this.app.lib.aneka
694
819
  const { uniq, without } = this.app.lib._
@@ -696,6 +821,15 @@ async function factory (pkgName) {
696
821
  return uniq(without(items, undefined, null))
697
822
  }
698
823
 
824
+ /**
825
+ * Check and set the iconset for a request.
826
+ *
827
+ * @async
828
+ * @method
829
+ * @param {Object} req - The request object.
830
+ * @param {Object} reply - The reply object.
831
+ * @returns {Promise<void>} - A promise that resolves when the iconset is checked and set.
832
+ */
699
833
  checkIconset = async (req, reply) => {
700
834
  const { get, isString } = this.app.lib._
701
835
  const mpa = this.app.waibuMpa
@@ -708,6 +842,15 @@ async function factory (pkgName) {
708
842
  req.iconset = req.iconset ?? 'default'
709
843
  }
710
844
 
845
+ /**
846
+ * Check and set the theme for a request.
847
+ *
848
+ * @async
849
+ * @method
850
+ * @param {Object} req - The request object.
851
+ * @param {Object} reply - The reply object.
852
+ * @returns {Promise<void>} - A promise that resolves when the theme is checked and set.
853
+ */
711
854
  checkTheme = async (req, reply) => {
712
855
  const { get, isString } = this.app.lib._
713
856
  const mpa = this.app.waibuMpa
@@ -720,6 +863,15 @@ async function factory (pkgName) {
720
863
  req.theme = req.theme ?? 'default'
721
864
  }
722
865
 
866
+ /**
867
+ * Check and set the team for a request.
868
+ *
869
+ * @async
870
+ * @method
871
+ * @param {Object} req - The request object.
872
+ * @param {Object} reply - The reply object.
873
+ * @returns {Promise<void>} - A promise that resolves when the team is checked and set.
874
+ */
723
875
  checkTeam = async (req, reply) => {
724
876
  const { includes } = this.app.lib.aneka
725
877
  const { outmatch } = this.app.lib
@@ -742,6 +894,16 @@ async function factory (pkgName) {
742
894
  // passed
743
895
  }
744
896
 
897
+ /**
898
+ * Check and set the user for a request.
899
+ *
900
+ * @async
901
+ * @method
902
+ * @param {Object} req - The request object.
903
+ * @param {Object} reply - The reply object.
904
+ * @param {Object} source - The source object.
905
+ * @returns {Promise<boolean|void>} - A promise that resolves to a boolean indicating the result of the check or void.
906
+ */
745
907
  checkUser = async (req, reply, source) => {
746
908
  const { merge, isEmpty, camelCase, get } = this.app.lib._
747
909
  const { routePath } = this.app.waibu
@@ -785,12 +947,11 @@ async function factory (pkgName) {
785
947
  await setUser()
786
948
  return secure
787
949
  }
788
- const silentOnError = this.config.auth[webApp].silentOnError ?? this.config.auth.common.silentOnError
950
+ const { silentOnError, methods } = this._getAuthSetting(null, webApp)
789
951
  const payload = silentOnError ? { noContent: true } : undefined
790
- const authMethods = this.config.auth[webApp].methods ?? []
791
- if (isEmpty(authMethods)) throw this.error('noAuthMethod', merge({ statusCode: 500 }, payload))
952
+ if (isEmpty(methods)) throw this.error('noAuthMethod', merge({ statusCode: 500 }, payload))
792
953
  let success
793
- for (const m of authMethods) {
954
+ for (const m of methods) {
794
955
  const handler = this[camelCase(`verify ${m}`)]
795
956
  if (!handler) throw this.error('invalidAuthMethod%s', m, merge({ statusCode: 500 }, payload))
796
957
  const check = await handler(req, reply, source, payload)
@@ -803,6 +964,15 @@ async function factory (pkgName) {
803
964
  return secure
804
965
  }
805
966
 
967
+ /**
968
+ * Check and set the Cross-site settings for a request.
969
+ *
970
+ * @async
971
+ * @method
972
+ * @param {Object} req - The request object.
973
+ * @param {Object} reply - The reply object.
974
+ * @returns {Promise<void>} - A promise that resolves when the XSite is checked and set.
975
+ */
806
976
  checkXSite = async (req, reply) => {
807
977
  const { get } = this.app.lib._
808
978
  if (!this.config.multiSite.enabled) return
@@ -811,6 +981,14 @@ async function factory (pkgName) {
811
981
  if (!get(req, 'user.isXSiteAdmin')) throw this.error('accessDenied', { statusCode: 403 })
812
982
  }
813
983
 
984
+ /**
985
+ * Check the route for a request.
986
+ *
987
+ * @async
988
+ * @method
989
+ * @param {Object} req - The request object.
990
+ * @returns {Promise<void>} - A promise that resolves when the route is checked.
991
+ */
814
992
  checkRoute = async (req) => {
815
993
  const { routePath } = this.app.waibu
816
994
  const { outmatch } = this.app.lib
@@ -821,6 +999,14 @@ async function factory (pkgName) {
821
999
  if (paths.find(isMatch)) throw this.error('_notFound')
822
1000
  }
823
1001
 
1002
+ /**
1003
+ * Parse namespace settings for a request.
1004
+ *
1005
+ * @method
1006
+ * @param {string} ns - The namespace.
1007
+ * @param {Object} setting - The setting object.
1008
+ * @param {Array} items - The items to parse.
1009
+ */
824
1010
  parseNsSettings = (ns, setting, items) => {
825
1011
  const { trim, set, isPlainObject, isArray, isEmpty, find } = this.app.lib._
826
1012
  const { parseObject, dayjs } = this.app.lib
@@ -848,13 +1034,712 @@ async function factory (pkgName) {
848
1034
  }
849
1035
  }
850
1036
 
851
- createNewSite = createNewSite
852
- removeSite = removeSite
853
- getSite = getSite
854
- getUserById = getUserById
1037
+ /**
1038
+ * Get all fixtures for the specified alias, replacing any occurrences of '{alias}' in the fixture data with the provided alias.
1039
+ *
1040
+ * @async
1041
+ * @method
1042
+ * @param {string} [alias] - The alias for the fixtures.
1043
+ * @returns {Promise<object>} - A promise that resolves to the fixtures data.
1044
+ */
1045
+ getAllFixtures = async (alias) => {
1046
+ const { readConfig } = this.app.bajo
1047
+ const { isEmpty, omit, kebabCase, isString } = this.app.lib._
1048
+ const { getModel } = this.app.dobo
1049
+ const { fastGlob } = this.app.lib
1050
+ const data = {}
1051
+
1052
+ function replaceAlias (alias, items) {
1053
+ for (const item of items) {
1054
+ for (const key in item) {
1055
+ const val = item[key]
1056
+ if (isString(val)) item[key] = val.replaceAll('{alias}', alias)
1057
+ }
1058
+ }
1059
+ }
1060
+
1061
+ const formats = this.app.configHandlers.map(item => item.ext.slice(1))
1062
+ const overrideBase = `${this.app.getPluginDataDir('sumba')}/create-new-site-fixtures/${alias}`
1063
+ const models = this.app.dobo.models.filter(m => {
1064
+ const prop = m.properties.find(p => p.name === 'siteId')
1065
+ return !!prop
1066
+ }).map(m => m.name)
1067
+ models.unshift('SumbaSite')
1068
+ const files = (await fastGlob(`${overrideBase}/*.{${formats.join(',')}}`)).map(file => {
1069
+ const ext = path.extname(file)
1070
+ return file.slice(0, file.length - ext.length)
1071
+ })
1072
+ for (const m of models) {
1073
+ const model = getModel(m)
1074
+ const file = `${overrideBase}/${kebabCase(m)}`
1075
+ let fixtures = (await model.loadFixtures({ collectItems: true, noLookup: true })) ?? []
1076
+ if (files.includes(file)) {
1077
+ const items = await readConfig(file, { defValue: [] })
1078
+ if (!isEmpty(items)) fixtures = items
1079
+ }
1080
+ if (!Array.isArray(fixtures)) fixtures = [fixtures]
1081
+ if (fixtures.length === 0) continue
1082
+ replaceAlias(alias, fixtures)
1083
+ if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
1084
+ const omitted = ['_attachments', 'siteId']
1085
+ for (const item of ['createdAt', 'updatedAt', 'immutable']) {
1086
+ const props = model.properties.filter(prop => prop.feature === ('dobo:' + item)).map(prop => prop.name)
1087
+ if (props.length > 0) omitted.push(...props)
1088
+ }
1089
+ for (const idx in fixtures) {
1090
+ fixtures[idx] = omit(fixtures[idx], omitted)
1091
+ }
1092
+ data[m] = m === 'SumbaSite' ? fixtures[0] : fixtures
1093
+ }
1094
+ return data
1095
+ }
855
1096
 
856
- getUserByToken = getUserByToken
857
- getUserByUsernamePassword = getUserByUsernamePassword
1097
+ /**
1098
+ * Create references for the specified site using the provided data, options, and verbosity settings.
1099
+ *
1100
+ * @async
1101
+ * @method
1102
+ * @param {object} site - The site object for which to create references.
1103
+ * @param {object} data - The data object containing fixtures for the site.
1104
+ * @param {object} options - Options to pass to the createRecord method.
1105
+ * @param {boolean} verbose - Whether to log verbose output.
1106
+ */
1107
+ createRefs = async (site, data, options, verbose) => {
1108
+ const { isString } = this.app.lib._
1109
+ const { getModel } = this.app.dobo
1110
+ for (const m in data) {
1111
+ if (m === 'SumbaSite') continue
1112
+ const mdl = getModel(m)
1113
+ const fixtures = data[m]
1114
+ for (const f of fixtures) {
1115
+ f.siteId = site.id + ''
1116
+ const lv = { siteId: f.siteId }
1117
+ for (const key in f) {
1118
+ const val = f[key]
1119
+ if (isString(val) && val.slice(0, 2) === '?:') f[key] = await mdl._simpleLookup(val.slice(2), lv, options)
1120
+ }
1121
+ await mdl.createRecord(f, { ...options, noFlash: true })
1122
+ }
1123
+ if (verbose) this.print.succeed('writingModel%s%s', mdl.name, fixtures.length)
1124
+ }
1125
+ if (verbose) this.print.succeed('populateRouteGuard')
1126
+ await this.populateRouteGuards([site])
1127
+ }
1128
+
1129
+ /**
1130
+ * Create a new site with the specified alias and optional hostname, using fixtures for initial data.
1131
+ *
1132
+ * @async
1133
+ * @method
1134
+ * @param {string} alias - The alias for the new site.
1135
+ * @param {string} [hostname] - The hostname for the new site.
1136
+ * @param {boolean} [verbose=false] - Whether to log verbose output.
1137
+ */
1138
+ createNewSite = async (alias, hostname, verbose) => {
1139
+ const { isEmpty } = this.app.lib._
1140
+ const { getModel } = this.app.dobo
1141
+
1142
+ if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
1143
+ let spin
1144
+ if (verbose) spin = this.print.spinner().start('processing...')
1145
+ const query = { $or: [{ alias }] }
1146
+ if (!isEmpty(hostname)) query.$or.push({ hostname })
1147
+ const model = getModel('SumbaSite')
1148
+ const site = await model.findOneRecord({ query })
1149
+ if (!isEmpty(site)) {
1150
+ if (verbose) spin.stop()
1151
+ throw this.error('aliasOrHostnameExists%s%s', alias, hostname ?? '')
1152
+ }
1153
+ // lets go
1154
+ const fixtures = await this.getAllFixtures(alias)
1155
+ if (verbose) spin.stop()
1156
+ fixtures.SumbaSite.alias = alias
1157
+ if (!isEmpty(hostname)) fixtures.SumbaSite.hostname = hostname
1158
+ await model.transaction(async (trx) => {
1159
+ const newSite = await model.createRecord(fixtures.SumbaSite, { trx, noHook: true })
1160
+ if (verbose) this.print.succeed('writingModel%s%s', model.name, 1)
1161
+ const options = { trx }
1162
+ await this.createRefs(newSite, fixtures, options, verbose)
1163
+ })
1164
+ if (verbose) this.print.info('done')
1165
+ }
1166
+
1167
+ /**
1168
+ * Remove references for the specified site using the provided options and verbosity settings.
1169
+ *
1170
+ * @async
1171
+ * @method
1172
+ * @param {object} site - The site object for which to remove references.
1173
+ * @param {object} options - Options to pass to the removeRecord method.
1174
+ * @param {boolean} verbose - Whether to log verbose output.
1175
+ */
1176
+ removeRefs = async (site, options, verbose) => {
1177
+ const { orderBy } = this.app.lib._
1178
+ const { getModel } = this.app.dobo
1179
+ const models = orderBy(this.app.dobo.models, ['buildLevel'], ['desc']).filter(m => {
1180
+ const prop = m.properties.find(p => p.name === 'siteId')
1181
+ return !!prop
1182
+ }).map(m => m.name)
1183
+ for (const m of models) {
1184
+ const mdl = getModel(m)
1185
+ const rows = await mdl.findAllRecord({ query: { siteId: site.id + '' } }, { ...options, dataOnly: true })
1186
+ const ids = rows.map(item => item.id)
1187
+ // TODO: backup
1188
+ if (ids.length === 0) continue
1189
+ for (const id of ids) {
1190
+ await mdl.removeRecord(id, { noReturn: true, ...options, noFlash: true })
1191
+ }
1192
+ if (verbose) this.print.succeed('removedFrom%s%s', mdl.name, ids.length)
1193
+ }
1194
+ }
1195
+
1196
+ /**
1197
+ * Remove a site with the specified alias, along with its references, using the provided verbosity settings.
1198
+ *
1199
+ * @async
1200
+ * @method
1201
+ * @param {string} alias - The alias of the site to remove.
1202
+ * @param {boolean} [verbose=false] - Whether to log verbose output.
1203
+ */
1204
+ removeSite = async (alias, verbose) => {
1205
+ const { isEmpty } = this.app.lib._
1206
+ const { getModel } = this.app.dobo
1207
+
1208
+ if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
1209
+ const model = getModel('SumbaSite')
1210
+ const query = { alias }
1211
+ const site = await model.findOneRecord({ query })
1212
+ if (isEmpty(site)) throw this.error('aliasNotFound%s', alias)
1213
+ await model.transaction(async (trx) => {
1214
+ const options = { trx, noHook: true }
1215
+ await this.removeRefs(site, options, verbose)
1216
+ await model.removeRecord(site.id, { noReturn: true, trx, noHook: true })
1217
+ if (verbose) this.print.succeed('removedFrom%s%s', model.name, 1)
1218
+ })
1219
+ if (verbose) this.print.info('done')
1220
+ }
1221
+
1222
+ /**
1223
+ * 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.
1224
+ *
1225
+ * @async
1226
+ * @method
1227
+ * @param {string|number} input - The input value, which can be either a hostname or an ID.
1228
+ * @param {boolean} [byId=false] - Whether to fetch the site by ID.
1229
+ * @returns {object} The site information.
1230
+ */
1231
+ getSite = async (input, byId = false) => {
1232
+ const { omit } = this.app.lib._
1233
+ const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
1234
+ const omitted = ['status']
1235
+
1236
+ let site = {}
1237
+ const mergeSetting = async (site) => {
1238
+ const { defaultsDeep, isSet } = this.app.lib.aneka
1239
+ const { get, filter } = this.app.lib._
1240
+ const defSetting = {}
1241
+ const nsSetting = {}
1242
+ const names = this.app.getAllNs()
1243
+ const query = {
1244
+ ns: { $in: names },
1245
+ siteId: site.id + ''
1246
+ }
1247
+ const all = await this.app.dobo.getModel('SumbaSiteSetting').findAllRecord({ query })
1248
+ for (const ns of names) {
1249
+ const item = get(this, `app.${ns}.config.siteSetting`)
1250
+ if (isSet(item)) defSetting[ns] = item
1251
+ const items = filter(all, { ns })
1252
+ this.parseNsSettings(ns, nsSetting, items)
1253
+ }
1254
+ site.setting = defaultsDeep({}, nsSetting, defSetting)
1255
+ // additional fields
1256
+ const country = await this.app.dobo.getModel('CdbCountry').getRecord(site.country, { noMagic: true })
1257
+ site.countryName = (country ?? {}).name ?? site.country
1258
+ }
1259
+
1260
+ if (!this.config.multiSite.enabled) {
1261
+ const filter = { query: { alias: 'default' } }
1262
+ const key = 'dobo|SumbaSite|getSite|default'
1263
+ if (getCache) {
1264
+ site = await getCache({ key })
1265
+ if (site) return site
1266
+ }
1267
+ const resp = await this.app.dobo.getModel('SumbaSite').findOneRecord(filter, { noHook: true })
1268
+ site = omit(resp, omitted)
1269
+ await mergeSetting(site)
1270
+ if (setCache) {
1271
+ await setCache({ key, value: site, ttl: this.config.cacheTtl.getSiteDur })
1272
+ }
1273
+ return site
1274
+ }
1275
+ let query
1276
+ if (byId) query = { id: input }
1277
+ else query = { hostname: input }
1278
+ const key = `dobo|SumbaSite|getSite|multiSite|${input}`
1279
+ if (getCache) {
1280
+ site = await getCache({ key })
1281
+ if (site) return JSON.parse(site)
1282
+ }
1283
+ let row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
1284
+ if (!row) {
1285
+ if (this.config.multiSite.catchAll) {
1286
+ query = { alias: this.config.multiSite.catchAll === true ? 'default' : this.config.multiSite.catchAll }
1287
+ row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
1288
+ }
1289
+ if (!row) throw this.error('unknownSite')
1290
+ }
1291
+ if (row.status !== 'ACTIVE') throw this.error('siteInactiveInfo')
1292
+ site = omit(row, omitted)
1293
+ await mergeSetting(site)
1294
+ if (setCache) {
1295
+ await setCache({ key, value: JSON.stringify(site), ttl: this.config.cacheTtl.getSiteDur })
1296
+ }
1297
+ return site
1298
+ }
1299
+
1300
+ /**
1301
+ * Merge team information into the user object.
1302
+ *
1303
+ * @async
1304
+ * @method
1305
+ * @param {object} user - The user object to merge team information into.
1306
+ * @param {object} req - The request object.
1307
+ */
1308
+ mergeTeam = async (user, req) => {
1309
+ const { map, pick } = this.app.lib._
1310
+ const { getModel } = this.app.dobo
1311
+ user.teams = []
1312
+ const query = { userId: user.id + '', siteId: user.siteId, status: 'ACTIVE' }
1313
+ let mdl = getModel('SumbaTeamUser')
1314
+ const userTeam = await mdl.findAllRecord({ query })
1315
+ if (userTeam.length === 0) return
1316
+ delete query.userId
1317
+ const idProp = mdl.getProperty('id')
1318
+ const $in = userTeam.map(item => ['integer', 'smallint'].includes(idProp.type) ? parseInt(item.teamId) : item.teamId)
1319
+ query.id = { $in }
1320
+ mdl = getModel('SumbaTeam')
1321
+ const teams = await mdl.findAllRecord({ query })
1322
+ if (teams.length > 0) {
1323
+ delete query.id
1324
+ delete query.status
1325
+ query.teamId = { $in: teams.map(t => t.id + '') }
1326
+ mdl = getModel('SumbaTeamSetting')
1327
+ const items = await mdl.findAllRecord({ query })
1328
+ for (const team of teams) {
1329
+ const names = map(items, 'ns')
1330
+ const item = pick(team, ['id', 'alias'])
1331
+ item.setting = {}
1332
+ for (const ns of names) {
1333
+ this.parseNsSettings(ns, item.setting, items.filter(s => s.teamId === (team.id + '')))
1334
+ }
1335
+ user.teams.push(item)
1336
+ }
1337
+ }
1338
+ user.isXSiteAdmin = this.config.xSiteAdmins.includes(`${req.site.alias}:${user.username}`)
1339
+ user.isAdmin = user.teams.some(t => t.alias === 'administrator')
1340
+ for (const field of this.unsafeUserFields) {
1341
+ delete user[field]
1342
+ }
1343
+ }
1344
+
1345
+ /**
1346
+ * Get a user by their ID.
1347
+ *
1348
+ * @async
1349
+ * @method
1350
+ * @param {string|number} id - The ID of the user to retrieve.
1351
+ * @param {object} req - The request object.
1352
+ * @returns {object|null} The user object if found, otherwise null.
1353
+ */
1354
+ getUserById = async (id, req) => {
1355
+ const { getModel } = this.app.dobo
1356
+ const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
1357
+ const key = `dobo|SumbaUser|getUserById|${id}`
1358
+ let user
1359
+ if (getCache) {
1360
+ user = await getCache({ key })
1361
+ if (user) return JSON.parse(user)
1362
+ }
1363
+ user = await getModel('SumbaUser').getRecord(id, { noHook: true, noDriverHook: true, throwNotFound: false, req })
1364
+ if (!user) return
1365
+ await this.mergeTeam(user, req)
1366
+ if (setCache) {
1367
+ await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByIdDur })
1368
+ }
1369
+ return user
1370
+ }
1371
+
1372
+ /**
1373
+ * Get a user by their token.
1374
+ *
1375
+ * @async
1376
+ * @method
1377
+ * @param {string} token - The token of the user to retrieve.
1378
+ * @param {object} req - The request object.
1379
+ * @returns {object|null} The user object if found, otherwise null.
1380
+ */
1381
+ getUserByToken = async (token, req) => {
1382
+ const { getModel } = this.app.dobo
1383
+ const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
1384
+ const key = `dobo|SumbaUser|getUserByToken|${token}`
1385
+ let user
1386
+ if (getCache) {
1387
+ user = await getCache({ key })
1388
+ if (user) return JSON.parse(user)
1389
+ }
1390
+ user = await getModel('SumbaUser').findOneRecord({ query: { token } }, { noHook: true, noDriverHook: true, throwNotFound: false, req })
1391
+ if (!user) return
1392
+ await this.mergeTeam(user, req)
1393
+ if (setCache) {
1394
+ await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByTokenDur })
1395
+ }
1396
+ return user
1397
+ }
1398
+
1399
+ getUserByUsernamePassword = async (username = '', password = '', req) => {
1400
+ const { getModel } = this.app.dobo
1401
+ const { importPkg } = this.app.bajo
1402
+ const model = getModel('SumbaUser')
1403
+ await model.validate({ username, password }, null, { partial: true, ns: ['sumba', 'dobo'], fields: ['username', 'password'] })
1404
+ const bcrypt = await importPkg('bajoExtra:bcrypt')
1405
+
1406
+ const query = { username, provider: 'local', siteId: req.site.id + '' }
1407
+ const user = await model.findOneRecord({ query }, { req, forceNoHidden: true, noHook: true, noDriverHook: true })
1408
+ if (!user) throw this.error('validationError', { details: [{ field: 'username', error: 'Unknown username' }], statusCode: 401 })
1409
+ if (user.status !== 'ACTIVE') throw this.error('validationError', { details: ['User is inactive or temporarily disabled'], statusCode: 401 })
1410
+ const verified = await bcrypt.compare(password, user.password)
1411
+ if (!verified) throw this.error('validationError', { details: [{ field: 'password', error: 'invalidPassword' }], statusCode: 401 })
1412
+ await this.mergeTeam(user, req)
1413
+ return user
1414
+ }
1415
+
1416
+ /**
1417
+ * Clear the cache for a specific site.
1418
+ *
1419
+ * @async
1420
+ * @method
1421
+ * @param {string|number} id - The ID of the site.
1422
+ * @param {object} result - The result object containing site data.
1423
+ */
1424
+ clearCacheSite = async (id, result) => {
1425
+ if (!this.app.bajoCache) return
1426
+ const { clear } = this.app.bajoCache ?? {}
1427
+ const { get } = this.app.lib._
1428
+ await clear({ key: 'dobo|SumbaSite|getSite|default' })
1429
+ await clear({ key: `dobo|SumbaSite|getSite|multiSite|${id}` })
1430
+ await clear({ key: `dobo|SumbaSite|getSite|multiSite|${get(result, 'data.hostname', get(result, 'oldData.hostname'))}` })
1431
+ }
1432
+
1433
+ /**
1434
+ * Clear the cache for a specific user.
1435
+ *
1436
+ * @async
1437
+ * @method
1438
+ * @param {string|number} id - The ID of the user.
1439
+ * @param {object} result - The result object containing user data.
1440
+ */
1441
+ clearCacheUser = async (id, result) => {
1442
+ if (!this.app.bajoCache) return
1443
+ const { clear } = this.app.bajoCache ?? {}
1444
+ const { get } = this.app.lib._
1445
+ const token = get(result, 'data.token', get(result, 'oldData.token', ''))
1446
+ await clear({ key: `dobo|SumbaUser|getUserById|${id}` })
1447
+ await clear({ key: `dobo|SumbaUser|getUserByToken|${token}` })
1448
+ }
1449
+
1450
+ /**
1451
+ * Filter model data based on settings.
1452
+ *
1453
+ * @method
1454
+ * @param {object} opts - The options object.
1455
+ * @param {object} opts.model - The model object.
1456
+ * @param {string} opts.field - The field to filter.
1457
+ * @param {object} [opts.options={}] - Additional options.
1458
+ * @returns {object} The filtered results and operation values.
1459
+ */
1460
+ filterModelFromSetting = (opts = {}) => {
1461
+ const { model, field, options = {} } = opts
1462
+ const { isEmpty, isArray, set } = this.app.lib._
1463
+ const { isSet } = this.app.lib.aneka
1464
+ const { req } = options
1465
+ const opValue = req.getSetting(`sumba:queryGuard.${field}`, {})
1466
+ const results = []
1467
+ const prop = model.getProperty(field)
1468
+ for (const op of ['in', 'nin', 'inOrEmpty']) {
1469
+ if (isEmpty(opValue[op]) || !isArray(opValue[op])) continue
1470
+ if (op === 'inOrEmpty') {
1471
+ const val = set({}, field, set({}, '$in', opValue[op]))
1472
+ const nl = set({}, field, { $eq: null })
1473
+ const item = { $or: [val, nl] }
1474
+ let v
1475
+ if (['string', 'text'].includes(prop.type)) v = ''
1476
+ else if (['integer', 'smallint', 'float', 'double'].includes(prop.type)) v = 0
1477
+ if (isSet(v)) {
1478
+ const bl = set({}, field, { $eq: v })
1479
+ item.$or.push(bl)
1480
+ }
1481
+ results.push(item)
1482
+ } else results.push(set({}, field, set({}, '$' + op, opValue[op])))
1483
+ }
1484
+ return { results, opValue }
1485
+ }
1486
+
1487
+ /**
1488
+ * Apply query guards to the provided query.
1489
+ *
1490
+ * @async
1491
+ * @method
1492
+ * @param {object} [opts={}] - The options object.
1493
+ * @param {object} opts.model - The model object.
1494
+ * @param {object} [opts.q={}] - The query object.
1495
+ * @param {array} [opts.teamIds=[]] - The team IDs.
1496
+ * @param {object} [opts.options={}] - Additional options.
1497
+ */
1498
+ runQueryGuard = async (opts = {}) => {
1499
+ const { model, q = {}, teamIds = [], options = {} } = opts
1500
+ const { set, orderBy, isEmpty, isArray } = this.app.lib._
1501
+ const { includes } = this.app.lib.aneka
1502
+ const { sanitizeByType } = this.app.dobo
1503
+ const { req } = options
1504
+ const results = []
1505
+
1506
+ const guards = await this.getQueryGuards()
1507
+ const fields = model.getNonVirtualProperties().map(prop => prop.name)
1508
+ const filterFn = item => {
1509
+ const bySiteId = item.siteId === req.site.id + ''
1510
+ const byModel = item.models.includes(model.name)
1511
+ const byFields = fields.includes(item.field)
1512
+ return bySiteId && byModel && byFields
1513
+ }
1514
+
1515
+ const rules = orderBy(guards.filter(filterFn), ['field'])
1516
+ for (const field of fields) {
1517
+ if (!model.getNonVirtualProperties(true).includes(field)) continue // or, should it throws exception instead?
1518
+ const inSetting = this.filterModelFromSetting({ model, field, options })
1519
+ const prop = model.getProperty(field)
1520
+ const items = rules.filter(item => item.field === field)
1521
+ for (const item of items) {
1522
+ let values = item.value.map(val => {
1523
+ return sanitizeByType(val, prop.type, { strict: true, inputFormat: 'string', model: model.name })
1524
+ })
1525
+ const op = item.condition.toLowerCase()
1526
+ if (['in', 'nin'].includes(op) && !isEmpty(inSetting.opValue[op]) && isArray(inSetting.opValue[op])) values = values.filter(val => inSetting.opValue[op].includes(val))
1527
+ if (isEmpty(values)) continue
1528
+ let value
1529
+ if (['in', 'nin'].includes(op)) value = set({}, '$' + op, values)
1530
+ else if (op === 'between') value = { $gte: values[0], $lte: values[1] }
1531
+ else value = set({}, '$' + op, values[0])
1532
+ const teamOk = item.allTeams ? true : (item.teamIds.length === 0 ? false : includes(item.teamIds, teamIds))
1533
+ if (!teamOk) throw this.error('_abortAction')
1534
+ results.push(set({}, field, value))
1535
+ }
1536
+ }
1537
+ q.$and.push(...results)
1538
+ }
1539
+
1540
+ /**
1541
+ * Apply attribute guards to the provided model.
1542
+ *
1543
+ * @async
1544
+ * @method
1545
+ * @param {object} [opts={}] - The options object.
1546
+ * @param {object} opts.model - The model object.
1547
+ * @param {array} [opts.teamIds=[]] - The team IDs.
1548
+ * @param {object} [opts.options={}] - Additional options.
1549
+ */
1550
+ runAttribGuard = async (opts = {}) => {
1551
+ const { model, teamIds = [], options = {} } = opts
1552
+ const { uniq } = this.app.lib._
1553
+ const { includes } = this.app.lib.aneka
1554
+ const { req } = options
1555
+ const results = []
1556
+
1557
+ const guards = await this.getAttribGuards()
1558
+ const filterFn = item => {
1559
+ const bySiteId = item.siteId === req.site.id + ''
1560
+ const byModel = item.models.includes(model.name)
1561
+ const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
1562
+ return bySiteId && byModel && byTeamId
1563
+ }
1564
+ guards.filter(filterFn).forEach(item => results.push(...item.hiddenFields))
1565
+ options.hidden = options.hidden ?? []
1566
+ options.hidden.push(...results)
1567
+ options.hidden = uniq(options.hidden)
1568
+ }
1569
+
1570
+ /**
1571
+ * Get the team IDs and aliases for the user in the request.
1572
+ *
1573
+ * @method
1574
+ * @param {object} req - The request object.
1575
+ * @returns {object} An object containing the team IDs and aliases.
1576
+ */
1577
+ getTeamIdsAndAliases = (req) => {
1578
+ const { get } = this.app.lib._
1579
+ const teams = get(req, 'user.teams', [])
1580
+ const teamIds = teams.map(team => team.id + '')
1581
+ const aliases = teams.map(team => team.alias)
1582
+ return { teamIds, aliases }
1583
+ }
1584
+
1585
+ /**
1586
+ * Rebuild the filter for the provided model.
1587
+ *
1588
+ * @async
1589
+ * @method
1590
+ * @param {object} model - The model object.
1591
+ * @param {object} [filter={}] - The filter object.
1592
+ * @param {object} [options={}] - Additional options.
1593
+ * @returns {Promise<object>} The rebuilt filter.
1594
+ */
1595
+ rebuildFilter = async (model, filter = {}, options = {}) => {
1596
+ const { isEmpty, get, keys } = this.app.lib._
1597
+ const { req } = options
1598
+ const allowEmpty = !get(this, `app.${model.ns}.config.sumba.noEmptyQuery`, []).includes(model.name)
1599
+ const hasSiteId = model.hasProperty('siteId')
1600
+ const hasUserId = model.hasProperty('userId')
1601
+ const hasTeamId = model.hasProperty('teamId')
1602
+ const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
1603
+ const q = { $and: [] }
1604
+
1605
+ filter.query = filter.query ?? {}
1606
+ if (!isEmpty(filter.query)) {
1607
+ if (filter.query.$and) q.$and.push(...filter.query.$and)
1608
+ else q.$and.push(filter.query)
1609
+ }
1610
+ if (req.routeOptions.config.xSite) {
1611
+ filter.query = q
1612
+ return
1613
+ }
1614
+ if (hasSiteId) q.$and.push({ siteId: req.site.id + '' })
1615
+ if (aliases.includes('administrator')) {
1616
+ if (get(req, 'site.alias') === 'default') {
1617
+ filter.query = q
1618
+ return
1619
+ }
1620
+ const fields = keys(req.getSetting('sumba:queryGuard', {}))
1621
+ const results = []
1622
+ for (const field of fields) {
1623
+ if (!model.hasProperty(field)) continue
1624
+ const inSetting = this.filterModelFromSetting({ model, field, options })
1625
+ if (inSetting.results.length > 0) results.push(...inSetting.results)
1626
+ }
1627
+ if (results.length > 0) q.$and.push(...results)
1628
+ filter.query = q
1629
+ return
1630
+ }
1631
+ if (isEmpty(req.user)) {
1632
+ if (q.$and.length === 0 && !allowEmpty) throw this.error('_emptyColumnQuery')
1633
+ filter.query = q
1634
+ return
1635
+ }
1636
+
1637
+ const condUserId = {
1638
+ $or: [
1639
+ { userId: req.user.id + '' },
1640
+ { userId: { $eq: null } }
1641
+ ]
1642
+ }
1643
+
1644
+ const condTeamId = {
1645
+ $or: [
1646
+ { teamId: { $in: teamIds } },
1647
+ { teamId: { $eq: null } }
1648
+ ]
1649
+ }
1650
+
1651
+ if (hasTeamId) {
1652
+ if (hasUserId) q.$and.push({ $or: [condTeamId, condUserId] })
1653
+ else q.$and.push(condTeamId)
1654
+ } else if (hasUserId) q.$and.push(condUserId)
1655
+
1656
+ await this.runQueryGuard({ model, q, teamIds, options, allowEmpty })
1657
+ await this.runAttribGuard({ model, teamIds, options })
1658
+ if (q.$and.length === 0 && !allowEmpty) throw this.error('_emptyColumnQuery')
1659
+ filter.query = q
1660
+ }
1661
+
1662
+ /**
1663
+ * Apply query hook to the provided model.
1664
+ *
1665
+ * @async
1666
+ * @method
1667
+ * @param {object} model - The model object.
1668
+ * @param {string|number} id - The ID of the model.
1669
+ * @param {object} options - Additional options.
1670
+ * @returns {object} The result of the model hook.
1671
+ */
1672
+ applyQueryHook = async (model, id, options = {}) => {
1673
+ const { isEmpty } = this.app.lib._
1674
+ const { req = {} } = options
1675
+ if (options.noAutoFilter || isEmpty(req) || isEmpty(req.site)) return
1676
+
1677
+ const filter = {}
1678
+ await this.rebuildFilter(model, filter, options)
1679
+ if (filter.query.$and) filter.query.$and.push({ id })
1680
+ else filter.query.id = id
1681
+ const row = await model.findOneRecord(filter, { count: false })
1682
+ if (!row) throw this.app.dobo.error('recordNotFound%s%s', id, this.name, { statusCode: 404 })
1683
+ }
1684
+
1685
+ /**
1686
+ * Apply action hook to the provided model.
1687
+ *
1688
+ * @async
1689
+ * @method
1690
+ * @param {object} [opts={}] - The options object.
1691
+ * @param {object} opts.model - The model object.
1692
+ * @param {array} [opts.teamIds=[]] - The team IDs.
1693
+ * @param {object} [opts.options={}] - Additional options.
1694
+ */
1695
+ applyActionHook = async (opts = {}) => {
1696
+ const { model, options = {} } = opts
1697
+ const { req } = options
1698
+ if (!req) return
1699
+ if (!req.site) return
1700
+
1701
+ let action
1702
+ if (['findOneRecord', 'findRecord', 'countRecord', 'getRecord'].includes(options.action)) action = 'READ'
1703
+ else if (['createRecord', 'bulkCreateRecord'].includes(options.action)) action = 'CREATE'
1704
+ else if (['updateRecord', 'upsertRecord'].includes(options.action)) action = 'UPDATE'
1705
+ else if (['removeRecord'].includes(options.action)) action = 'REMOVE'
1706
+ else if (['findAllRecord'].includes(options.action)) action = 'EXPORT'
1707
+ if (!action) return
1708
+
1709
+ const allowed = await this.isActionAllowed(action, model, req)
1710
+ if (!allowed) throw this.error('accessDenied', { statusCode: 403 })
1711
+ }
1712
+
1713
+ /**
1714
+ * 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.
1715
+ *
1716
+ * @async
1717
+ * @method
1718
+ * @param {string} action - The action to check. Available actions are: 'READ', 'CREATE', 'UPDATE', 'REMOVE' and 'EXPORT'.
1719
+ * @param {object} model - The model object.
1720
+ * @param {object} req - The request object.
1721
+ * @returns {Promise<boolean>} - Returns true if the action is allowed, otherwise false.
1722
+ */
1723
+ isActionAllowed = async (action, model, req) => {
1724
+ const { includes } = this.app.lib.aneka
1725
+ if (!req) return true
1726
+ if (!req.site) return true
1727
+ const guards = await this.getActionGuards()
1728
+ const { teamIds, aliases } = this.getTeamIdsAndAliases(req)
1729
+ if (aliases.includes('administrator')) return true
1730
+ const filterFn = item => {
1731
+ const bySiteId = item.siteId === req.site.id + ''
1732
+ const byModel = item.models.includes(model.name)
1733
+ const byTeamId = item.allTeams ? true : includes(item.teamIds, teamIds)
1734
+ return bySiteId && byModel && byTeamId
1735
+ }
1736
+ let denied = false
1737
+ for (const item of guards.filter(filterFn)) {
1738
+ if (item.value.includes('*')) continue
1739
+ if (!item.value.includes(action)) denied = true
1740
+ }
1741
+ return !denied
1742
+ }
858
1743
  }
859
1744
 
860
1745
  return Sumba