@sfxcode/nuxt-ui-mongocamp 1.1.2 → 1.1.4

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/README.md CHANGED
@@ -33,14 +33,14 @@ These modules are declared as `moduleDependencies` and are automatically set up
33
33
  ## Quick Setup
34
34
 
35
35
  ```bash
36
- npm install nuxt-ui-mongocamp
36
+ npm install @sfxcode/nuxt-ui-mongocamp
37
37
  ```
38
38
 
39
39
  Add the module to `nuxt.config.ts`:
40
40
 
41
41
  ```ts
42
42
  export default defineNuxtConfig({
43
- modules: ['nuxt-ui-mongocamp'],
43
+ modules: ['@sfxcode/nuxt-ui-mongocamp'],
44
44
 
45
45
  mongocamp: {
46
46
  url: process.env.MONGOCAMP_URL,
@@ -213,13 +213,16 @@ Fields are sorted with `_id` first, `metaData` last, and all other fields alphab
213
213
 
214
214
  ## Route Protection
215
215
 
216
- The module registers a global route middleware at startup:
216
+ Route protection is opt-in and config-driven via `useMongocampRoles()`. Set `useGlobalAuthMiddleware: true` and list your protected route globs under `nuxtUiMongocamp` — nothing is protected by default. See [Route Protection](https://sfxcode.github.io/nuxt-ui-mongocamp/guide/route-protection) for the full behavior.
217
217
 
218
218
  | Path pattern | Requirement |
219
219
  |---|---|
220
- | `/secured/**` | User must be logged in; redirects to `/` otherwise |
221
- | `/admin/**` or `/secured/admin/**` | User must be logged in **and** have the admin role; redirects to `/secured` otherwise |
222
- | `/logout` | Calls `logout()` and redirects to `/` |
220
+ | Matches `securedRouteParts` | User must be logged in |
221
+ | Matches `managementRouteParts` | User must be a manager (`managerRoles`, or admin) |
222
+ | Matches `adminRouteParts` | User must be an admin |
223
+ | `/logout` | Calls `logout()` |
224
+
225
+ On any unmet requirement (or `/logout`), the middleware redirects to `notAllowedPath` (default `'/'`), which is always itself allowed so it can never cause a redirect loop.
223
226
 
224
227
  ## Runtime Plugin
225
228
 
@@ -233,7 +236,22 @@ const { $mongocampVersion } = useNuxtApp()
233
236
 
234
237
  ## Configuration
235
238
 
236
- The module's own config key is `nuxtUiMongocamp` (currently no options). The MongoCamp server is configured under the `mongocamp` key (provided by `@sfxcode/nuxt-mongocamp-server`):
239
+ The module's own config key is `nuxtUiMongocamp` — it configures the route middleware described above:
240
+
241
+ ```ts
242
+ nuxtUiMongocamp: {
243
+ useGlobalAuthMiddleware: true, // default: false
244
+ notAllowedPath: '/login', // default: '/'
245
+ managerRoles: ['support'], // default: []
246
+ securedRouteParts: ['/secured/**'], // default: []
247
+ managementRouteParts: ['/secured/manage/**'], // default: []
248
+ adminRouteParts: ['/secured/admin/**'], // default: []
249
+ }
250
+ ```
251
+
252
+ See [Configuration](https://sfxcode.github.io/nuxt-ui-mongocamp/guide/configuration) for details on each option.
253
+
254
+ The MongoCamp server is configured separately, under the `mongocamp` key (provided by `@sfxcode/nuxt-mongocamp-server`):
237
255
 
238
256
  ```ts
239
257
  mongocamp: {
package/dist/module.d.mts CHANGED
@@ -1,8 +1,34 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
 
3
3
  interface ModuleOptions {
4
+ useGlobalAuthMiddleware?: boolean;
5
+ /**
6
+ * Path the global auth middleware navigates to when a route is not allowed
7
+ * (not logged in, or logged in without the required role) — e.g. '/login'.
8
+ * Always treated as allowed by the middleware itself, so it can never cause a redirect loop.
9
+ */
10
+ notAllowedPath?: string;
11
+ /**
12
+ * Roles with management access
13
+ */
14
+ managerRoles: string[];
15
+ /**
16
+ * Routes that can only be accessed if the user is logged in
17
+ */
18
+ securedRouteParts: string[];
19
+ /**
20
+ * Routes that can only be accessed by manager users
21
+ */
22
+ managementRouteParts: string[];
23
+ /**
24
+ * Routes that can only be accessed by admin users
25
+ */
26
+ adminRouteParts: string[];
27
+ }
28
+ interface ModulePublicRuntimeConfig {
29
+ nuxtUiMongocampOptions: ModuleOptions;
4
30
  }
5
31
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
6
32
 
7
33
  export { _default as default };
8
- export type { ModuleOptions };
34
+ export type { ModuleOptions, ModulePublicRuntimeConfig };
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.16.0"
6
6
  },
7
- "version": "1.1.2",
7
+ "version": "1.1.4",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.2",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { defineNuxtModule, createResolver, addPlugin, addComponentsDir, addImportsDir } from '@nuxt/kit';
2
+ import { defu } from 'defu';
2
3
 
3
4
  const module$1 = defineNuxtModule({
4
5
  meta: {
@@ -9,7 +10,14 @@ const module$1 = defineNuxtModule({
9
10
  }
10
11
  },
11
12
  // Default configuration options of the Nuxt module
12
- defaults: {},
13
+ defaults: {
14
+ useGlobalAuthMiddleware: false,
15
+ notAllowedPath: "/",
16
+ managerRoles: [],
17
+ securedRouteParts: [],
18
+ managementRouteParts: [],
19
+ adminRouteParts: []
20
+ },
13
21
  moduleDependencies: {
14
22
  "@nuxt/ui": {},
15
23
  "unocss-nuxt-ui": {},
@@ -23,7 +31,11 @@ const module$1 = defineNuxtModule({
23
31
  }
24
32
  }
25
33
  },
26
- setup(_options, _nuxt) {
34
+ setup(options, nuxt) {
35
+ nuxt.options.runtimeConfig.public.nuxtUiMongocampOptions = defu(
36
+ nuxt.options.runtimeConfig.public.nuxtUiMongocampOptions,
37
+ options
38
+ );
27
39
  const { resolve } = createResolver(import.meta.url);
28
40
  const runtimeDir = resolve("./runtime");
29
41
  addPlugin(resolve(runtimeDir, "plugin"));
@@ -0,0 +1,6 @@
1
+ type __VLS_Props = {
2
+ bucketName: string;
3
+ };
4
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
5
+ declare const _default: typeof __VLS_export;
6
+ export default _default;
@@ -0,0 +1,362 @@
1
+ <script setup>
2
+ import { h, reactive, ref, resolveComponent, watch } from "vue";
3
+ import useMongocampCollection from "../composables/useMongocampCollection";
4
+ import { useMongocampBucket } from "../composables/useMongocampBucket";
5
+ import { useMongocampQuery } from "../composables/useMongocampQuery";
6
+ const props = defineProps({
7
+ bucketName: { type: String, required: true }
8
+ });
9
+ const { pagination, total } = useMongocampCollection();
10
+ const {
11
+ listFiles,
12
+ deleteFile,
13
+ updateFileInformation,
14
+ downloadFile,
15
+ downloadingFileIds,
16
+ uploadFile,
17
+ uploading,
18
+ fileActionInFlight
19
+ } = useMongocampBucket();
20
+ const { like } = useMongocampQuery();
21
+ const fileInputRef = ref(null);
22
+ function openFilePicker() {
23
+ fileInputRef.value?.click();
24
+ }
25
+ async function handleFileSelected(event) {
26
+ const input = event.target;
27
+ const file = input.files?.[0];
28
+ input.value = "";
29
+ if (!file) return;
30
+ const success = await uploadFile(props.bucketName, file);
31
+ if (success) await fetchFiles();
32
+ }
33
+ const UButton = resolveComponent("UButton");
34
+ const UTooltip = resolveComponent("UTooltip");
35
+ function withTooltip(text, node) {
36
+ return h(UTooltip, { text }, { default: () => node });
37
+ }
38
+ function sortHeader(column, label) {
39
+ const isSorted = column.getIsSorted();
40
+ return h(UButton, {
41
+ color: "neutral",
42
+ variant: "ghost",
43
+ label,
44
+ icon: isSorted === "asc" ? "i-lucide-arrow-up-narrow-wide" : isSorted === "desc" ? "i-lucide-arrow-down-wide-narrow" : "i-lucide-arrow-up-down",
45
+ class: "-mx-2.5",
46
+ onClick: () => column.toggleSorting(isSorted === "asc")
47
+ });
48
+ }
49
+ function sortingToMongoSort(s) {
50
+ return s.map((col) => col.desc ? `-${col.id}` : col.id);
51
+ }
52
+ const BYTE_UNITS = ["B", "KB", "MB", "GB", "TB"];
53
+ function formatBytes(length) {
54
+ if (!length) return "0 B";
55
+ const exponent = Math.min(Math.floor(Math.log(length) / Math.log(1024)), BYTE_UNITS.length - 1);
56
+ const value = length / 1024 ** exponent;
57
+ return `${exponent === 0 ? value : value.toFixed(1)} ${BYTE_UNITS[exponent]}`;
58
+ }
59
+ function formatDate(value) {
60
+ try {
61
+ return new Date(value).toLocaleString();
62
+ } catch {
63
+ return String(value);
64
+ }
65
+ }
66
+ const detailOpen = ref(false);
67
+ const detailContent = ref("");
68
+ function openMetadataDetail(metadata) {
69
+ detailContent.value = JSON.stringify(metadata, null, 2);
70
+ detailOpen.value = true;
71
+ }
72
+ function makeMetadataCell() {
73
+ return ({ row }) => {
74
+ const metadata = row.original.metadata ?? {};
75
+ const keys = Object.keys(metadata);
76
+ if (keys.length === 0) return h("span", { class: "text-dimmed" }, "\u2014");
77
+ return withTooltip("View metadata", h(UButton, {
78
+ "icon": "i-lucide-braces",
79
+ "color": "neutral",
80
+ "variant": "ghost",
81
+ "size": "xs",
82
+ "label": `${keys.length} ${keys.length === 1 ? "key" : "keys"}`,
83
+ "aria-label": "View metadata",
84
+ "onClick": () => openMetadataDetail(metadata)
85
+ }));
86
+ };
87
+ }
88
+ const isRenameModalOpen = ref(false);
89
+ const fileToRename = ref(void 0);
90
+ const renameData = ref({ filename: "", metadata: [] });
91
+ const renameSchema = reactive([
92
+ {
93
+ $formkit: "nuxtUIInput",
94
+ name: "filename",
95
+ label: "Filename",
96
+ validation: "required"
97
+ },
98
+ {
99
+ $formkit: "nuxtUIRepeater",
100
+ name: "metadata",
101
+ label: "Metadata",
102
+ children: [
103
+ { $formkit: "nuxtUIInput", name: "key", label: "Key" },
104
+ { $formkit: "nuxtUIInput", name: "value", label: "Value" }
105
+ ]
106
+ }
107
+ ]);
108
+ function openRename(file) {
109
+ fileToRename.value = file;
110
+ renameData.value = {
111
+ filename: file.filename,
112
+ metadata: Object.entries(file.metadata ?? {}).map(([key, value]) => ({ key, value }))
113
+ };
114
+ isRenameModalOpen.value = true;
115
+ }
116
+ async function handleRenameSave() {
117
+ if (!fileToRename.value) return;
118
+ const metadata = {};
119
+ for (const entry of renameData.value.metadata) {
120
+ if (entry.key) metadata[entry.key] = entry.value;
121
+ }
122
+ const success = await updateFileInformation(props.bucketName, fileToRename.value.id, {
123
+ filename: renameData.value.filename,
124
+ metadata
125
+ });
126
+ if (success) {
127
+ isRenameModalOpen.value = false;
128
+ await fetchFiles();
129
+ }
130
+ }
131
+ const isDeleteModalOpen = ref(false);
132
+ const fileToDelete = ref(void 0);
133
+ function confirmDeleteFile(file) {
134
+ fileToDelete.value = file;
135
+ isDeleteModalOpen.value = true;
136
+ }
137
+ async function handleDeleteFile() {
138
+ if (!fileToDelete.value) return;
139
+ const success = await deleteFile(props.bucketName, fileToDelete.value.id);
140
+ if (success) {
141
+ isDeleteModalOpen.value = false;
142
+ await fetchFiles();
143
+ }
144
+ }
145
+ function makeActionsColumn() {
146
+ return {
147
+ id: "actions",
148
+ header: "",
149
+ cell: ({ row }) => {
150
+ const file = row.original;
151
+ return h("div", { class: "flex gap-1 justify-end" }, [
152
+ withTooltip("Download file", h(UButton, {
153
+ "icon": "i-lucide-download",
154
+ "color": "neutral",
155
+ "variant": "ghost",
156
+ "size": "sm",
157
+ "aria-label": "Download file",
158
+ "loading": downloadingFileIds.value.has(file.id),
159
+ "onClick": () => downloadFile(props.bucketName, file.id)
160
+ })),
161
+ withTooltip("Rename / edit metadata", h(UButton, {
162
+ "icon": "i-lucide-pencil",
163
+ "color": "neutral",
164
+ "variant": "ghost",
165
+ "size": "sm",
166
+ "aria-label": "Rename / edit metadata",
167
+ "loading": fileActionInFlight.value.has(file.id),
168
+ "onClick": () => openRename(file)
169
+ })),
170
+ withTooltip("Delete file", h(UButton, {
171
+ "icon": "i-lucide-trash-2",
172
+ "color": "error",
173
+ "variant": "ghost",
174
+ "size": "sm",
175
+ "aria-label": "Delete file",
176
+ "loading": fileActionInFlight.value.has(file.id),
177
+ "onClick": () => confirmDeleteFile(file)
178
+ }))
179
+ ]);
180
+ }
181
+ };
182
+ }
183
+ const columns = ref([
184
+ {
185
+ accessorKey: "filename",
186
+ header: ({ column }) => sortHeader(column, "Filename"),
187
+ cell: ({ row }) => h("span", row.original.filename)
188
+ },
189
+ {
190
+ accessorKey: "length",
191
+ header: ({ column }) => sortHeader(column, "Size"),
192
+ cell: ({ row }) => h("span", formatBytes(row.original.length))
193
+ },
194
+ {
195
+ accessorKey: "uploadDate",
196
+ header: ({ column }) => sortHeader(column, "Uploaded"),
197
+ cell: ({ row }) => h("span", formatDate(row.original.uploadDate))
198
+ },
199
+ {
200
+ id: "metadata",
201
+ header: "Metadata",
202
+ cell: makeMetadataCell()
203
+ },
204
+ makeActionsColumn()
205
+ ]);
206
+ const files = ref([]);
207
+ const loading = ref(false);
208
+ const filterText = ref("");
209
+ const sorting = ref([]);
210
+ const isInitializing = ref(false);
211
+ let filterTimer;
212
+ function buildLuceneFilter(term) {
213
+ const t = term.trim();
214
+ return t ? like("filename", t) : void 0;
215
+ }
216
+ function onFilterInput() {
217
+ clearTimeout(filterTimer);
218
+ filterTimer = setTimeout(() => {
219
+ pagination.value.pageIndex = 1;
220
+ fetchFiles();
221
+ }, 300);
222
+ }
223
+ watch(sorting, () => {
224
+ if (isInitializing.value) return;
225
+ pagination.value.pageIndex = 1;
226
+ fetchFiles();
227
+ });
228
+ async function fetchFiles() {
229
+ loading.value = true;
230
+ try {
231
+ const result = await listFiles(props.bucketName, {
232
+ rowsPerPage: pagination.value.pageSize,
233
+ page: pagination.value.pageIndex,
234
+ sort: sorting.value.length ? sortingToMongoSort(sorting.value).join(",") : void 0,
235
+ filter: buildLuceneFilter(filterText.value)
236
+ });
237
+ total.value = result.total;
238
+ files.value = result.files;
239
+ } finally {
240
+ loading.value = false;
241
+ }
242
+ }
243
+ async function init() {
244
+ isInitializing.value = true;
245
+ sorting.value = [];
246
+ pagination.value.pageIndex = 1;
247
+ filterText.value = "";
248
+ files.value = [];
249
+ await fetchFiles();
250
+ isInitializing.value = false;
251
+ }
252
+ watch(() => props.bucketName, init, { immediate: true });
253
+ </script>
254
+
255
+ <template>
256
+ <div class="flex flex-col gap-4">
257
+ <div class="flex items-center justify-between gap-4">
258
+ <UInput
259
+ v-model="filterText"
260
+ icon="i-lucide-search"
261
+ placeholder="Filter by filename..."
262
+ size="sm"
263
+ class="flex-1 max-w-xs"
264
+ @input="onFilterInput"
265
+ />
266
+ <div class="flex items-center gap-2">
267
+ <span class="text-sm text-gray-500 dark:text-gray-400 shrink-0">
268
+ {{ total }} files
269
+ </span>
270
+ <UTooltip text="Upload file">
271
+ <UButton
272
+ icon="i-lucide-upload"
273
+ color="primary"
274
+ variant="ghost"
275
+ size="sm"
276
+ :loading="uploading"
277
+ aria-label="Upload file"
278
+ @click="openFilePicker"
279
+ />
280
+ </UTooltip>
281
+ <input
282
+ ref="fileInputRef"
283
+ type="file"
284
+ class="hidden"
285
+ @change="handleFileSelected"
286
+ >
287
+ <UTooltip text="Reload">
288
+ <UButton
289
+ icon="i-lucide-refresh-cw"
290
+ color="neutral"
291
+ variant="ghost"
292
+ :loading="loading"
293
+ aria-label="Reload"
294
+ @click="init"
295
+ />
296
+ </UTooltip>
297
+ <UPagination
298
+ v-model:page="pagination.pageIndex"
299
+ :total="total"
300
+ :items-per-page="pagination.pageSize"
301
+ @update:page="fetchFiles"
302
+ />
303
+ </div>
304
+ </div>
305
+ <UTable
306
+ v-model:sorting="sorting"
307
+ :sorting-options="{ manualSorting: true }"
308
+ :data="files"
309
+ :columns="columns"
310
+ :loading="loading"
311
+ />
312
+
313
+ <UModal
314
+ v-model:open="detailOpen"
315
+ title="Metadata"
316
+ >
317
+ <template #body>
318
+ <pre class="text-xs overflow-auto max-h-[60vh] whitespace-pre-wrap break-all">{{ detailContent }}</pre>
319
+ </template>
320
+ </UModal>
321
+
322
+ <UModal
323
+ v-model:open="isRenameModalOpen"
324
+ title="Rename / edit metadata"
325
+ :ui="{ footer: 'justify-end' }"
326
+ >
327
+ <template #body>
328
+ <FUDataEdit
329
+ :data="renameData"
330
+ :schema="renameSchema"
331
+ submit-label="Save"
332
+ submit-icon="i-lucide-save"
333
+ @data-saved="handleRenameSave"
334
+ />
335
+ </template>
336
+ </UModal>
337
+
338
+ <UModal
339
+ v-model:open="isDeleteModalOpen"
340
+ title="Delete File"
341
+ :ui="{ footer: 'justify-end' }"
342
+ >
343
+ <template #body>
344
+ <p>Are you sure you want to delete this file? This action cannot be undone.</p>
345
+ </template>
346
+ <template #footer>
347
+ <UButton
348
+ label="Cancel"
349
+ color="neutral"
350
+ variant="ghost"
351
+ @click="isDeleteModalOpen = false"
352
+ />
353
+ <UButton
354
+ label="Delete"
355
+ color="error"
356
+ icon="i-lucide-trash-2"
357
+ @click="handleDeleteFile"
358
+ />
359
+ </template>
360
+ </UModal>
361
+ </div>
362
+ </template>
@@ -0,0 +1,6 @@
1
+ type __VLS_Props = {
2
+ bucketName: string;
3
+ };
4
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
5
+ declare const _default: typeof __VLS_export;
6
+ export default _default;
@@ -1,6 +1,7 @@
1
1
  type __VLS_Props = {
2
2
  infoPath?: string;
3
3
  dataPath?: string;
4
+ bucketFilesPath?: string;
4
5
  };
5
6
  declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
6
7
  declare const _default: typeof __VLS_export;
@@ -3,7 +3,8 @@ import { h, ref, resolveComponent } from "vue";
3
3
  import { useMongocampApi, useMongocampBucket } from "#imports";
4
4
  const props = defineProps({
5
5
  infoPath: { type: String, required: false },
6
- dataPath: { type: String, required: false }
6
+ dataPath: { type: String, required: false },
7
+ bucketFilesPath: { type: String, required: false }
7
8
  });
8
9
  const { collectionApi } = useMongocampApi();
9
10
  const { isBucketCollection, bucketNameFor, bucketActionInFlight, clearBucket, deleteBucket } = useMongocampBucket();
@@ -118,6 +119,14 @@ const columns = [
118
119
  if (isBucketCollection(row.original.name)) {
119
120
  const bucketName = bucketNameFor(row.original.name);
120
121
  buttons.push(
122
+ withTooltip("Browse files", h(UButton, {
123
+ "icon": "i-lucide-folder-open",
124
+ "color": "neutral",
125
+ "variant": "ghost",
126
+ "size": "sm",
127
+ "aria-label": "Browse files",
128
+ "to": `${props.bucketFilesPath ?? "/secured/admin/buckets"}/${bucketName}`
129
+ })),
121
130
  withTooltip("Clear bucket", h(UButton, {
122
131
  "icon": "i-lucide-eraser",
123
132
  "color": "warning",
@@ -1,6 +1,7 @@
1
1
  type __VLS_Props = {
2
2
  infoPath?: string;
3
3
  dataPath?: string;
4
+ bucketFilesPath?: string;
4
5
  };
5
6
  declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
6
7
  declare const _default: typeof __VLS_export;
@@ -1,4 +1,19 @@
1
- import type { BucketInformation } from '@sfxcode/nuxt-mongocamp-server';
1
+ import type { BucketInformation, FileInformation } from '@sfxcode/nuxt-mongocamp-server';
2
+ export interface ListFilesOptions {
3
+ filter?: string;
4
+ sort?: string;
5
+ projection?: string;
6
+ page?: number;
7
+ rowsPerPage?: number;
8
+ }
9
+ export interface ListFilesResult {
10
+ files: FileInformation[];
11
+ total: number;
12
+ }
13
+ export interface UpdateFileInformationOptions {
14
+ filename?: string;
15
+ metadata?: Record<string, string>;
16
+ }
2
17
  export declare function useMongocampBucket(): {
3
18
  isBucketCollection: (collectionName: string) => boolean;
4
19
  bucketNameFor: (collectionName: string) => string;
@@ -8,6 +23,10 @@ export declare function useMongocampBucket(): {
8
23
  downloadFile: (collectionName: string, fileId: string) => Promise<void>;
9
24
  uploadFile: (collectionName: string, file: File) => Promise<boolean>;
10
25
  bucketActionInFlight: import("vue").Ref<Set<string> & Omit<Set<string>, keyof Set<any>>, Set<string> | (Set<string> & Omit<Set<string>, keyof Set<any>>)>;
26
+ fileActionInFlight: import("vue").Ref<Set<string> & Omit<Set<string>, keyof Set<any>>, Set<string> | (Set<string> & Omit<Set<string>, keyof Set<any>>)>;
27
+ listFiles: (bucketName: string, options?: ListFilesOptions) => Promise<ListFilesResult>;
28
+ deleteFile: (bucketName: string, fileId: string) => Promise<boolean>;
29
+ updateFileInformation: (bucketName: string, fileId: string, options: UpdateFileInformationOptions) => Promise<boolean>;
11
30
  listBuckets: () => Promise<string[]>;
12
31
  getBucketInfo: (bucketName: string) => Promise<BucketInformation>;
13
32
  clearBucket: (bucketName: string) => Promise<boolean>;
@@ -24,6 +24,7 @@ export function useMongocampBucket() {
24
24
  const downloadingFileIds = ref(/* @__PURE__ */ new Set());
25
25
  const uploading = ref(false);
26
26
  const bucketActionInFlight = ref(/* @__PURE__ */ new Set());
27
+ const fileActionInFlight = ref(/* @__PURE__ */ new Set());
27
28
  function isBucketCollection(collectionName) {
28
29
  return BUCKET_COLLECTION_SUFFIX.test(collectionName);
29
30
  }
@@ -60,6 +61,49 @@ export function useMongocampBucket() {
60
61
  uploading.value = false;
61
62
  }
62
63
  }
64
+ async function listFiles(bucketName, options = {}) {
65
+ const res = await fileApi.listFilesRaw({
66
+ bucketName,
67
+ filter: options.filter,
68
+ sort: options.sort,
69
+ projection: options.projection,
70
+ page: options.page,
71
+ rowsPerPage: options.rowsPerPage
72
+ });
73
+ const total = +(res.raw.headers.get("x-pagination-count-rows") ?? 0);
74
+ const files = await res.value();
75
+ return { files, total };
76
+ }
77
+ async function deleteFile(bucketName, fileId) {
78
+ fileActionInFlight.value.add(fileId);
79
+ try {
80
+ const result = await fileApi.deleteFile({ bucketName, fileId });
81
+ toast.add({ title: "File deleted", description: "The file was deleted.", color: "success" });
82
+ return result.wasAcknowledged;
83
+ } catch {
84
+ toast.add({ title: "Delete failed", description: "Could not delete the file.", color: "error" });
85
+ return false;
86
+ } finally {
87
+ fileActionInFlight.value.delete(fileId);
88
+ }
89
+ }
90
+ async function updateFileInformation(bucketName, fileId, options) {
91
+ fileActionInFlight.value.add(fileId);
92
+ try {
93
+ const result = await fileApi.updateFileInformation({
94
+ bucketName,
95
+ fileId,
96
+ updateFileInformationRequest: { filename: options.filename, metadata: options.metadata }
97
+ });
98
+ toast.add({ title: "File updated", description: "The file information was updated.", color: "success" });
99
+ return result.wasAcknowledged;
100
+ } catch {
101
+ toast.add({ title: "Update failed", description: "Could not update the file information.", color: "error" });
102
+ return false;
103
+ } finally {
104
+ fileActionInFlight.value.delete(fileId);
105
+ }
106
+ }
63
107
  async function listBuckets() {
64
108
  return bucketApi.listBuckets();
65
109
  }
@@ -101,6 +145,10 @@ export function useMongocampBucket() {
101
145
  downloadFile,
102
146
  uploadFile,
103
147
  bucketActionInFlight,
148
+ fileActionInFlight,
149
+ listFiles,
150
+ deleteFile,
151
+ updateFileInformation,
104
152
  listBuckets,
105
153
  getBucketInfo,
106
154
  clearBucket,
@@ -0,0 +1,7 @@
1
+ export declare function useMongocampRoles(): {
2
+ isLoggedIn: import("vue").ComputedRef<boolean>;
3
+ isAdmin: import("vue").ComputedRef<boolean>;
4
+ isManager: import("vue").ComputedRef<boolean>;
5
+ notAllowedPath: string;
6
+ isAllowedPathForRoute: (route: string) => boolean;
7
+ };
@@ -0,0 +1,37 @@
1
+ import { useRuntimeConfig } from "#app";
2
+ import { minimatch } from "minimatch";
3
+ import { useMongocampAuth, useMongocampStorage } from "#imports";
4
+ import { computed } from "vue";
5
+ export function useMongocampRoles() {
6
+ const config = useRuntimeConfig();
7
+ const { isLoggedIn } = useMongocampAuth();
8
+ const state = useMongocampStorage();
9
+ const notAllowedPath = config.public.nuxtUiMongocampOptions.notAllowedPath ?? "/";
10
+ const managerRoles = config.public.nuxtUiMongocampOptions.managerRoles ?? [];
11
+ const securedRouteParts = config.public.nuxtUiMongocampOptions.securedRouteParts ?? [];
12
+ const managementRouteParts = config.public.nuxtUiMongocampOptions.managementRouteParts ?? [];
13
+ const adminRouteParts = config.public.nuxtUiMongocampOptions.adminRouteParts ?? [];
14
+ const isAdmin = computed(() => state.value?.profile?.isAdmin ?? false);
15
+ const roles = computed(() => state.value?.profile?.roles ?? []);
16
+ function matchesAnyRole(allowedRoles) {
17
+ return allowedRoles.some((role) => roles.value.includes(role));
18
+ }
19
+ const isManager = computed(() => isAdmin.value || matchesAnyRole(managerRoles));
20
+ function matchesAnyPattern(route, patterns) {
21
+ return patterns.some((pattern) => minimatch(route, pattern) || minimatch(`${route}/`, pattern));
22
+ }
23
+ function isAllowedPathForRoute(route) {
24
+ if (route === notAllowedPath) {
25
+ return true;
26
+ }
27
+ if (!isLoggedIn.value && matchesAnyPattern(route, securedRouteParts)) {
28
+ return false;
29
+ } else if (!isManager.value && matchesAnyPattern(route, managementRouteParts)) {
30
+ return false;
31
+ } else if (!isAdmin.value && matchesAnyPattern(route, adminRouteParts)) {
32
+ return false;
33
+ }
34
+ return true;
35
+ }
36
+ return { isLoggedIn, isAdmin, isManager, notAllowedPath, isAllowedPathForRoute };
37
+ }
@@ -1,20 +1,24 @@
1
- import { defineNuxtPlugin, addRouteMiddleware, navigateTo, useAsyncData } from "#app";
2
- import { useMongocampStorage, useMongocampApi, useMongocampAuth } from "#imports";
1
+ import { defineNuxtPlugin, addRouteMiddleware, navigateTo, useAsyncData, useRuntimeConfig } from "#app";
2
+ import { useMongocampApi, useMongocampAuth } from "#imports";
3
+ import { useMongocampRoles } from "./composables/useMongocampRoles.js";
3
4
  export default defineNuxtPlugin(async (_nuxtApp) => {
4
- const { logout, isLoggedIn } = useMongocampAuth();
5
+ const { logout } = useMongocampAuth();
5
6
  const { informationApi } = useMongocampApi();
6
- const state = useMongocampStorage();
7
+ const { notAllowedPath, isAllowedPathForRoute } = useMongocampRoles();
8
+ const config = useRuntimeConfig();
9
+ const useGlobalAuthMiddleware = config.public.nuxtUiMongocampOptions.useGlobalAuthMiddleware ?? false;
7
10
  const { data: version } = await useAsyncData("version", () => informationApi.version());
8
- addRouteMiddleware("global-auth", (to) => {
9
- if ((to.path.startsWith("/admin") || to.path.startsWith("/secured/admin")) && (!isLoggedIn.value || !state.value.profile.isAdmin)) {
10
- return navigateTo("/secured");
11
- } else if (to.path.startsWith("/secured") && !isLoggedIn.value) {
12
- return navigateTo("/");
13
- } else if (to.path === "/logout") {
14
- logout();
15
- return navigateTo("/");
16
- }
17
- }, { global: true });
11
+ if (useGlobalAuthMiddleware) {
12
+ addRouteMiddleware("global-auth", (to) => {
13
+ if (to.path === "/logout") {
14
+ logout();
15
+ return navigateTo(notAllowedPath);
16
+ }
17
+ if (!isAllowedPathForRoute(to.path)) {
18
+ return navigateTo(notAllowedPath);
19
+ }
20
+ }, { global: true });
21
+ }
18
22
  return {
19
23
  provide: {
20
24
  mongocampVersion: version
package/dist/types.d.mts CHANGED
@@ -1,3 +1,9 @@
1
+ import type { ModulePublicRuntimeConfig } from './module.mjs'
2
+
3
+ declare module '@nuxt/schema' {
4
+ interface PublicRuntimeConfig extends ModulePublicRuntimeConfig {}
5
+ }
6
+
1
7
  export { default } from './module.mjs'
2
8
 
3
- export { type ModuleOptions } from './module.mjs'
9
+ export { type ModuleOptions, type ModulePublicRuntimeConfig } from './module.mjs'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sfxcode/nuxt-ui-mongocamp",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "A Nuxt module that wraps @sfxcode/nuxt-mongocamp-server with ready-made UI components, composables, and a runtime plugin",
5
5
  "repository": "sfxcode/nuxt-ui-mongocamp",
6
6
  "homepage": "https://sfxcode.github.io/nuxt-ui-mongocamp/",
@@ -46,8 +46,9 @@
46
46
  "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt prepare playground",
47
47
  "release": "npm run lint && npm run test && npm run prepack && changelogen --patch --release && npm publish && git push --follow-tags",
48
48
  "lint": "eslint .",
49
- "test": "vitest run",
49
+ "test": "vitest run --project unit --project components",
50
50
  "test:watch": "vitest watch",
51
+ "test:e2e:auth": "vitest run --project e2e-auth",
51
52
  "test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
52
53
  "docs:dev": "vitepress dev docs",
53
54
  "docs:build": "vitepress build docs",
@@ -59,6 +60,8 @@
59
60
  "@nuxt/ui": "4.9.0",
60
61
  "@sfxcode/nuxt-mongocamp-server": "^1.4.4",
61
62
  "@sfxcode/nuxt-ui-formkit": "^1.2.6",
63
+ "defu": "^6.1.7",
64
+ "minimatch": "^10.2.5",
62
65
  "unocss-nuxt-ui": "^1.2.2"
63
66
  },
64
67
  "devDependencies": {
@@ -67,9 +70,12 @@
67
70
  "@nuxt/module-builder": "^1.0.2",
68
71
  "@nuxt/schema": "^4.4.8",
69
72
  "@nuxt/test-utils": "^4.0.3",
73
+ "@playwright/test": "^1.43.1",
70
74
  "@types/node": "latest",
75
+ "@vue/test-utils": "^2.4.2",
71
76
  "changelogen": "^0.6.2",
72
77
  "eslint": "^10.7.0",
78
+ "happy-dom": ">=20.0.11",
73
79
  "nuxt": "^4.4.8",
74
80
  "tailwindcss": "^4.3.2",
75
81
  "typescript": "~6.0.3",