-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
416 lines (377 loc) · 10.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*!
* Oloma Dev.
*
* [olobase] <https://github.com/olomadev/olobase>
*
* Copyright (c) 2022-2024, Oloma Software.
*
* https://oloma.dev/end-user-license-agreement
*/
import upperFirst from "lodash/upperFirst"
import lowerCase from "lodash/lowerCase"
import isEmpty from "lodash/isEmpty"
import cookies from "olobase-admin/src/utils/cookies"
import messages from "olobase-admin/src/store/messages"
import auth from "olobase-admin/src/store/auth"
import guest from "olobase-admin/src/store/guest"
import api from "olobase-admin/src/store/api"
import storeResource from "olobase-admin/src/store/resource"
import routeResource from "olobase-admin/src/router/resource"
export default class Olobase {
constructor(env) {
this.env = env
}
setOptions({
app,
router,
resources,
store,
i18n,
downloadUrl,
readFileUrl,
title,
routes,
locales,
authProvider,
dataProvider,
config,
canAction,
http
}) {
if (typeof this.env.VITE_SUPPORTED_LOCALES == "undefined") {
throw new Error("Oloma configuration error: .env.local or .env.prod environment file missed in your project !");
}
const supportedLocales = this.env.VITE_SUPPORTED_LOCALES;
let translations = [];
if (supportedLocales
&& Object.prototype.toString.call(supportedLocales) === "[object String]")
{
const split = supportedLocales.split(",");
if (Array.isArray(split)) {
translations = split;
}
}
this.cookieKey = JSON.parse(this.env.VITE_COOKIE);
/**
* Options properties
*/
this.app = app
this.router = router
this.store = store
this.i18n = i18n
this.apiUrl = this.env.VITE_API_URL
this.downloadUrl = downloadUrl
this.readFileUrl = readFileUrl
this.title = title
this.routes = routes
this.locales = locales
this.translations = translations
this.authProvider = authProvider
this.dataProvider = dataProvider
this.config = config || {}
this.canAction = canAction
this.http = http
this.saved = false // global form saved object
if (resources) {
this.setResources(resources);
}
}
setResources(resources) {
this.resources = resources
.map((r) => {
return typeof r === "string"
? {
name: r,
}
: r;
})
.map((r) => {
/**
* Get valid routes
*/
let routes = ["list", "show", "create", "edit"].filter((name) => {
return !r.routes || r.routes.includes(name)
})
/**
* Get valid actions
*/
let actions = ["list", "show", "create", "edit", "delete"].filter(
(name) => {
if ((r.actions || []).length) {
return r.actions.includes(name)
}
if ((r.except || []).length) {
return !r.except.includes(name)
}
return true
}
);
let nameKey = `resources.${r.name}.name`
let getName = (count) =>
this.i18n.global.te(nameKey)
? this.i18n.global.tc(nameKey, count)
: upperFirst(lowerCase(r.name))
return {
...r,
icon: r.icon || "mdi-view-grid",
routes,
actions,
getName,
singularName: getName(1),
pluralName: getName(10),
getTitle: (action, item = null) => {
let titleKey = `resources.${r.name}.titles.${action}`
if (item) {
return this.i18n.global.te(titleKey)
? this.i18n.global.t(titleKey, item.raw)
: this.i18n.global.t(`va.pages.${action}`);
}
return this.i18n.global.te(titleKey)
? this.i18n.global.t(titleKey)
: this.i18n.global.t(`va.pages.${action}`, {
resource: getName(action === "list" ? 10 : 1).toLowerCase(),
})
},
canAction: async (action) => {
/**
* Test if action exist for this resource
*/
if (!actions.includes(action)) {
return false;
}
let canAction = this.canAction
/**
* Use custom action if defined
*/
if (canAction) {
let result = canAction({
resource: r,
action,
can: await this.can,
})
/**
* If valid boolean return this value instead of default next behavior
*/
if (typeof result === "boolean") {
return result
}
}
/**
* OK if no permissions set
*/
if (!r.permissions) {
return true
}
/**
* Get permissions for asked action
*/
let permissions = (r.permissions || [])
.filter((p) => {
return typeof p === "string" || p.actions.includes(action);
})
.map((p) => {
return typeof p === "string" ? p : p.name;
})
let result = permissions.length && await this.can(permissions)
// console.error(result)
// Test if current user can access
return result
},
}
})
} // end setResource
/**
* Init to admin properties
*/
init() {
/**
* Auth store & api dispatcher module injection
*/
this.store.registerModule("messages", messages);
this.store.registerModule("api", api);
this.store.registerModule(
"auth",
this.authProvider ? auth(this.authProvider, this.router) : guest
)
/**
* Add API resources modules dynamically
*/
if (this.dataProvider) {
this.resources.forEach((resource) =>
this.store.registerModule(
resource.name,
storeResource({
provider: this.dataProvider,
resource,
i18n: this.i18n,
})
)
);
}
/**
* Add resources routes dynamically
*/
this.routes.children = this.resources
.map((resource) =>
routeResource({
app: this.app,
admin: this,
store: this.store,
i18: this.i18n,
resource,
title: this.i18n.global.t("titles." + this.title),
})
)
.concat(
(this.routes.children || []).map((r) => {
r.meta = { ...(r.meta || {}), authenticated: true }
return r;
})
)
// add routes dynmically
//
this.router.addRoute(this.routes)
/**
* Check Auth after each navigation
*/
this.router.beforeEach(async (to, from, next) => {
this.store.commit("messages/cleanError")
this.store.commit("messages/cleanSnackbar")
/**
* Set main and document title
*/
document.title = to.meta.title
? `${this.i18n.global.t("titles." + lowerCase(to.meta.title))} | ${this.i18n.global.t("titles." + lowerCase(this.title))}`
: this.i18n.global.t("titles." + lowerCase(this.title))
next();
})
} // end init function
/**
* Permissions helper & directive
*/
async can(permissions) {
if (!this.authProvider || isEmpty(permissions)) {
return false
}
const Self = this;
let result = false;
let user = await new Promise(function (resolve) {
let res = cookies.get(Self.cookieKey.user)
if (res) {
res = JSON.parse(res)
return resolve(res)
}
return resolve(null)
}).catch(function (e) {
console.error(e)
})
if (user && Array.isArray(permissions)) {
user.permissions.forEach(function(roleKey) {
if (permissions.includes(roleKey)) {
result = true
}
})
}
return result
}
/**
* Get global admin config object
*
* @return
*/
getConfig() {
return this.config;
}
/**
* Get full resource object meta from name
*/
getResource(name) {
return this.resources.find((r) => r.name === name)
}
/**
* Get label source, humanize it if not found
*/
getSourceLabel(resource, source) {
if (resource && source) {
let key = `resources.${resource}.fields.${source}`;
return this.i18n.global.te(key)
? this.i18n.global.t(key)
: upperFirst(lowerCase(source.replace(".", " ")));
}
return null
}
/**
* Resource link helper with action permission test
*/
getResourceLink(link) {
let getLink = ({ name, icon, text, action }) => {
action = action || "list";
let resource = this.getResource(name);
if (!resource) {
return false;
}
let { routes, canAction, singularName, pluralName } = resource
/**
* Route must exist
*/
if (!routes.includes(action)) {
return false;
}
/**
* Current user must have permission for this action
*/
if (!canAction(action)) {
return false;
}
return {
icon: icon || resource.icon,
text: text || (action === "list" ? pluralName : singularName),
link: { name: `${name}_${action}` },
};
}
if (typeof link === "object") {
return getLink(link);
}
return getLink({ name: link });
}
/**
* Resource links list helper
*/
getResourceLinks(links) {
return links
.map((link) => {
if (typeof link === "object") {
if (link.children) {
return link;
}
return this.getResourceLink(link);
}
return this.getResourceLink({ name: link })
})
.filter((r) => r)
}
/**
* Global confirm dialog function
*/
confirm(title, message) {
return this.store.dispatch("messages/confirm", { title, message })
}
/**
* Show global snackbar message
*/
message(type, message) {
this.store.commit("messages/show", { type: type.toLowerCase(), message: message });
}
/**
* Refresh the current page
*/
refresh(resource) {
return this.store.dispatch("api/refresh", resource);
}
/**
* Disable/enable "api errors" before/after http request(s)
*/
hideApiErrors(status) {
this.store.commit("messages/hideApiErrors", status);
}
} // end class