nuxt-auto-crud 1.2.2 → 1.4.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 (31) hide show
  1. package/README.md +189 -90
  2. package/dist/module.d.mts +49 -1
  3. package/dist/module.json +1 -1
  4. package/dist/module.mjs +24 -1
  5. package/dist/runtime/server/api/[model]/[id].delete.d.ts +1 -1
  6. package/dist/runtime/server/api/[model]/[id].delete.js +20 -2
  7. package/dist/runtime/server/api/[model]/[id].get.d.ts +1 -1
  8. package/dist/runtime/server/api/[model]/[id].get.js +21 -4
  9. package/dist/runtime/server/api/[model]/[id].patch.d.ts +1 -1
  10. package/dist/runtime/server/api/[model]/[id].patch.js +29 -5
  11. package/dist/runtime/server/api/[model]/index.get.js +25 -4
  12. package/dist/runtime/server/api/[model]/index.post.d.ts +1 -1
  13. package/dist/runtime/server/api/[model]/index.post.js +23 -8
  14. package/dist/runtime/server/utils/auth.d.ts +2 -0
  15. package/dist/runtime/server/utils/auth.js +39 -0
  16. package/dist/runtime/server/utils/config.d.ts +2 -0
  17. package/dist/runtime/server/utils/config.js +4 -0
  18. package/dist/runtime/server/utils/jwt.d.ts +2 -0
  19. package/dist/runtime/server/utils/jwt.js +19 -0
  20. package/dist/runtime/server/utils/modelMapper.d.ts +31 -0
  21. package/dist/runtime/server/utils/modelMapper.js +38 -0
  22. package/package.json +20 -10
  23. package/src/runtime/server/api/[model]/[id].delete.ts +29 -3
  24. package/src/runtime/server/api/[model]/[id].get.ts +29 -5
  25. package/src/runtime/server/api/[model]/[id].patch.ts +40 -9
  26. package/src/runtime/server/api/[model]/index.get.ts +33 -5
  27. package/src/runtime/server/api/[model]/index.post.ts +32 -15
  28. package/src/runtime/server/utils/auth.ts +55 -0
  29. package/src/runtime/server/utils/config.ts +6 -0
  30. package/src/runtime/server/utils/jwt.ts +23 -0
  31. package/src/runtime/server/utils/modelMapper.ts +83 -0
@@ -1,14 +1,29 @@
1
- import { eventHandler, getRouterParams, readBody } from "h3";
2
- import { getTableForModel } from "../../utils/modelMapper.js";
1
+ import { eventHandler, getRouterParams, readBody, createError } from "h3";
2
+ import { getTableForModel, filterHiddenFields, filterUpdatableFields, filterPublicColumns } from "../../utils/modelMapper.js";
3
3
  import { useDrizzle } from "#site/drizzle";
4
+ import { useAutoCrudConfig } from "../../utils/config.js";
5
+ import { checkAdminAccess } from "../../utils/auth.js";
4
6
  export default eventHandler(async (event) => {
7
+ const { resources } = useAutoCrudConfig();
5
8
  const { model } = getRouterParams(event);
9
+ const isAdmin = await checkAdminAccess(event, model, "create");
10
+ if (!isAdmin) {
11
+ const resourceConfig = resources?.[model];
12
+ const isPublic = resourceConfig?.public === true || Array.isArray(resourceConfig?.public) && resourceConfig.public.includes("create");
13
+ if (!isPublic) {
14
+ throw createError({
15
+ statusCode: 401,
16
+ message: "Unauthorized"
17
+ });
18
+ }
19
+ }
6
20
  const table = getTableForModel(model);
7
21
  const body = await readBody(event);
8
- const values = {
9
- ...body,
10
- createdAt: /* @__PURE__ */ new Date()
11
- };
12
- const record = await useDrizzle().insert(table).values(values).returning().get();
13
- return record;
22
+ const payload = filterUpdatableFields(model, body);
23
+ const newRecord = await useDrizzle().insert(table).values(payload).returning().get();
24
+ if (isAdmin) {
25
+ return filterHiddenFields(model, newRecord);
26
+ } else {
27
+ return filterPublicColumns(model, newRecord);
28
+ }
14
29
  });
@@ -0,0 +1,2 @@
1
+ import type { H3Event } from 'h3';
2
+ export declare function checkAdminAccess(event: H3Event, model: string, action: string): Promise<boolean>;
@@ -0,0 +1,39 @@
1
+ import { createError } from "h3";
2
+ import { useAutoCrudConfig } from "./config.js";
3
+ import { verifyJwtToken } from "./jwt.js";
4
+ export async function checkAdminAccess(event, model, action) {
5
+ const { auth } = useAutoCrudConfig();
6
+ if (!auth?.enabled) {
7
+ return true;
8
+ }
9
+ if (auth.type === "jwt") {
10
+ if (!auth.jwtSecret) {
11
+ console.warn("JWT Secret is not configured but auth type is jwt");
12
+ return false;
13
+ }
14
+ return verifyJwtToken(event, auth.jwtSecret);
15
+ }
16
+ if (typeof requireUserSession !== "function") {
17
+ throw new TypeError("requireUserSession is not available");
18
+ }
19
+ try {
20
+ await requireUserSession(event);
21
+ if (auth.authorization) {
22
+ if (event.context.ability) {
23
+ const can = event.context.ability.can(action, model);
24
+ if (!can) {
25
+ throw createError({
26
+ statusCode: 403,
27
+ message: "Forbidden"
28
+ });
29
+ }
30
+ }
31
+ }
32
+ return true;
33
+ } catch (e) {
34
+ if (e.statusCode === 403) {
35
+ throw e;
36
+ }
37
+ return false;
38
+ }
39
+ }
@@ -0,0 +1,2 @@
1
+ import type { ModuleOptions } from '../../../types.js';
2
+ export declare const useAutoCrudConfig: () => ModuleOptions;
@@ -0,0 +1,4 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ export const useAutoCrudConfig = () => {
3
+ return useRuntimeConfig().autoCrud;
4
+ };
@@ -0,0 +1,2 @@
1
+ import type { H3Event } from 'h3';
2
+ export declare function verifyJwtToken(event: H3Event, secret: string): Promise<boolean>;
@@ -0,0 +1,19 @@
1
+ import { jwtVerify } from "jose";
2
+ import { getRequestHeader } from "h3";
3
+ export async function verifyJwtToken(event, secret) {
4
+ const authHeader = getRequestHeader(event, "Authorization");
5
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
6
+ return false;
7
+ }
8
+ const token = authHeader.split(" ")[1];
9
+ if (!token) {
10
+ return false;
11
+ }
12
+ try {
13
+ const secretKey = new TextEncoder().encode(secret);
14
+ await jwtVerify(token, secretKey);
15
+ return true;
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
@@ -9,6 +9,11 @@ import type { SQLiteTable } from 'drizzle-orm/sqlite-core';
9
9
  * }
10
10
  */
11
11
  export declare const customUpdatableFields: Record<string, string[]>;
12
+ /**
13
+ * Custom hidden fields configuration (optional)
14
+ * Only define here if you want to override the default hidden fields
15
+ */
16
+ export declare const customHiddenFields: Record<string, string[]>;
12
17
  /**
13
18
  * Auto-generated model table map
14
19
  * Automatically includes all tables from schema
@@ -53,3 +58,29 @@ export declare function getModelPluralName(modelName: string): string;
53
58
  * @returns Array of model names
54
59
  */
55
60
  export declare function getAvailableModels(): string[];
61
+ /**
62
+ * Gets the hidden fields for a model
63
+ * @param modelName - The name of the model
64
+ * @returns Array of field names that should be hidden
65
+ */
66
+ export declare function getHiddenFields(modelName: string): string[];
67
+ /**
68
+ * Gets the public columns for a model
69
+ * @param modelName - The name of the model
70
+ * @returns Array of field names that are public (or undefined if all are public)
71
+ */
72
+ export declare function getPublicColumns(modelName: string): string[] | undefined;
73
+ /**
74
+ * Filters an object to only include public columns (if configured)
75
+ * @param modelName - The name of the model
76
+ * @param data - The data object to filter
77
+ * @returns Filtered object
78
+ */
79
+ export declare function filterPublicColumns(modelName: string, data: Record<string, unknown>): Record<string, unknown>;
80
+ /**
81
+ * Filters an object to exclude hidden fields
82
+ * @param modelName - The name of the model
83
+ * @param data - The data object to filter
84
+ * @returns Filtered object without hidden fields
85
+ */
86
+ export declare function filterHiddenFields(modelName: string, data: Record<string, unknown>): Record<string, unknown>;
@@ -3,11 +3,16 @@ import pluralize from "pluralize";
3
3
  import { pascalCase } from "scule";
4
4
  import { getTableColumns as getDrizzleTableColumns } from "drizzle-orm";
5
5
  import { createError } from "h3";
6
+ import { useRuntimeConfig } from "#imports";
6
7
  const PROTECTED_FIELDS = ["id", "createdAt", "created_at"];
8
+ const HIDDEN_FIELDS = ["password", "secret", "token"];
7
9
  export const customUpdatableFields = {
8
10
  // Add custom field restrictions here if needed
9
11
  // By default, all fields except PROTECTED_FIELDS are updatable
10
12
  };
13
+ export const customHiddenFields = {
14
+ // Add custom hidden fields here if needed
15
+ };
11
16
  function buildModelTableMap() {
12
17
  const tableMap = {};
13
18
  for (const [key, value] of Object.entries(schema)) {
@@ -72,3 +77,36 @@ export function getModelPluralName(modelName) {
72
77
  export function getAvailableModels() {
73
78
  return Object.keys(modelTableMap);
74
79
  }
80
+ export function getHiddenFields(modelName) {
81
+ if (customHiddenFields[modelName]) {
82
+ return customHiddenFields[modelName];
83
+ }
84
+ return HIDDEN_FIELDS;
85
+ }
86
+ export function getPublicColumns(modelName) {
87
+ const { resources } = useRuntimeConfig().autoCrud;
88
+ return resources?.[modelName]?.publicColumns;
89
+ }
90
+ export function filterPublicColumns(modelName, data) {
91
+ const publicColumns = getPublicColumns(modelName);
92
+ if (!publicColumns) {
93
+ return filterHiddenFields(modelName, data);
94
+ }
95
+ const filtered = {};
96
+ for (const [key, value] of Object.entries(data)) {
97
+ if (publicColumns.includes(key) && !getHiddenFields(modelName).includes(key)) {
98
+ filtered[key] = value;
99
+ }
100
+ }
101
+ return filtered;
102
+ }
103
+ export function filterHiddenFields(modelName, data) {
104
+ const hiddenFields = getHiddenFields(modelName);
105
+ const filtered = {};
106
+ for (const [key, value] of Object.entries(data)) {
107
+ if (!hiddenFields.includes(key)) {
108
+ filtered[key] = value;
109
+ }
110
+ }
111
+ return filtered;
112
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-auto-crud",
3
- "version": "1.2.2",
3
+ "version": "1.4.0",
4
4
  "description": "Exposes RESTful CRUD APIs for your Nuxt app based solely on your database migrations.",
5
5
  "author": "Cliford Pereira",
6
6
  "license": "MIT",
@@ -35,24 +35,27 @@
35
35
  ],
36
36
  "scripts": {
37
37
  "prepack": "nuxt-module-build build",
38
- "dev": "npm run dev:prepare && nuxi dev playground",
39
- "dev:build": "nuxi build playground",
40
- "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
38
+ "dev": "npm run dev:prepare && nuxi dev playground-fullstack",
39
+ "dev:build": "nuxi build playground-fullstack",
40
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground-fullstack",
41
41
  "release": "npm run lint && npm run test && npm run prepack && changelogen --release && npm publish && git push --follow-tags",
42
42
  "lint": "eslint .",
43
43
  "test": "vitest run",
44
+ "test:api": "node scripts/test-api.mjs",
44
45
  "test:watch": "vitest watch",
45
- "test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
46
+ "test:types": "vue-tsc --noEmit && cd playground-fullstack && vue-tsc --noEmit",
46
47
  "link": "npm link"
47
48
  },
48
49
  "dependencies": {
49
50
  "@nuxt/kit": "^4.2.1",
50
- "@types/pluralize": "^0.0.33"
51
+ "@types/pluralize": "^0.0.33",
52
+ "pluralize": "^8.0.0",
53
+ "scule": "^1.0.0",
54
+ "c12": "^2.0.1",
55
+ "jose": "^5.9.6"
51
56
  },
52
57
  "peerDependencies": {
53
- "drizzle-orm": "^0.30.0",
54
- "pluralize": "^8.0.0",
55
- "scule": "^1.0.0"
58
+ "drizzle-orm": "^0.30.0"
56
59
  },
57
60
  "devDependencies": {
58
61
  "@nuxt/devtools": "^3.1.0",
@@ -60,12 +63,19 @@
60
63
  "@nuxt/module-builder": "^1.0.2",
61
64
  "@nuxt/schema": "^4.2.1",
62
65
  "@nuxt/test-utils": "^3.20.1",
66
+ "@nuxthub/core": "^0.9.1",
63
67
  "@types/node": "latest",
68
+ "better-sqlite3": "^12.4.6",
64
69
  "changelogen": "^0.6.2",
70
+ "drizzle-kit": "^0.31.7",
71
+ "drizzle-orm": "^0.38.3",
65
72
  "eslint": "^9.39.1",
66
73
  "nuxt": "^4.2.1",
74
+ "nuxt-auth-utils": "^0.5.25",
75
+ "nuxt-authorization": "^0.3.5",
67
76
  "typescript": "~5.9.3",
68
77
  "vitest": "^4.0.13",
69
- "vue-tsc": "^3.1.5"
78
+ "vue-tsc": "^3.1.5",
79
+ "wrangler": "^4.51.0"
70
80
  }
71
81
  }
@@ -1,15 +1,36 @@
1
1
  // server/api/[model]/[id].delete.ts
2
2
  import { eventHandler, getRouterParams, createError } from 'h3'
3
3
  import { eq } from 'drizzle-orm'
4
- import { getTableForModel, getModelSingularName } from '../../utils/modelMapper'
4
+ import { getTableForModel, getModelSingularName, filterHiddenFields, filterPublicColumns } from '../../utils/modelMapper'
5
5
 
6
6
  import type { TableWithId } from '../../types'
7
7
  // @ts-expect-error - #site/drizzle is an alias defined by the module
8
8
  import { useDrizzle } from '#site/drizzle'
9
9
 
10
+ import { useAutoCrudConfig } from '../../utils/config'
11
+ import { checkAdminAccess } from '../../utils/auth'
12
+
10
13
  export default eventHandler(async (event) => {
11
- const { model, id } = getRouterParams(event)
14
+ const { resources } = useAutoCrudConfig()
15
+ const { model, id } = getRouterParams(event) as { model: string, id: string }
16
+
17
+ const isAdmin = await checkAdminAccess(event, model, 'delete')
18
+
19
+ // Check public access if not admin
20
+ if (!isAdmin) {
21
+ const resourceConfig = resources?.[model]
22
+ const isPublic = resourceConfig?.public === true || (Array.isArray(resourceConfig?.public) && resourceConfig.public.includes('delete'))
23
+
24
+ if (!isPublic) {
25
+ throw createError({
26
+ statusCode: 401,
27
+ message: 'Unauthorized',
28
+ })
29
+ }
30
+ }
31
+
12
32
  const table = getTableForModel(model) as TableWithId
33
+
13
34
  const singularName = getModelSingularName(model)
14
35
 
15
36
  const deletedRecord = await useDrizzle()
@@ -25,5 +46,10 @@ export default eventHandler(async (event) => {
25
46
  })
26
47
  }
27
48
 
28
- return deletedRecord
49
+ if (isAdmin) {
50
+ return filterHiddenFields(model, deletedRecord as Record<string, unknown>)
51
+ }
52
+ else {
53
+ return filterPublicColumns(model, deletedRecord as Record<string, unknown>)
54
+ }
29
55
  })
@@ -1,16 +1,35 @@
1
1
  // server/api/[model]/[id].get.ts
2
2
  import { eventHandler, getRouterParams, createError } from 'h3'
3
3
  import { eq } from 'drizzle-orm'
4
- import { getTableForModel, getModelSingularName } from '../../utils/modelMapper'
4
+ import { getTableForModel, filterHiddenFields, filterPublicColumns } from '../../utils/modelMapper'
5
5
 
6
6
  import type { TableWithId } from '../../types'
7
7
  // @ts-expect-error - #site/drizzle is an alias defined by the module
8
8
  import { useDrizzle } from '#site/drizzle'
9
9
 
10
+ import { useAutoCrudConfig } from '../../utils/config'
11
+ import { checkAdminAccess } from '../../utils/auth'
12
+
10
13
  export default eventHandler(async (event) => {
11
- const { model, id } = getRouterParams(event)
14
+ const { resources } = useAutoCrudConfig()
15
+ const { model, id } = getRouterParams(event) as { model: string, id: string }
16
+
17
+ const isAdmin = await checkAdminAccess(event, model, 'read')
18
+
19
+ // Check public access if not admin
20
+ if (!isAdmin) {
21
+ const resourceConfig = resources?.[model]
22
+ const isPublic = resourceConfig?.public === true || (Array.isArray(resourceConfig?.public) && resourceConfig.public.includes('read'))
23
+
24
+ if (!isPublic) {
25
+ throw createError({
26
+ statusCode: 401,
27
+ message: 'Unauthorized',
28
+ })
29
+ }
30
+ }
31
+
12
32
  const table = getTableForModel(model) as TableWithId
13
- const singularName = getModelSingularName(model)
14
33
 
15
34
  const record = await useDrizzle()
16
35
  .select()
@@ -21,9 +40,14 @@ export default eventHandler(async (event) => {
21
40
  if (!record) {
22
41
  throw createError({
23
42
  statusCode: 404,
24
- message: `${singularName} not found`,
43
+ message: 'Record not found',
25
44
  })
26
45
  }
27
46
 
28
- return record
47
+ if (isAdmin) {
48
+ return filterHiddenFields(model, record as Record<string, unknown>)
49
+ }
50
+ else {
51
+ return filterPublicColumns(model, record as Record<string, unknown>)
52
+ }
29
53
  })
@@ -1,26 +1,57 @@
1
1
  // server/api/[model]/[id].patch.ts
2
- import { eventHandler, getRouterParams, readBody } from 'h3'
2
+ import { eventHandler, getRouterParams, readBody, createError } from 'h3'
3
3
  import { eq } from 'drizzle-orm'
4
- import { getTableForModel, filterUpdatableFields } from '../../utils/modelMapper'
4
+ import { getTableForModel, filterUpdatableFields, filterHiddenFields, filterPublicColumns } from '../../utils/modelMapper'
5
5
 
6
6
  import type { TableWithId } from '../../types'
7
7
  // @ts-expect-error - #site/drizzle is an alias defined by the module
8
8
  import { useDrizzle } from '#site/drizzle'
9
9
 
10
+ import { useAutoCrudConfig } from '../../utils/config'
11
+ import { checkAdminAccess } from '../../utils/auth'
12
+
10
13
  export default eventHandler(async (event) => {
11
- const { model, id } = getRouterParams(event)
14
+ const { resources } = useAutoCrudConfig()
15
+ const { model, id } = getRouterParams(event) as { model: string, id: string }
16
+
17
+ const isAdmin = await checkAdminAccess(event, model, 'update')
18
+
19
+ // Check public access if not admin
20
+ if (!isAdmin) {
21
+ const resourceConfig = resources?.[model]
22
+ const isPublic = resourceConfig?.public === true || (Array.isArray(resourceConfig?.public) && resourceConfig.public.includes('update'))
23
+
24
+ if (!isPublic) {
25
+ throw createError({
26
+ statusCode: 401,
27
+ message: 'Unauthorized',
28
+ })
29
+ }
30
+ }
31
+
12
32
  const table = getTableForModel(model) as TableWithId
13
- const body = await readBody(event)
14
33
 
15
- // Filter to only allow updatable fields for this model
16
- const updateData = filterUpdatableFields(model, body)
34
+ const body = await readBody(event)
35
+ const payload = filterUpdatableFields(model, body)
17
36
 
18
- const record = await useDrizzle()
37
+ const updatedRecord = await useDrizzle()
19
38
  .update(table)
20
- .set(updateData)
39
+ .set(payload)
21
40
  .where(eq(table.id, Number(id)))
22
41
  .returning()
23
42
  .get()
24
43
 
25
- return record
44
+ if (!updatedRecord) {
45
+ throw createError({
46
+ statusCode: 404,
47
+ message: 'Record not found',
48
+ })
49
+ }
50
+
51
+ if (isAdmin) {
52
+ return filterHiddenFields(model, updatedRecord as Record<string, unknown>)
53
+ }
54
+ else {
55
+ return filterPublicColumns(model, updatedRecord as Record<string, unknown>)
56
+ }
26
57
  })
@@ -1,15 +1,43 @@
1
1
  // server/api/[model]/index.get.ts
2
- import { eventHandler, getRouterParams } from 'h3'
3
- import { getTableForModel } from '../../utils/modelMapper'
2
+ import { eventHandler, getRouterParams, createError } from 'h3'
3
+ import { getTableForModel, filterHiddenFields, filterPublicColumns } from '../../utils/modelMapper'
4
4
 
5
5
  // @ts-expect-error - #site/drizzle is an alias defined by the module
6
6
  import { useDrizzle } from '#site/drizzle'
7
7
 
8
+ import { useAutoCrudConfig } from '../../utils/config'
9
+ import { checkAdminAccess } from '../../utils/auth'
10
+
8
11
  export default eventHandler(async (event) => {
9
- const { model } = getRouterParams(event)
12
+ console.log('[GET] Request received', event.path)
13
+ const { resources } = useAutoCrudConfig()
14
+ const { model } = getRouterParams(event) as { model: string }
15
+
16
+ const isAdmin = await checkAdminAccess(event, model, 'list')
17
+
18
+ // Check public access if not admin
19
+ if (!isAdmin) {
20
+ const resourceConfig = resources?.[model]
21
+ const isPublic = resourceConfig?.public === true || (Array.isArray(resourceConfig?.public) && resourceConfig.public.includes('list'))
22
+
23
+ if (!isPublic) {
24
+ throw createError({
25
+ statusCode: 401,
26
+ message: 'Unauthorized',
27
+ })
28
+ }
29
+ }
30
+
10
31
  const table = getTableForModel(model)
11
32
 
12
- const records = await useDrizzle().select().from(table).all()
33
+ const results = await useDrizzle().select().from(table).all()
13
34
 
14
- return records
35
+ return results.map((item: Record<string, unknown>) => {
36
+ if (isAdmin) {
37
+ return filterHiddenFields(model, item as Record<string, unknown>)
38
+ }
39
+ else {
40
+ return filterPublicColumns(model, item as Record<string, unknown>)
41
+ }
42
+ })
15
43
  })
@@ -1,26 +1,43 @@
1
1
  // server/api/[model]/index.post.ts
2
- import { eventHandler, getRouterParams, readBody } from 'h3'
3
- import { getTableForModel } from '../../utils/modelMapper'
2
+ import { eventHandler, getRouterParams, readBody, createError } from 'h3'
3
+ import { getTableForModel, filterHiddenFields, filterUpdatableFields, filterPublicColumns } from '../../utils/modelMapper'
4
4
 
5
5
  // @ts-expect-error - #site/drizzle is an alias defined by the module
6
6
  import { useDrizzle } from '#site/drizzle'
7
7
 
8
+ import { useAutoCrudConfig } from '../../utils/config'
9
+ import { checkAdminAccess } from '../../utils/auth'
10
+
8
11
  export default eventHandler(async (event) => {
9
- const { model } = getRouterParams(event)
10
- const table = getTableForModel(model)
11
- const body = await readBody(event)
12
+ const { resources } = useAutoCrudConfig()
13
+ const { model } = getRouterParams(event) as { model: string }
12
14
 
13
- // Add createdAt timestamp
14
- const values = {
15
- ...body,
16
- createdAt: new Date(),
15
+ const isAdmin = await checkAdminAccess(event, model, 'create')
16
+
17
+ // Check public access if not admin
18
+ if (!isAdmin) {
19
+ const resourceConfig = resources?.[model]
20
+ const isPublic = resourceConfig?.public === true || (Array.isArray(resourceConfig?.public) && resourceConfig.public.includes('create'))
21
+
22
+ if (!isPublic) {
23
+ throw createError({
24
+ statusCode: 401,
25
+ message: 'Unauthorized',
26
+ })
27
+ }
17
28
  }
18
29
 
19
- const record = await useDrizzle()
20
- .insert(table)
21
- .values(values)
22
- .returning()
23
- .get()
30
+ const table = getTableForModel(model)
24
31
 
25
- return record
32
+ const body = await readBody(event)
33
+ const payload = filterUpdatableFields(model, body)
34
+
35
+ const newRecord = await useDrizzle().insert(table).values(payload).returning().get()
36
+
37
+ if (isAdmin) {
38
+ return filterHiddenFields(model, newRecord as Record<string, unknown>)
39
+ }
40
+ else {
41
+ return filterPublicColumns(model, newRecord as Record<string, unknown>)
42
+ }
26
43
  })
@@ -0,0 +1,55 @@
1
+ import type { H3Event } from 'h3'
2
+ import { createError } from 'h3'
3
+ import { useAutoCrudConfig } from './config'
4
+ import { verifyJwtToken } from './jwt'
5
+
6
+ export async function checkAdminAccess(event: H3Event, model: string, action: string): Promise<boolean> {
7
+ const { auth } = useAutoCrudConfig()
8
+
9
+ if (!auth?.enabled) {
10
+ return true
11
+ }
12
+
13
+ if (auth.type === 'jwt') {
14
+ if (!auth.jwtSecret) {
15
+ console.warn('JWT Secret is not configured but auth type is jwt')
16
+ return false
17
+ }
18
+ return verifyJwtToken(event, auth.jwtSecret)
19
+ }
20
+
21
+ // Session based (default)
22
+ // @ts-expect-error - requireUserSession is auto-imported
23
+ if (typeof requireUserSession !== 'function') {
24
+ throw new TypeError('requireUserSession is not available')
25
+ }
26
+
27
+ try {
28
+ // @ts-expect-error - requireUserSession is auto-imported
29
+ await requireUserSession(event)
30
+
31
+ // Check authorization if enabled
32
+ if (auth.authorization) {
33
+ if (event.context.ability) {
34
+ const can = event.context.ability.can(action, model)
35
+ if (!can) {
36
+ throw createError({
37
+ statusCode: 403,
38
+ message: 'Forbidden',
39
+ })
40
+ }
41
+ }
42
+ }
43
+
44
+ return true
45
+ }
46
+ catch (e: unknown) {
47
+ // If it's a 403 (Forbidden) from our ability check, rethrow it
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ if ((e as any).statusCode === 403) {
50
+ throw e
51
+ }
52
+ // Otherwise (401 from requireUserSession), return false (treat as guest)
53
+ return false
54
+ }
55
+ }
@@ -0,0 +1,6 @@
1
+ import { useRuntimeConfig } from '#imports'
2
+ import type { ModuleOptions } from '../../../types'
3
+
4
+ export const useAutoCrudConfig = (): ModuleOptions => {
5
+ return useRuntimeConfig().autoCrud as ModuleOptions
6
+ }
@@ -0,0 +1,23 @@
1
+ import { jwtVerify } from 'jose'
2
+ import type { H3Event } from 'h3'
3
+ import { getRequestHeader } from 'h3'
4
+
5
+ export async function verifyJwtToken(event: H3Event, secret: string): Promise<boolean> {
6
+ const authHeader = getRequestHeader(event, 'Authorization')
7
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
8
+ return false
9
+ }
10
+
11
+ const token = authHeader.split(' ')[1]
12
+ if (!token) {
13
+ return false
14
+ }
15
+ try {
16
+ const secretKey = new TextEncoder().encode(secret)
17
+ await jwtVerify(token, secretKey)
18
+ return true
19
+ }
20
+ catch {
21
+ return false
22
+ }
23
+ }