adminforth 1.3.21 → 1.3.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/auth.ts CHANGED
@@ -30,10 +30,15 @@ class AdminForthAuth {
30
30
  response.setHeader('Set-Cookie', `adminforth_jwt=; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT`);
31
31
  }
32
32
 
33
- setAuthCookie({ response, username, pk}: {
34
- response: any, username: string, pk: string | null
33
+ setAuthCookie({ expireInDays, response, username, pk}: {
34
+ expireInDays?: number,
35
+ response: any,
36
+ username: string,
37
+ pk: string | null
35
38
  }) {
36
- const token = this.issueJWT({ username, pk, }, 'auth');
39
+ const expiresIn: string = expireInDays ? `${expireInDays}d` : (process.env.ADMINFORTH_AUTH_EXPIRESIN || '24h');
40
+
41
+ const token = this.issueJWT({ username, pk}, 'auth', expiresIn);
37
42
  response.setHeader('Set-Cookie', `adminforth_jwt=${token}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict`);
38
43
  }
39
44
 
@@ -47,11 +52,8 @@ class AdminForthAuth {
47
52
  const {name,value,expiry,httpOnly} = payload
48
53
  response.setHeader('Set-Cookie', `adminforth_${name}=${value}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=${new Date(Date.now() + expiry).toUTCString() } `);
49
54
  }
50
-
51
55
 
52
-
53
-
54
- issueJWT(payload: Object, type: string) {
56
+ issueJWT(payload: Object, type: string, expiresIn: string = '24h'): string {
55
57
  // read ADMINFORH_SECRET from environment if not drop error
56
58
  const secret = process.env.ADMINFORTH_SECRET;
57
59
  if (!secret) {
@@ -59,7 +61,6 @@ class AdminForthAuth {
59
61
  }
60
62
 
61
63
  // issue JWT token
62
- const expiresIn = process.env.ADMINFORTH_AUTH_EXPIRESIN || '24h';
63
64
  return jwt.sign({...payload, t: type}, secret, { expiresIn });
64
65
  }
65
66
 
package/dist/auth.js CHANGED
@@ -30,8 +30,9 @@ class AdminForthAuth {
30
30
  removeAuthCookie(response) {
31
31
  response.setHeader('Set-Cookie', `adminforth_jwt=; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=Thu, 01 Jan 1970 00:00:00 GMT`);
32
32
  }
33
- setAuthCookie({ response, username, pk }) {
34
- const token = this.issueJWT({ username, pk, }, 'auth');
33
+ setAuthCookie({ expireInDays, response, username, pk }) {
34
+ const expiresIn = expireInDays ? `${expireInDays}d` : (process.env.ADMINFORTH_AUTH_EXPIRESIN || '24h');
35
+ const token = this.issueJWT({ username, pk }, 'auth', expiresIn);
35
36
  response.setHeader('Set-Cookie', `adminforth_jwt=${token}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict`);
36
37
  }
37
38
  removeCustomCookie({ response, name }) {
@@ -41,14 +42,13 @@ class AdminForthAuth {
41
42
  const { name, value, expiry, httpOnly } = payload;
42
43
  response.setHeader('Set-Cookie', `adminforth_${name}=${value}; Path=${this.adminforth.config.baseUrl || '/'}; HttpOnly; SameSite=Strict; Expires=${new Date(Date.now() + expiry).toUTCString()} `);
43
44
  }
44
- issueJWT(payload, type) {
45
+ issueJWT(payload, type, expiresIn = '24h') {
45
46
  // read ADMINFORH_SECRET from environment if not drop error
46
47
  const secret = process.env.ADMINFORTH_SECRET;
47
48
  if (!secret) {
48
49
  throw new Error('ADMINFORTH_SECRET environment not set');
49
50
  }
50
51
  // issue JWT token
51
- const expiresIn = process.env.ADMINFORTH_AUTH_EXPIRESIN || '24h';
52
52
  return jwt.sign(Object.assign(Object.assign({}, payload), { t: type }), secret, { expiresIn });
53
53
  }
54
54
  verify(jwtToken_1, mustHaveType_1) {
@@ -251,6 +251,7 @@ export default class ConfigValidator {
251
251
  label: `Delete checked`,
252
252
  state: 'danger',
253
253
  icon: 'flowbite:trash-bin-outline',
254
+ confirm: 'Are you sure you want to delete selected items?',
254
255
  allowed: (_b) => __awaiter(this, [_b], void 0, function* ({ resource, adminUser, allowedActions }) { return allowedActions.delete; }),
255
256
  action: (_c) => __awaiter(this, [_c], void 0, function* ({ selectedIds, adminUser }) {
256
257
  const connector = this.adminforth.connectors[res.dataSource];
@@ -286,7 +287,7 @@ export default class ConfigValidator {
286
287
  if (error) {
287
288
  return { error, ok: false };
288
289
  }
289
- return { ok: true };
290
+ return { ok: true, successMessage: `${selectedIds.length} item${selectedIds.length > 1 ? 's' : ''} deleted` };
290
291
  })
291
292
  });
292
293
  }
@@ -43,8 +43,8 @@ export default class AdminForthRestAPI {
43
43
  path: '/login',
44
44
  handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, response }) {
45
45
  var _b, _c, _d, _e;
46
- const INVALID_MESSAGE = 'Invalid username or password';
47
- const { username, password } = body;
46
+ const INVALID_MESSAGE = 'Invalid Username or Password';
47
+ const { username, password, rememberMe } = body;
48
48
  let adminUser;
49
49
  let toReturn = { ok: true, allowedLogin: true };
50
50
  // get resource from db
@@ -71,9 +71,8 @@ export default class AdminForthRestAPI {
71
71
  offset: 0,
72
72
  sort: [],
73
73
  })).data) === null || _b === void 0 ? void 0 : _b[0];
74
- console.log('userRecord', userRecord, this.adminforth.config.auth.usernameField, username);
75
74
  if (!userRecord) {
76
- return { error: 'User not found' };
75
+ return { error: INVALID_MESSAGE };
77
76
  }
78
77
  const passwordHash = userRecord[this.adminforth.config.auth.passwordHashField];
79
78
  const valid = yield AdminForthAuth.verifyPassword(password, passwordHash);
@@ -94,7 +93,13 @@ export default class AdminForthRestAPI {
94
93
  }
95
94
  }
96
95
  if (toReturn.allowedLogin) {
97
- this.adminforth.auth.setAuthCookie({ response, username, pk: userRecord[userResource.columns.find((col) => col.primaryKey).name] });
96
+ const expireInDays = rememberMe && this.adminforth.config.auth.rememberMeDays;
97
+ this.adminforth.auth.setAuthCookie({
98
+ expireInDays,
99
+ response,
100
+ username,
101
+ pk: userRecord[userResource.columns.find((col) => col.primaryKey).name]
102
+ });
98
103
  }
99
104
  }
100
105
  else {
@@ -141,6 +146,7 @@ export default class AdminForthRestAPI {
141
146
  demoCredentials: this.adminforth.config.auth.demoCredentials,
142
147
  loginPromptHTML: this.adminforth.config.auth.loginPromptHTML,
143
148
  loginPageInjections: this.adminforth.config.customization.loginPageInjections,
149
+ rememberMeDays: this.adminforth.config.auth.rememberMeDays,
144
150
  };
145
151
  }),
146
152
  });
@@ -6,6 +6,7 @@ import {
6
6
  AdminForthResourcePages, AllowedActionsEnum,
7
7
  type AdminForthComponentDeclarationFull,
8
8
  type AfterSaveFunction,
9
+ AdminForthBulkAction,
9
10
  } from "../types/AdminForthConfig.js";
10
11
 
11
12
  import fs from 'fs';
@@ -260,7 +261,7 @@ export default class ConfigValidator implements IConfigValidator {
260
261
 
261
262
 
262
263
  //check if resource has bulkActions
263
- let bulkActions = res?.options?.bulkActions || [];
264
+ let bulkActions: AdminForthBulkAction[] = res?.options?.bulkActions || [];
264
265
 
265
266
  if (!Array.isArray(bulkActions)) {
266
267
  errors.push(`Resource "${res.resourceId}" bulkActions must be an array`);
@@ -272,6 +273,7 @@ export default class ConfigValidator implements IConfigValidator {
272
273
  label: `Delete checked`,
273
274
  state: 'danger',
274
275
  icon: 'flowbite:trash-bin-outline',
276
+ confirm: 'Are you sure you want to delete selected items?',
275
277
  allowed: async ({ resource, adminUser, allowedActions }) => { return allowedActions.delete },
276
278
  action: async ({ selectedIds, adminUser }) => {
277
279
  const connector = this.adminforth.connectors[res.dataSource];
@@ -324,7 +326,7 @@ export default class ConfigValidator implements IConfigValidator {
324
326
  if (error) {
325
327
  return { error, ok: false };
326
328
  }
327
- return { ok: true };
329
+ return { ok: true, successMessage: `${selectedIds.length} item${selectedIds.length > 1 ? 's' : ''} deleted` };
328
330
  }
329
331
  });
330
332
  }
@@ -62,8 +62,8 @@ export default class AdminForthRestAPI {
62
62
  path: '/login',
63
63
  handler: async ({ body, response }) => {
64
64
 
65
- const INVALID_MESSAGE = 'Invalid username or password';
66
- const { username, password } = body;
65
+ const INVALID_MESSAGE = 'Invalid Username or Password';
66
+ const { username, password, rememberMe } = body;
67
67
  let adminUser: AdminUser;
68
68
  let toReturn: { ok: boolean, redirectTo?: string, allowedLogin:boolean } = { ok: true, allowedLogin:true};
69
69
 
@@ -95,10 +95,9 @@ export default class AdminForthRestAPI {
95
95
  })
96
96
  ).data?.[0];
97
97
 
98
- console.log('userRecord', userRecord, this.adminforth.config.auth.usernameField, username);
99
98
 
100
99
  if (!userRecord) {
101
- return { error: 'User not found' };
100
+ return { error: INVALID_MESSAGE };
102
101
  }
103
102
 
104
103
  const passwordHash = userRecord[this.adminforth.config.auth.passwordHashField];
@@ -121,7 +120,13 @@ export default class AdminForthRestAPI {
121
120
  }
122
121
  }
123
122
  if (toReturn.allowedLogin){
124
- this.adminforth.auth.setAuthCookie({ response, username, pk: userRecord[userResource.columns.find((col) => col.primaryKey).name] });
123
+ const expireInDays = rememberMe && this.adminforth.config.auth.rememberMeDays;
124
+ this.adminforth.auth.setAuthCookie({
125
+ expireInDays,
126
+ response,
127
+ username,
128
+ pk: userRecord[userResource.columns.find((col) => col.primaryKey).name]
129
+ });
125
130
  }
126
131
  } else {
127
132
  return { error: INVALID_MESSAGE };
@@ -173,6 +178,7 @@ export default class AdminForthRestAPI {
173
178
  demoCredentials: this.adminforth.config.auth.demoCredentials,
174
179
  loginPromptHTML: this.adminforth.config.auth.loginPromptHTML,
175
180
  loginPageInjections: this.adminforth.config.customization.loginPageInjections,
181
+ rememberMeDays: this.adminforth.config.auth.rememberMeDays,
176
182
  };
177
183
  },
178
184
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "adminforth",
3
- "version": "1.3.21",
3
+ "version": "1.3.23",
4
4
  "description": "OpenSource Vue3 powered forth-generation admin panel",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -9,7 +9,7 @@ export function showWarningTost(message: string) {
9
9
  }
10
10
 
11
11
  export function showErrorTost(message: string, timeout?: number) {
12
- window.adminforth.alert({ message, variant: 'danger', timeout: timeout || 'unlimited'});
12
+ window.adminforth.alert({ message, variant: 'danger', timeout: timeout || 30});
13
13
  return message;
14
14
  }
15
15
 
@@ -57,7 +57,11 @@ export class FrontendAPI implements FrontendAPIInterface {
57
57
 
58
58
  confirm(params: ConfirmParams): Promise<void> {
59
59
  return new Promise((resolve, reject) => {
60
- this.modalStore.setModalContent({ content: params.message, acceptText: params.yes, cancelText: params.no })
60
+ this.modalStore.setModalContent({
61
+ content: params.message,
62
+ acceptText: params.yes || 'Yes',
63
+ cancelText: params.no || 'Cancel'
64
+ })
61
65
  this.modalStore.onAcceptFunction = resolve
62
66
  this.modalStore.onCancelFunction = reject
63
67
  this.modalStore.togleModal()
@@ -71,7 +71,7 @@ export const useCoreStore = defineStore('core', () => {
71
71
  window.adminforth.alert({
72
72
  message: respData.error,
73
73
  variant: 'danger',
74
- timeout: 'unlimited'
74
+ timeout: 30,
75
75
  });
76
76
  record.value = {};
77
77
  } else {
@@ -1,14 +1,30 @@
1
- import { ref, computed } from 'vue'
1
+ import { ref, watch, type Ref } from 'vue'
2
2
  import { defineStore } from 'pinia'
3
- import { callAdminForthApi } from '@/utils';
4
3
  import { v1 as uuid } from 'uuid';
4
+ import { useRoute } from 'vue-router';
5
+
6
+
5
7
 
6
8
  export const useToastStore = defineStore('toast', () => {
7
- const toasts = ref([]);
8
- const addToast = (toast) => {
9
- toasts.value.push({...toast, id: uuid()});
9
+ const toasts: Ref<any[]> = ref([]);
10
+ const route = useRoute();
11
+
12
+ watch(route, () => {
13
+ console.log('route changed 121');
14
+ // on route change clear all toasts older then 5 seconds
15
+ const now = +new Date();
16
+ toasts.value = toasts.value.filter((t) => now - t.createdAt < 5000);
17
+ });
18
+
19
+ const addToast = (toast: { message: string; variant: string }) => {
20
+ const toastId = uuid();
21
+ toasts.value.push({
22
+ ...toast,
23
+ id: toastId,
24
+ createdAt: +new Date(),
25
+ });
10
26
  };
11
- const removeToast = (toast) => {
27
+ const removeToast = (toast: { id: string }) => {
12
28
  toasts.value = toasts.value.filter((t) => t.id !== toast.id);
13
29
  };
14
30
  return { toasts, addToast, removeToast };
@@ -149,6 +149,10 @@ async function saveRecord() {
149
149
  primaryKey: response.newRecordId
150
150
  }
151
151
  });
152
+ window.adminforth.alert({
153
+ message: 'Record created successfully',
154
+ variant: 'success'
155
+ });
152
156
  }
153
157
  }
154
158
 
@@ -179,6 +179,16 @@ async function getList() {
179
179
  }
180
180
 
181
181
  async function startBulkAction(actionId) {
182
+ const action = coreStore.resource.options.bulkActions.find(a => a.id === actionId);
183
+ if (action.confirm) {
184
+ const confirmed = await window.adminforth.confirm({
185
+ message: action.confirm,
186
+ });
187
+ if (!confirmed) {
188
+ return;
189
+ }
190
+ }
191
+
182
192
  const data = await callAdminForthApi({
183
193
  path: '/start_bulk_action',
184
194
  method: 'POST',
@@ -192,6 +202,14 @@ async function startBulkAction(actionId) {
192
202
  if (data?.ok) {
193
203
  checkboxes.value = [];
194
204
  await getList();
205
+
206
+ if (data.successMessage) {
207
+ window.adminforth.alert({
208
+ message: data.successMessage,
209
+ variant: 'success'
210
+ });
211
+ }
212
+
195
213
  }
196
214
  if (data?.error) {
197
215
  showErrorTost(data.error);
@@ -56,9 +56,16 @@
56
56
  </button>
57
57
  </div>
58
58
 
59
- <div class="flex items-start mb-5 hidden">
59
+ <div v-if="coreStore.config.rememberMeDays"
60
+ class="flex items-start mb-5"
61
+ :title="`Stay logged in for ${coreStore.config.rememberMeDays} days`"
62
+ >
60
63
  <div class="flex items-center h-5">
61
- <input id="remember" type="checkbox" value="" class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800" required />
64
+ <input id="remember"
65
+ ref="rememberInput"
66
+ type="checkbox"
67
+ value=""
68
+ class="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300 dark:bg-gray-700 dark:border-gray-600 dark:focus:ring-blue-600 dark:ring-offset-gray-800 dark:focus:ring-offset-gray-800" />
62
69
  </div>
63
70
  <label for="remember" class="ms-2 text-sm font-medium text-gray-900 dark:text-gray-300">Remember me</label>
64
71
  </div>
@@ -125,6 +132,7 @@ import { useRouter } from 'vue-router';
125
132
 
126
133
  const passwordInput = ref(null);
127
134
  const usernameInput = ref(null);
135
+ const rememberInput = ref(null);
128
136
 
129
137
  const router = useRouter();
130
138
  const inProgress = ref(false);
@@ -166,6 +174,7 @@ async function login() {
166
174
  body: {
167
175
  username,
168
176
  password,
177
+ rememberMe: rememberInput.value.checked,
169
178
  }
170
179
  });
171
180
  inProgress.value = false;
@@ -239,11 +239,11 @@ export interface IAdminForthDataSourceConnectorConstructor {
239
239
 
240
240
  export interface IAdminForthAuth {
241
241
  verify(jwt : string, mustHaveType: string, decodeUser?: boolean): Promise<any>;
242
- issueJWT(payload: Object, type: string): string;
242
+ issueJWT(payload: Object, type: string, expiresIn?: string): string;
243
243
 
244
244
  removeCustomCookie({response, name}: {response: any, name: string}): void;
245
245
 
246
- setAuthCookie({response, username, pk,}: {response: any, username: string, pk: string}): void;
246
+ setAuthCookie({expireInDays, response, username, pk,}: {expireInDays?: number, response: any, username: string, pk: string}): void;
247
247
 
248
248
  removeAuthCookie(response: any): void;
249
249
  }
@@ -744,13 +744,17 @@ export type AdminForthBulkAction = {
744
744
  * Callback which will be called on backend when user clicks on action button.
745
745
  * It should return Promise which will be resolved when action is done.
746
746
  */
747
- action: ({ resource, selectedIds, adminUser }: { resource: AdminForthResource, selectedIds: Array<any>, adminUser: AdminUser }) => Promise<{ ok: boolean, error?: string }>,
747
+ action: ({ resource, selectedIds, adminUser }: { resource: AdminForthResource, selectedIds: Array<any>, adminUser: AdminUser }) => Promise<{ ok: boolean, error?: string, successMessage?: string }>,
748
748
 
749
749
  /**
750
750
  * Confirmation message which will be displayed to user before action is executed.
751
751
  */
752
752
  confirm?: string,
753
753
 
754
+ /**
755
+ * Success message which will be displayed to user after action is executed.
756
+ */
757
+ successMessage?: string,
754
758
  /**
755
759
  * Allowed callback called to check whether action is allowed for user.
756
760
  * 1. It called first time when user goes to list view. If callback returns false, action button will be hidden on list view.
@@ -1174,6 +1178,13 @@ export type AdminForthConfig = {
1174
1178
  * Any prompt to show users on login. Supports HTML.
1175
1179
  */
1176
1180
  loginPromptHTML?: string,
1181
+
1182
+ /**
1183
+ * Remember me days for "Remember Me" checkbox on login page.
1184
+ * If not set or set to null/0/undefined, "Remember Me" checkbox will not be displayed.
1185
+ * If rememberMeDays is set, then users who check "Remember Me" will be staying logged in for this amount of days.
1186
+ */
1187
+ rememberMeDays?: number,
1177
1188
  },
1178
1189
  /**
1179
1190
  * Array of resources which will be displayed in the admin panel.