@driveflux/auth 4.0.56 → 4.0.57

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 (48) hide show
  1. package/dist/AuthProvider.js +59 -76
  2. package/dist/authorization/constants.js +24 -45
  3. package/dist/authorization/define.js +28 -57
  4. package/dist/authorization/fields/index.js +7 -4
  5. package/dist/authorization/helpers.js +8 -10
  6. package/dist/authorization/index.js +6 -6
  7. package/dist/authorization/permissions-list.js +7 -5
  8. package/dist/authorization/quick.js +1 -1
  9. package/dist/authorization/roles/admin/business-development-executive.js +7 -20
  10. package/dist/authorization/roles/admin/ceo.js +2 -4
  11. package/dist/authorization/roles/admin/common.js +2 -4
  12. package/dist/authorization/roles/admin/concierge.js +10 -35
  13. package/dist/authorization/roles/admin/customer-success-executive.js +10 -40
  14. package/dist/authorization/roles/admin/data-analyst.js +4 -7
  15. package/dist/authorization/roles/admin/designer.js +4 -7
  16. package/dist/authorization/roles/admin/engineer.js +4 -7
  17. package/dist/authorization/roles/admin/finance-executive.js +4 -11
  18. package/dist/authorization/roles/admin/head-of-business-development.js +5 -14
  19. package/dist/authorization/roles/admin/head-of-data-analytics.js +4 -14
  20. package/dist/authorization/roles/admin/head-of-engineering.js +7 -17
  21. package/dist/authorization/roles/admin/head-of-finance.js +4 -8
  22. package/dist/authorization/roles/admin/head-of-human-resources.js +6 -13
  23. package/dist/authorization/roles/admin/head-of-marketing.js +6 -17
  24. package/dist/authorization/roles/admin/head-of-operations.js +4 -8
  25. package/dist/authorization/roles/admin/head-of-product.js +7 -17
  26. package/dist/authorization/roles/admin/head-of-sales.js +6 -17
  27. package/dist/authorization/roles/admin/human-resources-executive.js +5 -12
  28. package/dist/authorization/roles/admin/marketing-executive.js +4 -7
  29. package/dist/authorization/roles/admin/product-manager.js +4 -7
  30. package/dist/authorization/roles/admin/sales-executive.js +8 -24
  31. package/dist/authorization/roles/consumer/business-admin.js +6 -19
  32. package/dist/authorization/roles/consumer/business-user.js +6 -18
  33. package/dist/authorization/roles/consumer/member.js +6 -16
  34. package/dist/authorization/types.js +1 -1
  35. package/dist/authorization/update-user-permissions.js +15 -22
  36. package/dist/authorization/utils.js +11 -26
  37. package/dist/context.js +9 -8
  38. package/dist/default.js +1 -1
  39. package/dist/server/authenticate-user.js +7 -11
  40. package/dist/server/cors.js +12 -23
  41. package/dist/server/credentials-provider.js +2 -2
  42. package/dist/server/next-auth.js +109 -104
  43. package/dist/server/prisma-adapter.js +52 -88
  44. package/dist/server/verfiy-token.js +24 -39
  45. package/dist/translations.js +4 -4
  46. package/dist/use-auth.js +1 -1
  47. package/dist/use-session.js +1 -1
  48. package/package.json +1 -1
@@ -8,34 +8,37 @@ import Cookies from 'js-cookie';
8
8
  //! seems like bad idea but it's the only way to resolve conflict
9
9
  //! between Vercel build and reference of NextRouter instance
10
10
  import Router, { useRouter } from 'next/dist/client/router.js';
11
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
11
+ import { useCallback, useEffect, useMemo, useRef, useState, } from 'react';
12
12
  import useSWR from 'swr';
13
13
  import { AuthContext } from './context.js';
14
14
  import { translations } from './translations.js';
15
- const AuthProvider = ({ children })=>{
15
+ const AuthProvider = ({ children }) => {
16
16
  const { data: session, status, update } = useAuthSession();
17
17
  const { setUserData } = useTrackEvent();
18
18
  const [token, setToken] = useState(null);
19
19
  /**
20
- * A reference to a promise that fetches a new access token from the server.
21
- * This is used to prevent multiple token requests from being sent simultaneously.
22
- */ const newTokenPromise = useRef(null);
20
+ * A reference to a promise that fetches a new access token from the server.
21
+ * This is used to prevent multiple token requests from being sent simultaneously.
22
+ */
23
+ const newTokenPromise = useRef(null);
23
24
  const localeLogicRan = useRef(false);
24
25
  const router = useRouter();
25
26
  const { pathname, asPath, query, locale } = router;
26
27
  const { toastResult } = useToastResult();
27
- const { data: user, isValidating, mutate, error } = useSWR(session ? `${config.apiUrl}/user` : null, {
28
- fallbackData: session?.user
28
+ const { data: user, isValidating, mutate, error, } = useSWR(session ? `${config.apiUrl}/user` : null, {
29
+ fallbackData: session
30
+ ?.user,
29
31
  });
30
32
  const isLoadingUser = status !== 'unauthenticated' && isValidating && !user;
31
33
  /**
32
- * Retrieves an access token for the current user. If a token is already available and has not expired, it will be returned immediately.
33
- * Otherwise, the function will attempt to retrieve the token from cookies, and if that fails, it will fetch a new token from the server.
34
- * If a new token is fetched, it will be stored in cookies and returned.
35
- * If the user is not authenticated, the function will return null and display an error message.
36
- * @returns {Promise<string | null>} A promise that resolves to the access token string, or null if the user is not authenticated.
37
- */ // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
38
- const getAccessToken = useCallback(async ()=>{
34
+ * Retrieves an access token for the current user. If a token is already available and has not expired, it will be returned immediately.
35
+ * Otherwise, the function will attempt to retrieve the token from cookies, and if that fails, it will fetch a new token from the server.
36
+ * If a new token is fetched, it will be stored in cookies and returned.
37
+ * If the user is not authenticated, the function will return null and display an error message.
38
+ * @returns {Promise<string | null>} A promise that resolves to the access token string, or null if the user is not authenticated.
39
+ */
40
+ // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
41
+ const getAccessToken = useCallback(async () => {
39
42
  // Check the state first, if we have a token, return it
40
43
  if (token && token.expiresAt > new Date()) {
41
44
  return token.accessToken;
@@ -48,17 +51,19 @@ const AuthProvider = ({ children })=>{
48
51
  if (expiresAt > new Date()) {
49
52
  setToken({
50
53
  accessToken: tokenFromCookies.accessToken,
51
- expiresAt
54
+ expiresAt,
52
55
  });
53
56
  }
54
57
  return tokenFromCookies.accessToken;
55
58
  }
56
- } catch (_e) {
57
- // TODO
58
- // Nothing to do here
59
59
  }
60
- const tokenPromise = newTokenPromise.current || // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
61
- (newTokenPromise.current = enhancedFetch(`${config.apiUrl}/user/token`));
60
+ catch (_e) {
61
+ // TODO
62
+ // Nothing to do here
63
+ }
64
+ const tokenPromise = newTokenPromise.current ||
65
+ // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
66
+ (newTokenPromise.current = enhancedFetch(`${config.apiUrl}/user/token`));
62
67
  // As a last resort, fetch a new token
63
68
  const newToken = await tokenPromise;
64
69
  // Resets the newTokenPromise reference to null after the new token has been fetched.
@@ -67,50 +72,42 @@ const AuthProvider = ({ children })=>{
67
72
  toastResult(newToken, {
68
73
  error: {
69
74
  title: translations.unauthenticated,
70
- description: translations.unauthenticatedDescription
71
- }
75
+ description: translations.unauthenticatedDescription,
76
+ },
72
77
  });
73
78
  return null;
74
79
  }
75
80
  const newTokenDetils = {
76
81
  accessToken: newToken.val.id,
77
- expiresAt: new Date(newToken.val.expiresAt)
82
+ expiresAt: new Date(newToken.val.expiresAt),
78
83
  };
79
84
  Cookies.set('accessTokenDetails', JSON.stringify(newTokenDetils));
80
85
  setToken(newTokenDetils);
81
86
  return newToken.val.id;
82
- }, [
83
- token
84
- ]);
85
- const refresh = useCallback(async ()=>{
87
+ }, [token]);
88
+ const refresh = useCallback(async () => {
86
89
  await update();
87
90
  return await mutate();
88
- }, [
89
- mutate,
90
- update
91
- ]);
92
- const logout = useCallback(async ()=>{
93
- await signOut({
94
- redirect: false
95
- });
91
+ }, [mutate, update]);
92
+ const logout = useCallback(async () => {
93
+ await signOut({ redirect: false });
96
94
  await refresh();
97
- }, [
98
- refresh
99
- ]);
100
- const context = useMemo(()=>({
101
- user,
102
- isLoadingUser,
103
- refresh,
104
- error,
105
- getAccessToken,
106
- // TODO
107
- /**
108
- * @deprecated do not use this property, use getAccessToken instead
109
- */ accessToken: token?.accessToken,
110
- signIn,
111
- logout,
112
- status
113
- }), [
95
+ }, [refresh]);
96
+ const context = useMemo(() => ({
97
+ user,
98
+ isLoadingUser,
99
+ refresh,
100
+ error,
101
+ getAccessToken,
102
+ // TODO
103
+ /**
104
+ * @deprecated do not use this property, use getAccessToken instead
105
+ */
106
+ accessToken: token?.accessToken,
107
+ signIn,
108
+ logout,
109
+ status,
110
+ }), [
114
111
  user,
115
112
  isLoadingUser,
116
113
  refresh,
@@ -118,11 +115,11 @@ const AuthProvider = ({ children })=>{
118
115
  getAccessToken,
119
116
  logout,
120
117
  token,
121
- status
118
+ status,
122
119
  ]);
123
120
  // Add preferredLocal if any
124
121
  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
125
- useEffect(()=>{
122
+ useEffect(() => {
126
123
  if (localeLogicRan.current || !user) {
127
124
  return;
128
125
  }
@@ -130,37 +127,23 @@ const AuthProvider = ({ children })=>{
130
127
  const langFromCookies = Cookies.get('NEXT_LOCALE');
131
128
  if (user?.preferredLocale && langFromCookies !== user?.preferredLocale) {
132
129
  Cookies.set('NEXT_LOCALE', user.preferredLocale);
133
- Router.push({
134
- pathname,
135
- query
136
- }, asPath, {
137
- locale: user.preferredLocale
138
- });
130
+ Router.push({ pathname, query }, asPath, { locale: user.preferredLocale });
139
131
  }
140
- }, [
141
- user?.preferredLocale,
142
- pathname,
143
- query,
144
- asPath
145
- ]);
132
+ }, [user?.preferredLocale, pathname, query, asPath]);
146
133
  // Add user to the tracking
147
134
  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
148
- useEffect(()=>{
149
- if (!user) return;
135
+ useEffect(() => {
136
+ if (!user)
137
+ return;
150
138
  setUserData({
151
139
  id: user.id,
152
140
  email: user.email,
153
141
  phoneNumber: user.phoneNumber,
154
142
  firstName: user.firstName,
155
143
  lastName: user.lastName,
156
- addresses: user.addresses
144
+ addresses: user.addresses,
157
145
  });
158
- }, [
159
- user
160
- ]);
161
- return /*#__PURE__*/ _jsx(AuthContext.Provider, {
162
- value: context,
163
- children: children
164
- });
146
+ }, [user]);
147
+ return _jsx(AuthContext.Provider, { value: context, children: children });
165
148
  };
166
149
  export default AuthProvider;
@@ -6,7 +6,7 @@ export const DEPARTMENTS = {
6
6
  SALES: 'sales',
7
7
  FINANCE: 'finance',
8
8
  DATA_ANALYTICS: 'dataAnalytics',
9
- PRODUCT: 'product'
9
+ PRODUCT: 'product',
10
10
  };
11
11
  export const ROLES = {
12
12
  CEO: 'ceo',
@@ -32,54 +32,43 @@ export const ROLES = {
32
32
  PRODUCT_MANAGER: 'productManager',
33
33
  MEMBER: 'member',
34
34
  BUSINESS_ADMIN: 'businessAdmin',
35
- BUSINESS_USER: 'businessUser'
35
+ BUSINESS_USER: 'businessUser',
36
36
  };
37
37
  export const DEPARTMENTS_MAP = {
38
38
  [DEPARTMENTS.CEO_OFFICE]: [
39
39
  ROLES.CEO,
40
40
  ROLES.HEAD_OF_HUMAN_RESOURCES,
41
- ROLES.HUMAN_RESOURCES_EXECUTIVE
41
+ ROLES.HUMAN_RESOURCES_EXECUTIVE,
42
42
  ],
43
43
  [DEPARTMENTS.OPERATIONS]: [
44
44
  ROLES.HEAD_OF_OPERATIONS,
45
45
  ROLES.CUSTOMER_SUCCESS_EXECUTIVE,
46
- ROLES.CONCIERGE
47
- ],
48
- [DEPARTMENTS.MARKETING]: [
49
- ROLES.HEAD_OF_MARKETING,
50
- ROLES.MARKETING_EXECUTIVE
46
+ ROLES.CONCIERGE,
51
47
  ],
48
+ [DEPARTMENTS.MARKETING]: [ROLES.HEAD_OF_MARKETING, ROLES.MARKETING_EXECUTIVE],
52
49
  [DEPARTMENTS.BUSINESS_DEVELOPMENT]: [
53
50
  ROLES.HEAD_OF_BUSINESS_DEVELOPMENT,
54
- ROLES.BUSINESS_DEVELOPMENT_EXECUTIVE
55
- ],
56
- [DEPARTMENTS.SALES]: [
57
- ROLES.HEAD_OF_SALES,
58
- ROLES.SALES_EXECUTIVE
59
- ],
60
- [DEPARTMENTS.FINANCE]: [
61
- ROLES.HEAD_OF_FINANCE,
62
- ROLES.FINANCE_EXECUTIVE
51
+ ROLES.BUSINESS_DEVELOPMENT_EXECUTIVE,
63
52
  ],
53
+ [DEPARTMENTS.SALES]: [ROLES.HEAD_OF_SALES, ROLES.SALES_EXECUTIVE],
54
+ [DEPARTMENTS.FINANCE]: [ROLES.HEAD_OF_FINANCE, ROLES.FINANCE_EXECUTIVE],
64
55
  [DEPARTMENTS.DATA_ANALYTICS]: [
65
56
  ROLES.HEAD_OF_DATA_ANALYTICS,
66
- ROLES.DATA_ANALYST
57
+ ROLES.DATA_ANALYST,
67
58
  ],
68
59
  [DEPARTMENTS.PRODUCT]: [
69
60
  ROLES.HEAD_OF_PRODUCT,
70
61
  ROLES.HEAD_OF_ENGINEERING,
71
62
  ROLES.DESIGNER,
72
63
  ROLES.ENGINEER,
73
- ROLES.PRODUCT_MANAGER
74
- ]
64
+ ROLES.PRODUCT_MANAGER,
65
+ ],
75
66
  };
76
- export const OWNER_ROLES = [
77
- ROLES.CEO
78
- ];
67
+ export const OWNER_ROLES = [ROLES.CEO];
79
68
  export const HIGHER_ADMIN_ROLES = [
80
69
  ROLES.HEAD_OF_HUMAN_RESOURCES,
81
70
  ROLES.HEAD_OF_PRODUCT,
82
- ROLES.HEAD_OF_ENGINEERING
71
+ ROLES.HEAD_OF_ENGINEERING,
83
72
  ];
84
73
  export const ADMIN_ROLES = [
85
74
  ...HIGHER_ADMIN_ROLES,
@@ -99,38 +88,28 @@ export const ADMIN_ROLES = [
99
88
  ROLES.DATA_ANALYST,
100
89
  ROLES.DESIGNER,
101
90
  ROLES.ENGINEER,
102
- ROLES.PRODUCT_MANAGER
103
- ];
104
- export const ALL_ADMIN_ROLES = [
105
- ...ADMIN_ROLES,
106
- ...OWNER_ROLES
91
+ ROLES.PRODUCT_MANAGER,
107
92
  ];
93
+ export const ALL_ADMIN_ROLES = [...ADMIN_ROLES, ...OWNER_ROLES];
108
94
  export const BUSINESS_ROLES = [
109
95
  ROLES.BUSINESS_ADMIN,
110
- ROLES.BUSINESS_USER
111
- ];
112
- export const CONSUMER_ROLES = [
113
- ...BUSINESS_ROLES,
114
- ROLES.MEMBER
115
- ];
116
- export const ASSIGNABLE_ROLES = [
117
- ...ADMIN_ROLES,
118
- ...CONSUMER_ROLES
96
+ ROLES.BUSINESS_USER,
119
97
  ];
98
+ export const CONSUMER_ROLES = [...BUSINESS_ROLES, ROLES.MEMBER];
99
+ export const ASSIGNABLE_ROLES = [...ADMIN_ROLES, ...CONSUMER_ROLES];
120
100
  /**
121
101
  * This is to make it easier for some libraries like zod to understand
122
102
  * the roles types. Keep this in sync with the above ROLES constant
123
- */ export const GENERAL_ROLES = [
124
- ...ALL_ADMIN_ROLES,
125
- ...CONSUMER_ROLES
126
- ];
103
+ */
104
+ export const GENERAL_ROLES = [...ALL_ADMIN_ROLES, ...CONSUMER_ROLES];
127
105
  export const GUEST_PERMISSIONS = [
128
106
  {
129
107
  action: 'create',
130
- subject: 'Inquiry'
108
+ subject: 'Inquiry',
131
109
  },
132
110
  {
133
111
  action: 'read',
134
- subject: 'Vehicle'
135
- }
112
+ subject: 'Vehicle',
113
+ // TODO: RESTRICT FIELDS
114
+ },
136
115
  ];
@@ -1,6 +1,6 @@
1
1
  import { AbilityBuilder } from '@casl/ability';
2
2
  import { createPrismaAbility } from '@casl/prisma';
3
- import { ALL_ADMIN_ROLES, CONSUMER_ROLES, GENERAL_ROLES, HIGHER_ADMIN_ROLES, OWNER_ROLES } from './constants.js';
3
+ import { ALL_ADMIN_ROLES, CONSUMER_ROLES, GENERAL_ROLES, HIGHER_ADMIN_ROLES, OWNER_ROLES, } from './constants.js';
4
4
  import { defineRoleAbilitiesBusinessDevelopmentExecutive } from './roles/admin/business-development-executive.js';
5
5
  import { defineRoleAbilitiesCeo } from './roles/admin/ceo.js';
6
6
  import { defineRoleAbilitiesCommonAdmin } from './roles/admin/common.js';
@@ -26,64 +26,45 @@ import { defineRoleAbilitiesSalesExecutive } from './roles/admin/sales-executive
26
26
  import { defineRoleAbilitiesBusinessAdmin } from './roles/consumer/business-admin.js';
27
27
  import { defineRoleAbilitiesBusinessUser } from './roles/consumer/business-user.js';
28
28
  import { defineRoleAbilitiesMember } from './roles/consumer/member.js';
29
- export const defineAbilityFor = async (user)=>{
29
+ export const defineAbilityFor = async (user) => {
30
30
  const { can, cannot, build } = new AbilityBuilder(createPrismaAbility);
31
31
  if (!user) {
32
32
  return build();
33
33
  }
34
- const groups = Array.isArray(user.groups) ? user.groups.map((r)=>`${r}`) : typeof user.groups === 'string' ? [
35
- user.groups
36
- ] : [];
37
- const consumerGroups = groups.filter((g)=>CONSUMER_ROLES.includes(g));
38
- const adminGroups = groups.filter((g)=>!consumerGroups.includes(g));
39
- const sortedGroups = [
40
- ...consumerGroups,
41
- ...adminGroups
42
- ];
43
- for (const role of sortedGroups){
34
+ const groups = Array.isArray(user.groups)
35
+ ? user.groups.map((r) => `${r}`)
36
+ : typeof user.groups === 'string'
37
+ ? [user.groups]
38
+ : [];
39
+ const consumerGroups = groups.filter((g) => CONSUMER_ROLES.includes(g));
40
+ const adminGroups = groups.filter((g) => !consumerGroups.includes(g));
41
+ const sortedGroups = [...consumerGroups, ...adminGroups];
42
+ for (const role of sortedGroups) {
44
43
  await defineSpecificRoleAbilities(role, can, cannot, user);
45
44
  }
46
45
  // Common admin abilities
47
- if (user.groups.some((g)=>adminGroups.includes(g))) {
46
+ if (user.groups.some((g) => adminGroups.includes(g))) {
48
47
  await defineRoleAbilitiesCommonAdmin(can);
49
48
  }
50
49
  // General abilities
51
- can([
52
- 'read',
53
- 'update'
54
- ], 'User', {
55
- id: user.id
56
- });
57
- can([
58
- 'read'
59
- ], 'Invoice', {
60
- payerId: user.id
61
- });
50
+ can(['read', 'update'], 'User', { id: user.id });
51
+ can(['read'], 'Invoice', { payerId: user.id });
62
52
  if (user.businessId) {
63
- can([
64
- 'read'
65
- ], 'Invoice', {
66
- payerId: user.businessId
67
- });
53
+ can(['read'], 'Invoice', { payerId: user.businessId });
68
54
  }
69
- can('reserveVehicle', 'User', {
70
- banned: false,
71
- consented: true
72
- });
55
+ can('reserveVehicle', 'User', { banned: false, consented: true });
73
56
  // Prevent updating the groups for all users
74
- cannot('update', 'User', [
75
- 'groups'
76
- ]);
57
+ cannot('update', 'User', ['groups']);
77
58
  return build();
78
59
  };
79
- const defineSpecificRoleAbilities = async (r, can, cannot, rawUser)=>{
60
+ const defineSpecificRoleAbilities = async (r, can, cannot, rawUser) => {
80
61
  if (!~GENERAL_ROLES.indexOf(r)) {
81
62
  return;
82
63
  }
83
64
  // Type issue
84
65
  const user = rawUser;
85
66
  const role = r;
86
- switch(role){
67
+ switch (role) {
87
68
  // Owners
88
69
  case 'ceo':
89
70
  defineRoleAbilitiesCeo(can);
@@ -161,30 +142,20 @@ const defineSpecificRoleAbilities = async (r, can, cannot, rawUser)=>{
161
142
  case 'businessAdmin':
162
143
  defineRoleAbilitiesBusinessAdmin(can, user);
163
144
  break;
164
- default:
165
- {
166
- const _exhaustiveCheck = role;
167
- break;
168
- }
145
+ default: {
146
+ const _exhaustiveCheck = role;
147
+ break;
148
+ }
169
149
  }
170
- if (![
171
- ...OWNER_ROLES,
172
- ...HIGHER_ADMIN_ROLES
173
- ].includes(role)) {
150
+ if (![...OWNER_ROLES, ...HIGHER_ADMIN_ROLES].includes(role)) {
174
151
  cannot('manageAdmin', 'User');
175
- cannot([
176
- 'create',
177
- 'update',
178
- 'delete'
179
- ], 'User', undefined, {
152
+ cannot(['create', 'update', 'delete'], 'User', undefined, {
180
153
  groups: {
181
- hasSome: [
182
- ...ALL_ADMIN_ROLES
183
- ]
184
- }
154
+ hasSome: [...ALL_ADMIN_ROLES],
155
+ },
185
156
  }).because('You are not allowed to update admin users');
186
157
  can('update', 'User', undefined, {
187
- id: user.id
158
+ id: user.id,
188
159
  });
189
160
  }
190
161
  };
@@ -1,5 +1,6 @@
1
1
  import { Prisma, prisma } from '@driveflux/db';
2
- export const MODEL_FIELDS = Object.keys(Prisma.ModelName).map((k)=>{
2
+ export const MODEL_FIELDS = Object.keys(Prisma.ModelName)
3
+ .map((k) => {
3
4
  if (!(k in Prisma.ModelName)) {
4
5
  return null;
5
6
  }
@@ -7,15 +8,17 @@ export const MODEL_FIELDS = Object.keys(Prisma.ModelName).map((k)=>{
7
8
  return {
8
9
  // TODO
9
10
  // @ts-expect-error
10
- [key]: prisma._runtimeDataModel.models[key].fields.map((f)=>f.name)
11
+ [key]: prisma._runtimeDataModel.models[key].fields.map((f) => f.name),
11
12
  };
12
- }).filter((m)=>m).reduce((carry, current)=>{
13
+ })
14
+ .filter((m) => m)
15
+ .reduce((carry, current) => {
13
16
  if (current) {
14
17
  Object.assign(carry, current);
15
18
  }
16
19
  return carry;
17
20
  }, {});
18
- export const getModelFields = (model)=>{
21
+ export const getModelFields = (model) => {
19
22
  const fields = MODEL_FIELDS[model];
20
23
  return fields;
21
24
  };
@@ -1,18 +1,16 @@
1
1
  import { ALL_ADMIN_ROLES, CONSUMER_ROLES, OWNER_ROLES } from './constants';
2
- export const extractAdminRoles = (userGroups)=>{
3
- return userGroups?.filter((group)=>isAdmin(group));
2
+ export const extractAdminRoles = (userGroups) => {
3
+ return userGroups?.filter((group) => isAdmin(group));
4
4
  };
5
- export const extractNonAdminRoles = (userGroups)=>{
6
- return userGroups?.filter((group)=>!isAdmin(group));
5
+ export const extractNonAdminRoles = (userGroups) => {
6
+ return userGroups?.filter((group) => !isAdmin(group));
7
7
  };
8
- export const isConsumer = (group)=>{
8
+ export const isConsumer = (group) => {
9
9
  return CONSUMER_ROLES.includes(group);
10
10
  };
11
- export const isOwner = (group)=>{
12
- return [
13
- ...OWNER_ROLES
14
- ]?.map((r)=>group === r)?.[0];
11
+ export const isOwner = (group) => {
12
+ return [...OWNER_ROLES]?.map((r) => group === r)?.[0];
15
13
  };
16
- export const isAdmin = (group)=>{
14
+ export const isAdmin = (group) => {
17
15
  return ALL_ADMIN_ROLES.includes(group);
18
16
  };
@@ -4,15 +4,15 @@ import { ErrorWithResult } from '@driveflux/result';
4
4
  import { GUEST_PERMISSIONS } from './constants.js';
5
5
  import buildAbilityFromJson from './quick.js';
6
6
  import { updateUserPermissions } from './update-user-permissions.js';
7
- export const buildOrDefineAbility = async (user, refresh)=>{
7
+ export const buildOrDefineAbility = async (user, refresh) => {
8
8
  if (!user) {
9
- return createPrismaAbility([
10
- ...GUEST_PERMISSIONS
11
- ], {
12
- detectSubjectType: detectSubjectType
9
+ return createPrismaAbility([...GUEST_PERMISSIONS], {
10
+ detectSubjectType: detectSubjectType,
13
11
  });
14
12
  }
15
- if (!Array.isArray(user.permissions) || !user.permissions?.length || refresh) {
13
+ if (!Array.isArray(user.permissions) ||
14
+ !user.permissions?.length ||
15
+ refresh) {
16
16
  const result = await updateUserPermissions(user);
17
17
  if (result.err) {
18
18
  throw new ErrorWithResult(result);
@@ -1,5 +1,5 @@
1
1
  import { s } from './utils.js';
2
- export const getPermissionsFromAbility = (ability)=>{
2
+ export const getPermissionsFromAbility = (ability) => {
3
3
  return {
4
4
  // Lists
5
5
  viewAnalytics: ability.can('manageAdmin', 'Reports'),
@@ -51,7 +51,7 @@ export const getPermissionsFromAbility = (ability)=>{
51
51
  updateVehicleServiceCenters: ability.can('update', 'Vehicle', 'allowedServiceCenterIds'),
52
52
  readPricingInput: ability.can('readPricingInput', 'Vehicle'),
53
53
  updatePricingInput: ability.can('update', 'Vehicle', 'pricing'),
54
- testPricingInput: ability.can('testPricingInput', 'Vehicle'),
54
+ testPricingInput: ability.can('testPricingInput', 'Vehicle'), // Special Permission to allow users edit pricing but without the ability to update
55
55
  // Users ( Members )
56
56
  createMember: ability.can('create', 'User'),
57
57
  updateMember: ability.can('update', s('User')),
@@ -82,7 +82,8 @@ export const getPermissionsFromAbility = (ability)=>{
82
82
  updateInvoice: ability.can('update', s('Invoice', 'payerId')),
83
83
  cancelInvoice: ability.can('cancelInvoice', 'Invoice'),
84
84
  markInvoiceAsPaid: ability.can('markInvoice', 'Invoice', 'paid'),
85
- markInvoiceAsRefunded: ability.can('markInvoice', 'Invoice', 'totalRefunded') && ability.can('create', 'Refund'),
85
+ markInvoiceAsRefunded: ability.can('markInvoice', 'Invoice', 'totalRefunded') &&
86
+ ability.can('create', 'Refund'),
86
87
  readPaymentMethodsUser: ability.can('read', s('User'), 'paymentMethods'),
87
88
  readPaymentMethodsBusiness: ability.can('read', s('Business'), 'paymentMethods'),
88
89
  addPaymentMethodUser: ability.can('update', s('User'), 'paymentMethods'),
@@ -130,7 +131,8 @@ export const getPermissionsFromAbility = (ability)=>{
130
131
  // TODO add logs permision or remove the comments
131
132
  // Logs
132
133
  // Website Settings
133
- uploadBanners: ability.can('update', 'PlatformConfig') && ability.can('create', 'PlatformConfig'),
134
+ uploadBanners: ability.can('update', 'PlatformConfig') &&
135
+ ability.can('create', 'PlatformConfig'),
134
136
  deleteBanners: ability.can('update', 'PlatformConfig'),
135
137
  // Quotations
136
138
  createQuotation: ability.can('create', 'Quotation'),
@@ -139,6 +141,6 @@ export const getPermissionsFromAbility = (ability)=>{
139
141
  createVacancy: ability.can('create', 'Vacancy'),
140
142
  updateVacancy: ability.can('update', 'Vacancy'),
141
143
  readApplicant: ability.can('read', 'Applicant'),
142
- readVacancy: ability.can('read', 'Vacancy')
144
+ readVacancy: ability.can('read', 'Vacancy'),
143
145
  };
144
146
  };
@@ -2,7 +2,7 @@ import { createPrismaAbility } from '@casl/prisma';
2
2
  import { detectSubjectType } from './utils.js';
3
3
  export function buildAbilityFromJson(user) {
4
4
  return createPrismaAbility(user.permissions, {
5
- detectSubjectType
5
+ detectSubjectType,
6
6
  });
7
7
  }
8
8
  export default buildAbilityFromJson;
@@ -1,5 +1,5 @@
1
1
  import { getDocumentsFields } from '../../utils.js';
2
- export const defineRoleAbilitiesBusinessDevelopmentExecutive = async (can, cannot)=>{
2
+ export const defineRoleAbilitiesBusinessDevelopmentExecutive = async (can, cannot) => {
3
3
  can('read', [
4
4
  'Subscription',
5
5
  'Vehicle',
@@ -13,35 +13,22 @@ export const defineRoleAbilitiesBusinessDevelopmentExecutive = async (can, canno
13
13
  'PaymentLink',
14
14
  'Invoice',
15
15
  'Transaction',
16
- 'Refund'
16
+ 'Refund',
17
17
  ]);
18
18
  cannot('update', 'Invoice');
19
- can('manage', [
20
- 'Vehicle',
21
- 'ServiceCenter',
22
- 'Host',
23
- 'Inquiry',
24
- 'Token'
25
- ]);
19
+ can('manage', ['Vehicle', 'ServiceCenter', 'Host', 'Inquiry', 'Token']);
26
20
  can('readPricingInput', 'Vehicle');
27
21
  can('connectHostToStripe', 'Host');
28
- can('update', 'Subscription', [
29
- 'vehicleId'
30
- ]);
22
+ can('update', 'Subscription', ['vehicleId']);
31
23
  cannot('read', 'User', 'status');
32
24
  cannot('read', 'User', [
33
25
  ...getDocumentsFields('identification'),
34
26
  ...getDocumentsFields('drivingHistory'),
35
27
  ...getDocumentsFields('financial'),
36
- ...getDocumentsFields('offerLetter')
37
- ]);
38
- can([
39
- 'viewSubscriptionApproval'
40
- ], 'Subscription');
41
- cannot('read', [
42
- 'Vacancy',
43
- 'Applicant'
28
+ ...getDocumentsFields('offerLetter'),
44
29
  ]);
30
+ can(['viewSubscriptionApproval'], 'Subscription');
31
+ cannot('read', ['Vacancy', 'Applicant']);
45
32
  can('read', 'Activity');
46
33
  can('read', 'ActivityTask');
47
34
  };
@@ -1,5 +1,3 @@
1
- export const defineRoleAbilitiesCeo = async (can)=>{
2
- can([
3
- 'manage'
4
- ], 'all');
1
+ export const defineRoleAbilitiesCeo = async (can) => {
2
+ can(['manage'], 'all');
5
3
  };
@@ -1,5 +1,3 @@
1
- export const defineRoleAbilitiesCommonAdmin = async (can)=>{
2
- can([
3
- 'read'
4
- ], 'Issue');
1
+ export const defineRoleAbilitiesCommonAdmin = async (can) => {
2
+ can(['read'], 'Issue');
5
3
  };