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/lib/config.js ADDED
@@ -0,0 +1,198 @@
1
+ export const defMultiSite = {
2
+ enabled: false,
3
+ catchAll: 'default'
4
+ }
5
+
6
+ /**
7
+ * Sumba configuration object
8
+ *
9
+ * @typedef {object} TConfig
10
+ * @type {object}
11
+ * @property {object} [config={}] - Configuration object
12
+ * @property {object} [config.multiSite={}] - Multi-site configuration object
13
+ * @property {boolean} [config.multiSite.enabled=false] - Whether multi-site is enabled or not. Default: false
14
+ * @property {string} [config.multiSite.catchAll='default'] - Which site alias to use as the catch-all. Default: 'default'
15
+ * @property {array} [config.xSiteAdmins=[]] - List of cross-site administrators. Format: "<siteAlias>:<username>"
16
+ * @property {object} [config.waibu={}] - Waibu configuration object
17
+ * @property {string} [config.waibu.prefix='site'] - Waibu prefix
18
+ * @property {string} [config.waibu.title='site'] - Waibu title
19
+ * @property {object} [config.waibuMpa={}] - Waibu MPA configuration object
20
+ * @property {object} [config.waibuMpa.auth={}] - Waibu MPA authentication configuration object
21
+ * @property {array} [config.waibuMpa.auth.methods=['session']] - Waibu MPA authentication methods. Default: ['session']
22
+ * @property {boolean} [config.waibuMpa.auth.silentOnError=false] - Whether to silently ignore authentication errors or not. Default: false
23
+ * @property {string} [config.waibuMpa.icon='globe'] - Waibu MPA icon. Default: 'globe'
24
+ * @property {object} [config.waibuMpa.redirect={}] - Waibu MPA route redirection
25
+ * @property {object} [config.waibuMpa.redirectSubRoute={}] - Waibu MPA sub-route redirection
26
+ * @property {object} [config.waibuRestApi={}] - Waibu REST API configuration object
27
+ * @property {object} [config.waibuRestApi.auth={}] - Waibu REST API authentication configuration object
28
+ * @property {array} [config.waibuRestApi.auth.methods=['basic', 'apiKey', 'jwt']] - Waibu REST API authentication methods. Default: ['basic', 'apiKey', 'jwt']
29
+ * @property {boolean} [config.waibuRestApi.auth.silentOnError=false] - Whether to silently ignore authentication errors or not. Default: false
30
+ * @property {object} [config.waibuStatic={}] - Waibu Static configuration object
31
+ * @property {object} [config.waibuStatic.auth={}] - Waibu Static authentication configuration object
32
+ * @property {array} [config.waibuStatic.auth.methods=['basic', 'apiKey', 'jwt']]
33
+ * @property {object} [config.waibuStatic.auth.basic={}] - Waibu Static Basic authentication configuration object
34
+ * @property {boolean} [config.waibuStatic.auth.basic.useUtf8=true] - Whether to use UTF-8 encoding for Basic authentication or not. Default: true
35
+ * @property {boolean} [config.waibuStatic.auth.basic.realm=true] - Whether to use realm for Basic authentication or not. Default: true
36
+ * @property {string} [config.waibuStatic.auth.basic.warningMessage='pleaseAuthenticate'] - Warning message for Basic authentication. Default: 'pleaseAuthenticate'
37
+ * @property {boolean} [config.waibuStatic.auth.silentOnError=false] - Whether to silently ignore authentication errors or not. Default: false
38
+ * @property {array} [config.waibuMpa.menuHandler=[]] - Waibu MPA menu handler
39
+ * @property {object} [config.waibuAdmin={}] - Waibu Admin configuration object
40
+ * @property {string} [config.waibuAdmin.menuHandler='sumba:adminMenu'] - Waibu Admin menu handler. Default: 'sumba:adminMenu'
41
+ * @property {boolean} [config.waibuAdmin.menuCollapsible=true] - Whether the Waibu Admin menu is collapsible or not. Default: true
42
+ * @property {object} [config.auth={}] - Authentication configuration object
43
+ * @property {object} [config.auth.apiKey={}] - API Key authentication configuration object
44
+ * @property {string} [config.auth.apiKey.type='Bearer'] - API Key authentication type. Default: 'Bearer'
45
+ * @property {string} [config.auth.apiKey.qsKey='apiKey'] - API Key authentication query string key. Default: 'apiKey'
46
+ * @property {string} [config.auth.apiKey.headerKey='X-Auth-ApiKey'] - API Key authentication header key. Default: 'X-Auth-ApiKey'
47
+ * @property {string} [config.auth.apiKey.algo='sha256'] - API Key authentication hashing algorithm. Default: 'sha256'
48
+ * @property {object} [config.auth.basic={}] - Basic authentication configuration object
49
+ * @property {object} [config.auth.jwt={}] - JWT authentication configuration object
50
+ * @property {string} [config.auth.jwt.type='Bearer'] - JWT authentication type. Default: 'Bearer'
51
+ * @property {string} [config.auth.jwt.qsKey='token'] - JWT authentication query string key. Default: 'token'
52
+ * @property {string} [config.auth.jwt.headerKey='X-Auth-Jwt'] - JWT authentication header key. Default: 'X-Auth-Jwt'
53
+ * @property {string} [config.auth.jwt.secret] - JWT authentication secret. Default: hard coded value, should be changed in production
54
+ * @property {string} [config.auth.jwt.expiresInDur='7d'] - JWT authentication token expiration duration. Default: '7d'
55
+ * @property {object} [config.redirect={}] - Redirection configuration object
56
+ */
57
+
58
+ async function configFactory () {
59
+ const { cloneDeep } = this.app.lib._
60
+ const config = {
61
+ multiSite: cloneDeep(defMultiSite),
62
+ xSiteAdmins: [], // format: "<siteAlias>:<username>"
63
+ waibu: {
64
+ title: 'site',
65
+ prefix: 'site'
66
+ },
67
+ dobo: {
68
+ model: {}
69
+ },
70
+ waibuRestApi: {
71
+ auth: {
72
+ methods: ['basic', 'apiKey', 'jwt'],
73
+ silentOnError: false
74
+ }
75
+ },
76
+ waibuStatic: {
77
+ auth: {
78
+ methods: ['basic', 'apiKey', 'jwt'],
79
+ basic: {
80
+ useUtf8: true,
81
+ realm: true,
82
+ warningMessage: 'pleaseAuthenticate'
83
+ },
84
+ silentOnError: false
85
+ }
86
+ },
87
+ waibuMpa: {
88
+ icon: 'globe',
89
+ auth: {
90
+ methods: ['session'],
91
+ silentOnError: false
92
+ },
93
+ redirect: {
94
+ '/': 'sumba:/your-stuff/profile',
95
+ '/your-stuff': 'sumba:/your-stuff/profile',
96
+ '/info': 'sumba:/info/about-us',
97
+ '/user': 'sumba:/your-stuff/profile',
98
+ '/db/export': 'sumba:/db/export/list',
99
+ '/help': 'sumba:/help/contact-form',
100
+ '/help/trouble-tickets': 'sumba:/help/trouble-tickets/list'
101
+ },
102
+ redirectSubRoute: {
103
+ waibuAdmin: {
104
+ '/': 'waibuAdmin:/site/site',
105
+ '/x': 'waibuAdmin:/site/x/site/list',
106
+ '/x/*': 'waibuAdmin:/site/x/{2}/list',
107
+ '/*': 'waibuAdmin:/site/{1}/list'
108
+ }
109
+ },
110
+ menuHandler: [{
111
+ title: 'account',
112
+ icon: 'person',
113
+ level: 9998,
114
+ children: [
115
+ // anonymous only
116
+ { title: 'signin', href: 'sumba:/signin', visible: 'anon' },
117
+ { title: 'forgotPassword', href: 'sumba:/user/forgot-password', visible: 'anon' },
118
+ { title: 'newUserSignup', href: 'sumba:/user/signup', visible: 'anon' },
119
+ { title: '-', visible: 'anon' },
120
+ { title: 'activation', href: 'sumba:/user/activation', visible: 'anon' },
121
+ // authenticated only
122
+ { title: 'yourProfile', href: 'sumba:/your-stuff/profile', visible: 'auth' },
123
+ { title: 'changePassword', href: 'sumba:/your-stuff/change-password', visible: 'auth' },
124
+ { title: 'downloadList', href: 'sumba:/your-stuff/download/list', visible: 'auth' },
125
+ { title: '-', visible: 'auth' },
126
+ { title: 'signout', href: 'sumba:/signout', visible: 'auth' }
127
+ ]
128
+ }, {
129
+ title: 'help',
130
+ icon: 'signInfo',
131
+ level: 9999,
132
+ children: [
133
+ { title: 'contactForm', href: 'sumba:/help/contact-form' },
134
+ { title: 'troubleTickets', href: 'sumba:/help/trouble-tickets', visible: 'auth' },
135
+ { title: '-' },
136
+ { title: 'cookiePolicy', href: 'sumba:/info/cookie-policy' },
137
+ { title: 'privacy', href: 'sumba:/info/privacy' },
138
+ { title: 'termsConditions', href: 'sumba:/info/terms-conditions' }
139
+ ]
140
+ }]
141
+ },
142
+ waibuAdmin: {
143
+ menuHandler: 'sumba:adminMenu',
144
+ menuCollapsible: true,
145
+ modelDisabled: 'all'
146
+ },
147
+ auth: {
148
+ apiKey: {
149
+ type: 'Bearer',
150
+ qsKey: 'apiKey',
151
+ headerKey: 'X-Auth-ApiKey',
152
+ algo: 'sha256' // changing this require each and every user to reset their apiKey
153
+ },
154
+ basic: {
155
+ },
156
+ jwt: {
157
+ type: 'Bearer',
158
+ qsKey: 'token',
159
+ headerKey: 'X-Auth-Jwt',
160
+ secret: '668de9cf57316c7dbf52f7ff7611c299',
161
+ expiresInDur: '7d'
162
+ }
163
+ },
164
+ redirect: {
165
+ signin: 'sumba:/signin',
166
+ afterSignin: '/',
167
+ signout: 'sumba:/signout',
168
+ afterSignout: '/'
169
+ },
170
+ siteSetting: {
171
+ forgotPasswordExpDur: '5m',
172
+ timeZone: 'UTC',
173
+ userPassword: {
174
+ minUpperCase: 1,
175
+ minLowerCase: 1,
176
+ minSpecialChar: 1,
177
+ minNumeric: 1,
178
+ noWhitespace: false,
179
+ latinOnlyChars: false,
180
+ pattern: {
181
+ lowerCase: 'abcdefghijklmnopqrstuvwxyz',
182
+ upperCase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
183
+ specialChar: '!@#$%*',
184
+ numeric: '0123456789'
185
+ }
186
+ }
187
+ },
188
+ cacheTtl: {
189
+ getSiteDur: '1m',
190
+ getUserByIdDur: '1m',
191
+ getUserByTokenDur: '1m'
192
+ }
193
+ }
194
+
195
+ return config
196
+ }
197
+
198
+ export default configFactory
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @typedef {object} TTokenData
3
+ * @type {object}
4
+ * @property {object} data - The token data object
5
+ * @property {string} data.token - The token string
6
+ * @property {string} data.expiresAt - The expiration date of the token
7
+ * @property {boolean} success - Indicates if the operation was successful
8
+ * @property {number} statusCode - The HTTP status code of the response
9
+ */
10
+ export const data = {
11
+ data: {
12
+ type: 'object',
13
+ properties: {
14
+ token: { type: 'string' },
15
+ expiresAt: { type: 'string' }
16
+ }
17
+ },
18
+ success: {
19
+ type: 'boolean',
20
+ default: true
21
+ },
22
+ statusCode: {
23
+ type: 'integer',
24
+ default: 200
25
+ }
26
+ }
27
+
28
+ /**
29
+ * @typedef {object} TTokenBody
30
+ * @type {object}
31
+ * @property {string} username - The username of the user
32
+ * @property {string} password - The password of the user
33
+ */
34
+ export const body = {
35
+ type: 'object',
36
+ properties: {
37
+ username: {
38
+ type: 'string'
39
+ },
40
+ password: {
41
+ type: 'string'
42
+ }
43
+ }
44
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sumba",
3
- "version": "2.34.4",
3
+ "version": "2.36.0",
4
4
  "description": "Biz Suite for Bajo Framework",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -11,7 +11,11 @@
11
11
  "bajo": {
12
12
  "type": "plugin",
13
13
  "alias": "sumba",
14
- "dependencies": ["bajo-extra", "bajo-common-db", "dobo"]
14
+ "dependencies": [
15
+ "bajo-extra",
16
+ "bajo-common-db",
17
+ "dobo"
18
+ ]
15
19
  },
16
20
  "repository": {
17
21
  "type": "git",
@@ -36,7 +40,9 @@
36
40
  "slug": "^11.0.1"
37
41
  },
38
42
  "devDependencies": {
43
+ "chai": "^6.2.2",
39
44
  "clean-jsdoc-theme": "^4.3.0",
40
- "jsdoc-plugin-intersection": "^1.0.4"
45
+ "jsdoc-plugin-intersection": "^1.0.4",
46
+ "mocha": "^11.7.6"
41
47
  }
42
48
  }
package/wiki/CHANGES.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changes
2
2
 
3
+ ## 2026-06-29
4
+
5
+ - [2.36.0] Move ```config``` object to dedicated file ```lib/config.js```
6
+ - [2.36.0] Changes in ```_getAuthSetting()```
7
+ - [2.36.0] Bug fix in ```runQueryGuard()```
8
+
9
+ ## 2026-06-29
10
+
11
+ - [2.35.0] Add ```SumbaActionGuard``` model & its helpers
12
+ - [2.35.0] Restructure admin menu
13
+ - [2.35.0] Documentations overhaul
14
+
3
15
  ## 2026-06-20
4
16
 
5
17
  - [2.34.3] Bug fix in ```checkTeam()```
@@ -1,106 +0,0 @@
1
- import path from 'path'
2
-
3
- export async function getAllFixtures (alias) {
4
- const { readConfig } = this.app.bajo
5
- const { isEmpty, omit, kebabCase, isString } = this.app.lib._
6
- const { getModel } = this.app.dobo
7
- const { fastGlob } = this.app.lib
8
- const data = {}
9
-
10
- function replaceAlias (alias, items) {
11
- for (const item of items) {
12
- for (const key in item) {
13
- const val = item[key]
14
- if (isString(val)) item[key] = val.replaceAll('{alias}', alias)
15
- }
16
- }
17
- }
18
-
19
- const formats = this.app.configHandlers.map(item => item.ext.slice(1))
20
- const overrideBase = `${this.app.getPluginDataDir('sumba')}/create-new-site-fixtures/${alias}`
21
- const models = this.app.dobo.models.filter(m => {
22
- const prop = m.properties.find(p => p.name === 'siteId')
23
- return !!prop
24
- }).map(m => m.name)
25
- models.unshift('SumbaSite')
26
- const files = (await fastGlob(`${overrideBase}/*.{${formats.join(',')}}`)).map(file => {
27
- const ext = path.extname(file)
28
- return file.slice(0, file.length - ext.length)
29
- })
30
- for (const m of models) {
31
- const model = getModel(m)
32
- const file = `${overrideBase}/${kebabCase(m)}`
33
- let fixtures = (await model.loadFixtures({ collectItems: true, noLookup: true })) ?? []
34
- if (files.includes(file)) {
35
- const items = await readConfig(file, { defValue: [] })
36
- if (!isEmpty(items)) fixtures = items
37
- }
38
- if (!Array.isArray(fixtures)) fixtures = [fixtures]
39
- if (fixtures.length === 0) continue
40
- replaceAlias(alias, fixtures)
41
- if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
42
- const omitted = ['_attachments', 'siteId']
43
- for (const item of ['createdAt', 'updatedAt', 'immutable']) {
44
- const props = model.properties.filter(prop => prop.feature === ('dobo:' + item)).map(prop => prop.name)
45
- if (props.length > 0) omitted.push(...props)
46
- }
47
- for (const idx in fixtures) {
48
- fixtures[idx] = omit(fixtures[idx], omitted)
49
- }
50
- data[m] = m === 'SumbaSite' ? fixtures[0] : fixtures
51
- }
52
- return data
53
- }
54
-
55
- export async function createRefs (site, data, options, verbose) {
56
- const { isString } = this.app.lib._
57
- const { getModel } = this.app.dobo
58
- for (const m in data) {
59
- if (m === 'SumbaSite') continue
60
- const mdl = getModel(m)
61
- const fixtures = data[m]
62
- for (const f of fixtures) {
63
- f.siteId = site.id + ''
64
- const lv = { siteId: f.siteId }
65
- for (const key in f) {
66
- const val = f[key]
67
- if (isString(val) && val.slice(0, 2) === '?:') f[key] = await mdl._simpleLookup(val.slice(2), lv, options)
68
- }
69
- await mdl.createRecord(f, { ...options, noFlash: true })
70
- }
71
- if (verbose) this.print.succeed('writingModel%s%s', mdl.name, fixtures.length)
72
- }
73
- if (verbose) this.print.succeed('populateRouteGuard')
74
- await this.populateRouteGuards([site])
75
- }
76
-
77
- async function createNewSite (alias, hostname, verbose) {
78
- const { isEmpty } = this.app.lib._
79
- const { getModel } = this.app.dobo
80
-
81
- if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
82
- let spin
83
- if (verbose) spin = this.print.spinner().start('processing...')
84
- const query = { $or: [{ alias }] }
85
- if (!isEmpty(hostname)) query.$or.push({ hostname })
86
- const model = getModel('SumbaSite')
87
- const site = await model.findOneRecord({ query })
88
- if (!isEmpty(site)) {
89
- if (verbose) spin.stop()
90
- throw this.error('aliasOrHOstnameExists%s%s', alias, hostname ?? '')
91
- }
92
- // lets go
93
- const fixtures = await getAllFixtures.call(this, alias)
94
- if (verbose) spin.stop()
95
- fixtures.SumbaSite.alias = alias
96
- if (!isEmpty(hostname)) fixtures.SumbaSite.hostname = hostname
97
- await model.transaction(async (trx) => {
98
- const newSite = await model.createRecord(fixtures.SumbaSite, { trx, noHook: true })
99
- if (verbose) this.print.succeed('writingModel%s%s', model.name, 1)
100
- const options = { trx }
101
- await createRefs.call(this, newSite, fixtures, options, verbose)
102
- })
103
- if (verbose) this.print.info('done')
104
- }
105
-
106
- export default createNewSite
package/lib/get-site.js DELETED
@@ -1,70 +0,0 @@
1
- async function getSite (input, byId = false) {
2
- const { omit } = this.app.lib._
3
- const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
4
- const omitted = ['status']
5
-
6
- let site = {}
7
- const mergeSetting = async (site) => {
8
- const { defaultsDeep, isSet } = this.app.lib.aneka
9
- const { get, filter } = this.app.lib._
10
- const defSetting = {}
11
- const nsSetting = {}
12
- const names = this.app.getAllNs()
13
- const query = {
14
- ns: { $in: names },
15
- siteId: site.id + ''
16
- }
17
- const all = await this.app.dobo.getModel('SumbaSiteSetting').findAllRecord({ query })
18
- for (const ns of names) {
19
- const item = get(this, `app.${ns}.config.siteSetting`)
20
- if (isSet(item)) defSetting[ns] = item
21
- const items = filter(all, { ns })
22
- this.parseNsSettings(ns, nsSetting, items)
23
- }
24
- site.setting = defaultsDeep({}, nsSetting, defSetting)
25
- // additional fields
26
- const country = await this.app.dobo.getModel('CdbCountry').getRecord(site.country, { noMagic: true })
27
- site.countryName = (country ?? {}).name ?? site.country
28
- }
29
-
30
- if (!this.config.multiSite.enabled) {
31
- const filter = { query: { alias: 'default' } }
32
- const key = 'dobo|SumbaSite|getSite|default'
33
- if (getCache) {
34
- site = await getCache({ key })
35
- if (site) return site
36
- }
37
- const resp = await this.app.dobo.getModel('SumbaSite').findOneRecord(filter, { noHook: true })
38
- site = omit(resp, omitted)
39
- await mergeSetting(site)
40
- if (setCache) {
41
- await setCache({ key, value: site, ttl: this.config.cacheTtl.getSiteDur })
42
- }
43
- return site
44
- }
45
- let query
46
- if (byId) query = { id: input }
47
- else query = { hostname: input }
48
- const key = `dobo|SumbaSite|getSite|multiSite|${input}`
49
- if (getCache) {
50
- site = await getCache({ key })
51
- if (site) return JSON.parse(site)
52
- }
53
- let row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
54
- if (!row) {
55
- if (this.config.multiSite.catchAll) {
56
- query = { alias: this.config.multiSite.catchAll === true ? 'default' : this.config.multiSite.catchAll }
57
- row = await this.app.dobo.getModel('SumbaSite').findOneRecord({ query }, { noHook: true })
58
- }
59
- if (!row) throw this.error('unknownSite')
60
- }
61
- if (row.status !== 'ACTIVE') throw this.error('siteInactiveInfo')
62
- site = omit(row, omitted)
63
- await mergeSetting(site)
64
- if (setCache) {
65
- await setCache({ key, value: JSON.stringify(site), ttl: this.config.cacheTtl.getSiteDur })
66
- }
67
- return site
68
- }
69
-
70
- export default getSite
package/lib/get-user.js DELETED
@@ -1,89 +0,0 @@
1
- export async function mergeTeam (user, req) {
2
- const { map, pick } = this.app.lib._
3
- const { getModel } = this.app.dobo
4
- user.teams = []
5
- const query = { userId: user.id + '', siteId: user.siteId, status: 'ACTIVE' }
6
- let mdl = getModel('SumbaTeamUser')
7
- const userTeam = await mdl.findAllRecord({ query })
8
- if (userTeam.length === 0) return
9
- delete query.userId
10
- const idProp = mdl.getProperty('id')
11
- const $in = userTeam.map(item => ['integer', 'smallint'].includes(idProp.type) ? parseInt(item.teamId) : item.teamId)
12
- query.id = { $in }
13
- mdl = getModel('SumbaTeam')
14
- const teams = await mdl.findAllRecord({ query })
15
- if (teams.length > 0) {
16
- delete query.id
17
- delete query.status
18
- query.teamId = { $in: teams.map(t => t.id + '') }
19
- mdl = getModel('SumbaTeamSetting')
20
- const items = await mdl.findAllRecord({ query })
21
- for (const team of teams) {
22
- const names = map(items, 'ns')
23
- const item = pick(team, ['id', 'alias'])
24
- item.setting = {}
25
- for (const ns of names) {
26
- this.parseNsSettings(ns, item.setting, items.filter(s => s.teamId === (team.id + '')))
27
- }
28
- user.teams.push(item)
29
- }
30
- }
31
- user.isXSiteAdmin = this.config.xSiteAdmins.includes(`${req.site.alias}:${user.username}`)
32
- user.isAdmin = user.teams.some(t => t.alias === 'administrator')
33
- for (const field of this.unsafeUserFields) {
34
- delete user[field]
35
- }
36
- }
37
-
38
- export async function getUserById (id, req) {
39
- const { getModel } = this.app.dobo
40
- const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
41
- const key = `dobo|SumbaUser|getUserById|${id}`
42
- let user
43
- if (getCache) {
44
- user = await getCache({ key })
45
- if (user) return JSON.parse(user)
46
- }
47
- user = await getModel('SumbaUser').getRecord(id, { noHook: true, noDriverHook: true, throwNotFound: false, req })
48
- if (!user) return
49
- await mergeTeam.call(this, user, req)
50
- if (setCache) {
51
- await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByIdDur })
52
- }
53
- return user
54
- }
55
-
56
- export async function getUserByToken (token, req) {
57
- const { getModel } = this.app.dobo
58
- const { set: setCache, get: getCache } = this.app.bajoCache ?? {}
59
- const key = `dobo|SumbaUser|getUserByToken|${token}`
60
- let user
61
- if (getCache) {
62
- user = await getCache({ key })
63
- if (user) return JSON.parse(user)
64
- }
65
- user = await getModel('SumbaUser').findOneRecord({ query: { token } }, { noHook: true, noDriverHook: true, throwNotFound: false, req })
66
- if (!user) return
67
- await mergeTeam.call(this, user, req)
68
- if (setCache) {
69
- await setCache({ key, value: JSON.stringify(user), ttl: this.config.cacheTtl.getUserByTokenDur })
70
- }
71
- return user
72
- }
73
-
74
- export async function getUserByUsernamePassword (username = '', password = '', req) {
75
- const { getModel } = this.app.dobo
76
- const { importPkg } = this.app.bajo
77
- const model = getModel('SumbaUser')
78
- await model.validate({ username, password }, null, { partial: true, ns: ['sumba', 'dobo'], fields: ['username', 'password'] })
79
- const bcrypt = await importPkg('bajoExtra:bcrypt')
80
-
81
- const query = { username, provider: 'local', siteId: req.site.id + '' }
82
- const user = await model.findOneRecord({ query }, { req, forceNoHidden: true, noHook: true, noDriverHook: true })
83
- if (!user) throw this.error('validationError', { details: [{ field: 'username', error: 'Unknown username' }], statusCode: 401 })
84
- if (user.status !== 'ACTIVE') throw this.error('validationError', { details: ['User is inactive or temporarily disabled'], statusCode: 401 })
85
- const verified = await bcrypt.compare(password, user.password)
86
- if (!verified) throw this.error('validationError', { details: [{ field: 'password', error: 'invalidPassword' }], statusCode: 401 })
87
- await mergeTeam.call(this, user, req)
88
- return user
89
- }
@@ -1,39 +0,0 @@
1
- export async function removeRefs (site, options, verbose) {
2
- const { orderBy } = this.app.lib._
3
- const { getModel } = this.app.dobo
4
- const models = orderBy(this.app.dobo.models, ['buildLevel'], ['desc']).filter(m => {
5
- const prop = m.properties.find(p => p.name === 'siteId')
6
- return !!prop
7
- }).map(m => m.name)
8
- for (const m of models) {
9
- const mdl = getModel(m)
10
- const rows = await mdl.findAllRecord({ query: { siteId: site.id + '' } }, { ...options, dataOnly: true })
11
- const ids = rows.map(item => item.id)
12
- // TODO: backup
13
- if (ids.length === 0) continue
14
- for (const id of ids) {
15
- await mdl.removeRecord(id, { noReturn: true, ...options, noFlash: true })
16
- }
17
- if (verbose) this.print.succeed('removedFrom%s%s', mdl.name, ids.length)
18
- }
19
- }
20
-
21
- async function removeSite (alias, verbose) {
22
- const { isEmpty } = this.app.lib._
23
- const { getModel } = this.app.dobo
24
-
25
- if (isEmpty(alias)) throw this.error('aliasRequired%s', alias)
26
- const model = getModel('SumbaSite')
27
- const query = { alias }
28
- const site = await model.findOneRecord({ query })
29
- if (isEmpty(site)) throw this.error('aliasNotFound%s', alias)
30
- await model.transaction(async (trx) => {
31
- const options = { trx, noHook: true }
32
- await removeRefs.call(this, site, options, verbose)
33
- await model.removeRecord(site.id, { noReturn: true, trx, noHook: true })
34
- if (verbose) this.print.succeed('removedFrom%s%s', model.name, 1)
35
- })
36
- if (verbose) this.print.info('done')
37
- }
38
-
39
- export default removeSite
@@ -1,29 +0,0 @@
1
- export const data = {
2
- data: {
3
- type: 'object',
4
- properties: {
5
- token: { type: 'string' },
6
- expiresAt: { type: 'string' }
7
- }
8
- },
9
- success: {
10
- type: 'boolean',
11
- default: true
12
- },
13
- statusCode: {
14
- type: 'integer',
15
- default: 200
16
- }
17
- }
18
-
19
- export const body = {
20
- type: 'object',
21
- properties: {
22
- username: {
23
- type: 'string'
24
- },
25
- password: {
26
- type: 'string'
27
- }
28
- }
29
- }