@open-mercato/core 0.10.1-develop.7762.1.657bb7236b → 0.10.1-develop.7763.1.caea616ebf
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/auth/api/profile/route.js +16 -2
- package/dist/modules/auth/api/profile/route.js.map +2 -2
- package/dist/modules/auth/lib/userDataSubject.js +26 -0
- package/dist/modules/auth/lib/userDataSubject.js.map +7 -0
- package/dist/modules/dashboards/api/layout/[itemId]/route.js +11 -4
- package/dist/modules/dashboards/api/layout/[itemId]/route.js.map +2 -2
- package/dist/modules/dashboards/api/layout/route.js +25 -13
- package/dist/modules/dashboards/api/layout/route.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/api/profile/route.ts +15 -1
- package/src/modules/auth/lib/userDataSubject.ts +30 -0
- package/src/modules/dashboards/api/layout/[itemId]/route.ts +12 -4
- package/src/modules/dashboards/api/layout/route.ts +25 -12
package/.turbo/turbo-build.log
CHANGED
|
@@ -10,6 +10,7 @@ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find"
|
|
|
10
10
|
import { buildPasswordSchema } from "@open-mercato/shared/lib/auth/passwordPolicy";
|
|
11
11
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
12
12
|
import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
|
|
13
|
+
import { resolveUserDataSubject } from "@open-mercato/core/modules/auth/lib/userDataSubject";
|
|
13
14
|
const logger = createLogger("auth").child({ component: "profile" });
|
|
14
15
|
const profileResponseSchema = z.object({
|
|
15
16
|
email: z.string().email(),
|
|
@@ -84,10 +85,18 @@ async function GET(req) {
|
|
|
84
85
|
try {
|
|
85
86
|
const container = await createRequestContainer();
|
|
86
87
|
const em = container.resolve("em");
|
|
88
|
+
const userId = await resolveUserDataSubject(em, auth);
|
|
89
|
+
if (!userId) {
|
|
90
|
+
return NextResponse.json({ error: translate("api.errors.forbidden", "Forbidden") }, { status: 403 });
|
|
91
|
+
}
|
|
87
92
|
const user = await findOneWithDecryption(
|
|
88
93
|
em,
|
|
89
94
|
User,
|
|
90
|
-
{
|
|
95
|
+
{
|
|
96
|
+
id: userId,
|
|
97
|
+
deletedAt: null,
|
|
98
|
+
...auth.isApiKey ? { tenantId: auth.tenantId, ...auth.orgId ? { organizationId: auth.orgId } : {} } : {}
|
|
99
|
+
},
|
|
91
100
|
void 0,
|
|
92
101
|
{ tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null }
|
|
93
102
|
);
|
|
@@ -111,6 +120,9 @@ async function PUT(req) {
|
|
|
111
120
|
if (!auth?.sub) {
|
|
112
121
|
return NextResponse.json({ error: translate("api.errors.unauthorized", "Unauthorized") }, { status: 401 });
|
|
113
122
|
}
|
|
123
|
+
if (auth.isApiKey) {
|
|
124
|
+
return NextResponse.json({ error: translate("api.errors.forbidden", "Forbidden") }, { status: 403 });
|
|
125
|
+
}
|
|
114
126
|
try {
|
|
115
127
|
const body = await req.json().catch(() => ({}));
|
|
116
128
|
const parsed = buildUpdateSchema(translate).safeParse(body);
|
|
@@ -206,6 +218,7 @@ const openApi = {
|
|
|
206
218
|
responses: [
|
|
207
219
|
{ status: 200, description: "Profile payload", schema: profileResponseSchema },
|
|
208
220
|
{ status: 401, description: "Unauthorized", schema: z.object({ error: z.string() }) },
|
|
221
|
+
{ status: 403, description: "No user binding in the authenticated scope", schema: z.object({ error: z.string() }) },
|
|
209
222
|
{ status: 404, description: "User not found", schema: z.object({ error: z.string() }) }
|
|
210
223
|
]
|
|
211
224
|
},
|
|
@@ -219,7 +232,8 @@ const openApi = {
|
|
|
219
232
|
responses: [
|
|
220
233
|
{ status: 200, description: "Profile updated", schema: profileUpdateResponseSchema },
|
|
221
234
|
{ status: 400, description: "Invalid payload", schema: z.object({ error: z.string() }) },
|
|
222
|
-
{ status: 401, description: "Unauthorized", schema: z.object({ error: z.string() }) }
|
|
235
|
+
{ status: 401, description: "Unauthorized", schema: z.object({ error: z.string() }) },
|
|
236
|
+
{ status: 403, description: "Interactive session required", schema: z.object({ error: z.string() }) }
|
|
223
237
|
]
|
|
224
238
|
}
|
|
225
239
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/auth/api/profile/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\n\nconst logger = createLogger('auth').child({ component: 'profile' })\n\nconst profileResponseSchema = z.object({\n email: z.string().email(),\n name: z.string().nullable().optional(),\n roles: z.array(z.string()),\n})\n\nconst passwordSchema = buildPasswordSchema()\n\nconst updateSchemaBase = z.object({\n email: z.string().email().optional(),\n currentPassword: z.string().trim().min(1).optional(),\n password: passwordSchema.optional(),\n})\n\nfunction buildUpdateSchema(translate: (key: string, fallback: string) => string) {\n return updateSchemaBase.superRefine((data, ctx) => {\n if (!data.email && !data.password) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: translate(\n 'auth.profile.form.errors.emailOrPasswordRequired',\n 'Provide an email or password.',\n ),\n path: ['email'],\n })\n }\n if (data.password && !data.currentPassword) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: translate(\n 'auth.profile.form.errors.currentPasswordRequired',\n 'Current password is required.',\n ),\n path: ['currentPassword'],\n })\n }\n if (data.currentPassword && !data.password) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: translate(\n 'auth.profile.form.errors.newPasswordRequired',\n 'New password is required.',\n ),\n path: ['password'],\n })\n }\n })\n}\n\nconst updateSchema = buildUpdateSchema((_key, fallback) => fallback)\n\nconst profileUpdateResponseSchema = z.object({\n ok: z.literal(true),\n email: z.string().email(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true },\n PUT: { requireAuth: true },\n}\n\nfunction buildCommandContext(container: Awaited<ReturnType<typeof createRequestContainer>>, auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>, req: Request): CommandRuntimeContext {\n return {\n container,\n auth,\n organizationScope: null,\n selectedOrganizationId: auth.orgId ?? null,\n organizationIds: auth.orgId ? [auth.orgId] : null,\n request: req,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n try {\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager)\n const user = await findOneWithDecryption(\n em,\n User,\n { id: auth.sub, deletedAt: null },\n undefined,\n { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null },\n )\n if (!user) {\n return NextResponse.json({ error: translate('auth.users.form.errors.notFound', 'User not found') }, { status: 404 })\n }\n const displayName = typeof user.name === 'string' ? user.name.trim() : ''\n return NextResponse.json({\n email: String(user.email),\n name: displayName.length > 0 ? displayName : null,\n roles: auth.roles ?? [],\n })\n } catch (err) {\n logger.error('Profile load failed', { err })\n return NextResponse.json({ error: translate('auth.profile.form.errors.load', 'Failed to load profile.') }, { status: 400 })\n }\n}\n\nexport async function PUT(req: Request) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n try {\n const body = await req.json().catch(() => ({}))\n const parsed = buildUpdateSchema(translate).safeParse(body)\n if (!parsed.success) {\n return NextResponse.json(\n {\n error: translate('auth.profile.form.errors.invalid', 'Invalid profile update.'),\n issues: parsed.error.issues,\n },\n { status: 400 },\n )\n }\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager)\n const authService = container.resolve('authService') as AuthService\n if (parsed.data.password) {\n const user = await findOneWithDecryption(\n em,\n User,\n { id: auth.sub, deletedAt: null },\n undefined,\n { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null },\n )\n if (!user) {\n return NextResponse.json({ error: translate('auth.users.form.errors.notFound', 'User not found') }, { status: 404 })\n }\n const currentPassword = parsed.data.currentPassword?.trim() ?? ''\n const isCurrentPasswordValid = await authService.verifyPassword(user, currentPassword)\n if (!isCurrentPasswordValid) {\n const message = translate(\n 'auth.profile.form.errors.currentPasswordInvalid',\n 'Current password is incorrect.',\n )\n return NextResponse.json(\n {\n error: message,\n issues: [{ path: ['currentPassword'], message }],\n },\n { status: 400 },\n )\n }\n }\n const commandBus = (container.resolve('commandBus') as CommandBus)\n const ctx = buildCommandContext(container, auth, req)\n const { result } = await commandBus.execute<{ id: string; email?: string; password?: string }, User>(\n 'auth.users.update',\n {\n input: {\n id: auth.sub,\n email: parsed.data.email,\n password: parsed.data.password,\n },\n ctx,\n },\n )\n const roles = await authService.getUserRoles(result, result.tenantId ? String(result.tenantId) : null)\n const jwt = signJwt({\n sub: String(result.id),\n sid: typeof auth.sid === 'string' ? auth.sid : undefined,\n tenantId: result.tenantId ? String(result.tenantId) : null,\n orgId: result.organizationId ? String(result.organizationId) : null,\n email: result.email,\n roles,\n })\n const res = NextResponse.json({ ok: true, email: String(result.email) })\n res.cookies.set('auth_token', jwt, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: 60 * 60 * 8,\n })\n return res\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n logger.error('Profile update failed', { err })\n return NextResponse.json({ error: translate('auth.profile.form.errors.save', 'Failed to update profile.') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Profile settings',\n methods: {\n GET: {\n summary: 'Get current profile',\n description: 'Returns the email address, display name, and roles for the signed-in user. The display name is null when unset.',\n responses: [\n { status: 200, description: 'Profile payload', schema: profileResponseSchema },\n { status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },\n { status: 404, description: 'User not found', schema: z.object({ error: z.string() }) },\n ],\n },\n PUT: {\n summary: 'Update current profile',\n description: 'Updates the email address or password for the signed-in user.',\n requestBody: {\n contentType: 'application/json',\n schema: updateSchema,\n },\n responses: [\n { status: 200, description: 'Profile updated', schema: profileUpdateResponseSchema },\n { status: 400, description: 'Invalid payload', schema: z.object({ error: z.string() }) },\n { status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAGlB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAEhC,SAAS,YAAY;AAErB,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAC7B,SAAS,0CAA0C;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { signJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'\nimport { resolveUserDataSubject } from '@open-mercato/core/modules/auth/lib/userDataSubject'\n\nconst logger = createLogger('auth').child({ component: 'profile' })\n\nconst profileResponseSchema = z.object({\n email: z.string().email(),\n name: z.string().nullable().optional(),\n roles: z.array(z.string()),\n})\n\nconst passwordSchema = buildPasswordSchema()\n\nconst updateSchemaBase = z.object({\n email: z.string().email().optional(),\n currentPassword: z.string().trim().min(1).optional(),\n password: passwordSchema.optional(),\n})\n\nfunction buildUpdateSchema(translate: (key: string, fallback: string) => string) {\n return updateSchemaBase.superRefine((data, ctx) => {\n if (!data.email && !data.password) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: translate(\n 'auth.profile.form.errors.emailOrPasswordRequired',\n 'Provide an email or password.',\n ),\n path: ['email'],\n })\n }\n if (data.password && !data.currentPassword) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: translate(\n 'auth.profile.form.errors.currentPasswordRequired',\n 'Current password is required.',\n ),\n path: ['currentPassword'],\n })\n }\n if (data.currentPassword && !data.password) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: translate(\n 'auth.profile.form.errors.newPasswordRequired',\n 'New password is required.',\n ),\n path: ['password'],\n })\n }\n })\n}\n\nconst updateSchema = buildUpdateSchema((_key, fallback) => fallback)\n\nconst profileUpdateResponseSchema = z.object({\n ok: z.literal(true),\n email: z.string().email(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true },\n PUT: { requireAuth: true },\n}\n\nfunction buildCommandContext(container: Awaited<ReturnType<typeof createRequestContainer>>, auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>, req: Request): CommandRuntimeContext {\n return {\n container,\n auth,\n organizationScope: null,\n selectedOrganizationId: auth.orgId ?? null,\n organizationIds: auth.orgId ? [auth.orgId] : null,\n request: req,\n }\n}\n\nexport async function GET(req: Request) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n try {\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager)\n const userId = await resolveUserDataSubject(em, auth)\n if (!userId) {\n return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })\n }\n const user = await findOneWithDecryption(\n em,\n User,\n {\n id: userId,\n deletedAt: null,\n ...(auth.isApiKey ? { tenantId: auth.tenantId, ...(auth.orgId ? { organizationId: auth.orgId } : {}) } : {}),\n },\n undefined,\n { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null },\n )\n if (!user) {\n return NextResponse.json({ error: translate('auth.users.form.errors.notFound', 'User not found') }, { status: 404 })\n }\n const displayName = typeof user.name === 'string' ? user.name.trim() : ''\n return NextResponse.json({\n email: String(user.email),\n name: displayName.length > 0 ? displayName : null,\n roles: auth.roles ?? [],\n })\n } catch (err) {\n logger.error('Profile load failed', { err })\n return NextResponse.json({ error: translate('auth.profile.form.errors.load', 'Failed to load profile.') }, { status: 400 })\n }\n}\n\nexport async function PUT(req: Request) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n if (auth.isApiKey) {\n return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })\n }\n try {\n const body = await req.json().catch(() => ({}))\n const parsed = buildUpdateSchema(translate).safeParse(body)\n if (!parsed.success) {\n return NextResponse.json(\n {\n error: translate('auth.profile.form.errors.invalid', 'Invalid profile update.'),\n issues: parsed.error.issues,\n },\n { status: 400 },\n )\n }\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager)\n const authService = container.resolve('authService') as AuthService\n if (parsed.data.password) {\n const user = await findOneWithDecryption(\n em,\n User,\n { id: auth.sub, deletedAt: null },\n undefined,\n { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null },\n )\n if (!user) {\n return NextResponse.json({ error: translate('auth.users.form.errors.notFound', 'User not found') }, { status: 404 })\n }\n const currentPassword = parsed.data.currentPassword?.trim() ?? ''\n const isCurrentPasswordValid = await authService.verifyPassword(user, currentPassword)\n if (!isCurrentPasswordValid) {\n const message = translate(\n 'auth.profile.form.errors.currentPasswordInvalid',\n 'Current password is incorrect.',\n )\n return NextResponse.json(\n {\n error: message,\n issues: [{ path: ['currentPassword'], message }],\n },\n { status: 400 },\n )\n }\n }\n const commandBus = (container.resolve('commandBus') as CommandBus)\n const ctx = buildCommandContext(container, auth, req)\n const { result } = await commandBus.execute<{ id: string; email?: string; password?: string }, User>(\n 'auth.users.update',\n {\n input: {\n id: auth.sub,\n email: parsed.data.email,\n password: parsed.data.password,\n },\n ctx,\n },\n )\n const roles = await authService.getUserRoles(result, result.tenantId ? String(result.tenantId) : null)\n const jwt = signJwt({\n sub: String(result.id),\n sid: typeof auth.sid === 'string' ? auth.sid : undefined,\n tenantId: result.tenantId ? String(result.tenantId) : null,\n orgId: result.organizationId ? String(result.organizationId) : null,\n email: result.email,\n roles,\n })\n const res = NextResponse.json({ ok: true, email: String(result.email) })\n res.cookies.set('auth_token', jwt, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: 60 * 60 * 8,\n })\n return res\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n const interceptorRejection = getCommandInterceptorHttpRejection(err)\n if (interceptorRejection) {\n return NextResponse.json(interceptorRejection.body, { status: interceptorRejection.status })\n }\n logger.error('Profile update failed', { err })\n return NextResponse.json({ error: translate('auth.profile.form.errors.save', 'Failed to update profile.') }, { status: 400 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Profile settings',\n methods: {\n GET: {\n summary: 'Get current profile',\n description: 'Returns the email address, display name, and roles for the signed-in user. The display name is null when unset.',\n responses: [\n { status: 200, description: 'Profile payload', schema: profileResponseSchema },\n { status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },\n { status: 403, description: 'No user binding in the authenticated scope', schema: z.object({ error: z.string() }) },\n { status: 404, description: 'User not found', schema: z.object({ error: z.string() }) },\n ],\n },\n PUT: {\n summary: 'Update current profile',\n description: 'Updates the email address or password for the signed-in user.',\n requestBody: {\n contentType: 'application/json',\n schema: updateSchema,\n },\n responses: [\n { status: 200, description: 'Profile updated', schema: profileUpdateResponseSchema },\n { status: 400, description: 'Invalid payload', schema: z.object({ error: z.string() }) },\n { status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },\n { status: 403, description: 'Interactive session required', schema: z.object({ error: z.string() }) },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAGlB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,eAAe;AACxB,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAEhC,SAAS,YAAY;AAErB,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS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BAAmB,QAAQ,sBAAsB;AAAA,QAC7E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,8CAA8C,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QAClH,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,MACxF;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,4BAA4B;AAAA,QACnF,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACvF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,MACtG;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
3
|
+
import { User } from "../data/entities.js";
|
|
4
|
+
const uuidSchema = z.string().uuid();
|
|
5
|
+
async function resolveUserDataSubject(em, auth) {
|
|
6
|
+
if (!auth.isApiKey) return auth.sub;
|
|
7
|
+
if (!uuidSchema.safeParse(auth.userId).success || !uuidSchema.safeParse(auth.tenantId).success) return null;
|
|
8
|
+
if (auth.orgId !== null && !uuidSchema.safeParse(auth.orgId).success) return null;
|
|
9
|
+
const user = await findOneWithDecryption(
|
|
10
|
+
em,
|
|
11
|
+
User,
|
|
12
|
+
{
|
|
13
|
+
id: auth.userId,
|
|
14
|
+
tenantId: auth.tenantId,
|
|
15
|
+
...auth.orgId ? { organizationId: auth.orgId } : {},
|
|
16
|
+
deletedAt: null
|
|
17
|
+
},
|
|
18
|
+
void 0,
|
|
19
|
+
{ tenantId: auth.tenantId, organizationId: auth.orgId }
|
|
20
|
+
);
|
|
21
|
+
return user?.id ?? null;
|
|
22
|
+
}
|
|
23
|
+
export {
|
|
24
|
+
resolveUserDataSubject
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=userDataSubject.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/auth/lib/userDataSubject.ts"],
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { User } from '../data/entities'\n\nconst uuidSchema = z.string().uuid()\n\nexport async function resolveUserDataSubject(\n em: EntityManager,\n auth: NonNullable<AuthContext>,\n): Promise<string | null> {\n if (!auth.isApiKey) return auth.sub\n if (!uuidSchema.safeParse(auth.userId).success || !uuidSchema.safeParse(auth.tenantId).success) return null\n if (auth.orgId !== null && !uuidSchema.safeParse(auth.orgId).success) return null\n\n const user = await findOneWithDecryption(\n em,\n User,\n {\n id: auth.userId,\n tenantId: auth.tenantId,\n ...(auth.orgId ? { organizationId: auth.orgId } : {}),\n deletedAt: null,\n },\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n return user?.id ?? null\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,6BAA6B;AACtC,SAAS,YAAY;AAErB,MAAM,aAAa,EAAE,OAAO,EAAE,KAAK;AAEnC,eAAsB,uBACpB,IACA,MACwB;AACxB,MAAI,CAAC,KAAK,SAAU,QAAO,KAAK;AAChC,MAAI,CAAC,WAAW,UAAU,KAAK,MAAM,EAAE,WAAW,CAAC,WAAW,UAAU,KAAK,QAAQ,EAAE,QAAS,QAAO;AACvG,MAAI,KAAK,UAAU,QAAQ,CAAC,WAAW,UAAU,KAAK,KAAK,EAAE,QAAS,QAAO;AAE7E,QAAM,OAAO,MAAM;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI,KAAK;AAAA,MACT,UAAU,KAAK;AAAA,MACf,GAAI,KAAK,QAAQ,EAAE,gBAAgB,KAAK,MAAM,IAAI,CAAC;AAAA,MACnD,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,MAAM;AAAA,EACxD;AACA,SAAO,MAAM,MAAM;AACrB;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -2,6 +2,8 @@ import { NextResponse } from "next/server";
|
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
4
4
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
5
|
+
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
6
|
+
import { resolveUserDataSubject } from "@open-mercato/core/modules/auth/lib/userDataSubject";
|
|
5
7
|
import { DashboardLayout } from "@open-mercato/core/modules/dashboards/data/entities";
|
|
6
8
|
import { dashboardLayoutItemPatchSchema } from "@open-mercato/core/modules/dashboards/data/validators";
|
|
7
9
|
import {
|
|
@@ -41,13 +43,18 @@ async function PATCH(req, ctx) {
|
|
|
41
43
|
const { resolve } = container;
|
|
42
44
|
const em = resolve("em");
|
|
43
45
|
const rbac = resolve("rbacService");
|
|
46
|
+
const userId = await resolveUserDataSubject(em, auth);
|
|
47
|
+
if (!userId) {
|
|
48
|
+
const { translate } = await resolveTranslations();
|
|
49
|
+
return NextResponse.json({ error: translate("api.errors.forbidden", "Forbidden") }, { status: 403 });
|
|
50
|
+
}
|
|
44
51
|
const scope = {
|
|
45
|
-
userId
|
|
52
|
+
userId,
|
|
46
53
|
tenantId: auth.tenantId ?? null,
|
|
47
54
|
organizationId: auth.orgId ?? null
|
|
48
55
|
};
|
|
49
56
|
const canConfigure = await rbac.userHasAllFeatures(
|
|
50
|
-
|
|
57
|
+
auth.sub,
|
|
51
58
|
["dashboards.configure"],
|
|
52
59
|
{ tenantId: scope.tenantId, organizationId: scope.organizationId }
|
|
53
60
|
);
|
|
@@ -57,7 +64,7 @@ async function PATCH(req, ctx) {
|
|
|
57
64
|
const guardResult = await validateCrudMutationGuard(container, {
|
|
58
65
|
tenantId: scope.tenantId ?? "",
|
|
59
66
|
organizationId: scope.organizationId,
|
|
60
|
-
userId:
|
|
67
|
+
userId: auth.sub,
|
|
61
68
|
resourceKind: RESOURCE_KIND,
|
|
62
69
|
resourceId: layoutItemId,
|
|
63
70
|
operation: "update",
|
|
@@ -92,7 +99,7 @@ async function PATCH(req, ctx) {
|
|
|
92
99
|
await runCrudMutationGuardAfterSuccess(container, {
|
|
93
100
|
tenantId: scope.tenantId ?? "",
|
|
94
101
|
organizationId: scope.organizationId,
|
|
95
|
-
userId:
|
|
102
|
+
userId: auth.sub,
|
|
96
103
|
resourceKind: RESOURCE_KIND,
|
|
97
104
|
resourceId: layoutItemId,
|
|
98
105
|
operation: "update",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/dashboards/api/layout/%5BitemId%5D/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { DashboardLayout } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { dashboardLayoutItemPatchSchema } from '@open-mercato/core/modules/dashboards/data/validators'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n dashboardsTag,\n dashboardsErrorSchema,\n dashboardsOkSchema,\n dashboardLayoutItemUpdateSchema,\n} from '../../openapi'\n\nconst DEFAULT_SIZE = 'md'\nconst RESOURCE_KIND = 'dashboards.layout'\n\nexport const metadata = {\n PATCH: { requireAuth: true, requireFeatures: ['dashboards.configure'] },\n}\n\nexport async function PATCH(req: Request, ctx: { params?: { itemId?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const layoutItemId = ctx.params?.itemId\n if (!layoutItemId) return NextResponse.json({ error: 'Missing layout item id' }, { status: 400 })\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n const parsed = dashboardLayoutItemPatchSchema.safeParse({ ...(body as Record<string, unknown>), id: layoutItemId })\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload', issues: parsed.error.issues }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = resolve('em') as any\n const rbac = resolve('rbacService') as any\n\n const
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAEf,MAAM,WAAW;AAAA,EACtB,OAAO,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACxE;AAEA,eAAsB,MAAM,KAAc,KAAuC;AAC/E,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,KAAM,QAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAC9E,QAAM,eAAe,IAAI,QAAQ;AACjC,MAAI,CAAC,aAAc,QAAO,aAAa,KAAK,EAAE,OAAO,yBAAyB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAEhG,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO,aAAa,KAAK,EAAE,OAAO,oBAAoB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC1E;AACA,MAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,MAAM,QAAQ,IAAI,GAAG;AAC5D,WAAO,aAAa,KAAK,EAAE,OAAO,kBAAkB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACxE;AACA,QAAM,SAAS,+BAA+B,UAAU,EAAE,GAAI,MAAkC,IAAI,aAAa,CAAC;AAClH,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,aAAa,KAAK,EAAE,OAAO,mBAAmB,QAAQ,OAAO,MAAM,OAAO,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACrG;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,EAAE,QAAQ,IAAI;AACpB,QAAM,KAAK,QAAQ,IAAI;AACvB,QAAM,OAAO,QAAQ,aAAa;AAElC,QAAM,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveUserDataSubject } from '@open-mercato/core/modules/auth/lib/userDataSubject'\nimport { DashboardLayout } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { dashboardLayoutItemPatchSchema } from '@open-mercato/core/modules/dashboards/data/validators'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n dashboardsTag,\n dashboardsErrorSchema,\n dashboardsOkSchema,\n dashboardLayoutItemUpdateSchema,\n} from '../../openapi'\n\nconst DEFAULT_SIZE = 'md'\nconst RESOURCE_KIND = 'dashboards.layout'\n\nexport const metadata = {\n PATCH: { requireAuth: true, requireFeatures: ['dashboards.configure'] },\n}\n\nexport async function PATCH(req: Request, ctx: { params?: { itemId?: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const layoutItemId = ctx.params?.itemId\n if (!layoutItemId) return NextResponse.json({ error: 'Missing layout item id' }, { status: 400 })\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n if (!body || typeof body !== 'object' || Array.isArray(body)) {\n return NextResponse.json({ error: 'Invalid payload' }, { status: 400 })\n }\n const parsed = dashboardLayoutItemPatchSchema.safeParse({ ...(body as Record<string, unknown>), id: layoutItemId })\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload', issues: parsed.error.issues }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = resolve('em') as any\n const rbac = resolve('rbacService') as any\n\n const userId = await resolveUserDataSubject(em, auth)\n if (!userId) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })\n }\n\n const scope = {\n userId,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const canConfigure = await rbac.userHasAllFeatures(\n auth.sub,\n ['dashboards.configure'],\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (!canConfigure) {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: auth.sub,\n resourceKind: RESOURCE_KIND,\n resourceId: layoutItemId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: { id: layoutItemId, size: parsed.data.size, settings: parsed.data.settings },\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const layout = await em.findOne(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n if (!layout) {\n return NextResponse.json({ error: 'Layout not found' }, { status: 404 })\n }\n\n const idx = layout.layoutJson.findIndex((item: { id?: string | null }) => item?.id === layoutItemId)\n if (idx === -1) {\n return NextResponse.json({ error: 'Layout item not found' }, { status: 404 })\n }\n\n const current = layout.layoutJson[idx]\n layout.layoutJson[idx] = {\n ...current,\n size: parsed.data.size ?? current.size ?? DEFAULT_SIZE,\n settings: parsed.data.settings ?? current.settings,\n }\n await em.flush()\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: auth.sub,\n resourceKind: RESOURCE_KIND,\n resourceId: layoutItemId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true })\n}\n\nconst layoutItemParamsSchema = z.object({\n itemId: z.string().uuid(),\n})\n\nconst layoutItemPatchDoc: OpenApiMethodDoc = {\n summary: 'Update a dashboard layout item',\n description: 'Adjusts the size or settings for a single widget within the dashboard layout.',\n tags: [dashboardsTag],\n requestBody: {\n contentType: 'application/json',\n schema: dashboardLayoutItemUpdateSchema,\n description: 'Payload containing the new size or settings for the widget.',\n },\n responses: [\n { status: 200, description: 'Layout item updated.', schema: dashboardsOkSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid payload or missing item id', schema: dashboardsErrorSchema },\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n { status: 403, description: 'Missing dashboards.configure feature', schema: dashboardsErrorSchema },\n { status: 404, description: 'Item not found', schema: dashboardsErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dashboardsTag,\n summary: 'Update dashboard layout item',\n pathParams: layoutItemParamsSchema,\n methods: {\n PATCH: layoutItemPatchDoc,\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAEf,MAAM,WAAW;AAAA,EACtB,OAAO,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACxE;AAEA,eAAsB,MAAM,KAAc,KAAuC;AAC/E,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,KAAM,QAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAC9E,QAAM,eAAe,IAAI,QAAQ;AACjC,MAAI,CAAC,aAAc,QAAO,aAAa,KAAK,EAAE,OAAO,yBAAyB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAEhG,MA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B,QAAQ,KAAK;AAAA,MACb,cAAc;AAAA,MACd,YAAY;AAAA,MACZ,WAAW;AAAA,MACX,eAAe,IAAI;AAAA,MACnB,gBAAgB,IAAI;AAAA,MACpB,UAAU,YAAY,YAAY;AAAA,IACpC,CAAC;AAAA,EACH;AAEA,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AACvC;AAEA,MAAM,yBAAyB,EAAE,OAAO;AAAA,EACtC,QAAQ,EAAE,OAAO,EAAE,KAAK;AAC1B,CAAC;AAED,MAAM,qBAAuC;AAAA,EAC3C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,aAAa;AAAA,EACpB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,wBAAwB,QAAQ,mBAAmB;AAAA,EACjF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,sBAAsB;AAAA,IAChG,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,IACrF,EAAE,QAAQ,KAAK,aAAa,wCAAwC,QAAQ,sBAAsB;AAAA,IAClG,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,sBAAsB;AAAA,EAC9E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,SAAS;AAAA,IACP,OAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -9,6 +9,8 @@ import { resolveAllowedWidgetIds } from "@open-mercato/core/modules/dashboards/l
|
|
|
9
9
|
import { authorizeFeatures } from "@open-mercato/shared/security/featurePolicy";
|
|
10
10
|
import { User } from "@open-mercato/core/modules/auth/data/entities";
|
|
11
11
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
12
|
+
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
13
|
+
import { resolveUserDataSubject } from "@open-mercato/core/modules/auth/lib/userDataSubject";
|
|
12
14
|
import {
|
|
13
15
|
runCrudMutationGuardAfterSuccess,
|
|
14
16
|
validateCrudMutationGuard
|
|
@@ -61,13 +63,17 @@ async function GET(req) {
|
|
|
61
63
|
const container = await createRequestContainer();
|
|
62
64
|
const em = container.resolve("em").fork({ clear: true, freshEventManager: true, useContext: true });
|
|
63
65
|
const rbac = container.resolve("rbacService");
|
|
64
|
-
const
|
|
66
|
+
const userId = await resolveUserDataSubject(em, auth);
|
|
67
|
+
if (!userId) {
|
|
68
|
+
const { translate } = await resolveTranslations();
|
|
69
|
+
return NextResponse.json({ error: translate("api.errors.forbidden", "Forbidden") }, { status: 403 });
|
|
70
|
+
}
|
|
65
71
|
const scope = {
|
|
66
|
-
userId
|
|
72
|
+
userId,
|
|
67
73
|
tenantId: auth.tenantId ?? null,
|
|
68
74
|
organizationId: auth.orgId ?? null
|
|
69
75
|
};
|
|
70
|
-
const effectiveFeatures = await rbac.getEffectiveFeatures(
|
|
76
|
+
const effectiveFeatures = await rbac.getEffectiveFeatures(auth.sub, {
|
|
71
77
|
tenantId: scope.tenantId,
|
|
72
78
|
organizationId: scope.organizationId
|
|
73
79
|
});
|
|
@@ -98,7 +104,7 @@ async function GET(req) {
|
|
|
98
104
|
size: widget.metadata.defaultSize ?? DEFAULT_SIZE,
|
|
99
105
|
settings: widget.metadata.defaultSettings ?? void 0
|
|
100
106
|
}));
|
|
101
|
-
if (hasRegisteredWidgets) {
|
|
107
|
+
if (hasRegisteredWidgets && !auth.isApiKey) {
|
|
102
108
|
layout = em.create(DashboardLayout, {
|
|
103
109
|
userId: scope.userId,
|
|
104
110
|
tenantId: scope.tenantId,
|
|
@@ -108,7 +114,7 @@ async function GET(req) {
|
|
|
108
114
|
em.persist(layout);
|
|
109
115
|
hasChanged = true;
|
|
110
116
|
}
|
|
111
|
-
} else if (hasRegisteredWidgets) {
|
|
117
|
+
} else if (hasRegisteredWidgets || auth.isApiKey) {
|
|
112
118
|
const existingLayout = layout;
|
|
113
119
|
const filtered = items.filter((item) => allowedIds.includes(item.widgetId));
|
|
114
120
|
if (filtered.length !== items.length) {
|
|
@@ -119,10 +125,10 @@ async function GET(req) {
|
|
|
119
125
|
if (existingLayout.layoutJson.length !== items.length || items.some((item, idx) => existingLayout.layoutJson[idx]?.id !== item.id)) {
|
|
120
126
|
hasChanged = true;
|
|
121
127
|
}
|
|
122
|
-
existingLayout.layoutJson = items;
|
|
128
|
+
if (!auth.isApiKey) existingLayout.layoutJson = items;
|
|
123
129
|
layout = existingLayout;
|
|
124
130
|
}
|
|
125
|
-
if (hasChanged) {
|
|
131
|
+
if (hasChanged && !auth.isApiKey) {
|
|
126
132
|
await em.flush();
|
|
127
133
|
}
|
|
128
134
|
const canConfigure = authorizeFeatures(["dashboards.configure"], {
|
|
@@ -189,13 +195,18 @@ async function PUT(req) {
|
|
|
189
195
|
const { resolve } = container;
|
|
190
196
|
const em = resolve("em").fork({ clear: true, freshEventManager: true, useContext: true });
|
|
191
197
|
const rbac = resolve("rbacService");
|
|
198
|
+
const userId = await resolveUserDataSubject(em, auth);
|
|
199
|
+
if (!userId) {
|
|
200
|
+
const { translate } = await resolveTranslations();
|
|
201
|
+
return NextResponse.json({ error: translate("api.errors.forbidden", "Forbidden") }, { status: 403 });
|
|
202
|
+
}
|
|
192
203
|
const scope = {
|
|
193
|
-
userId
|
|
204
|
+
userId,
|
|
194
205
|
tenantId: auth.tenantId ?? null,
|
|
195
206
|
organizationId: auth.orgId ?? null
|
|
196
207
|
};
|
|
197
208
|
const canConfigure = await rbac.userHasAllFeatures(
|
|
198
|
-
|
|
209
|
+
auth.sub,
|
|
199
210
|
["dashboards.configure"],
|
|
200
211
|
{ tenantId: scope.tenantId, organizationId: scope.organizationId }
|
|
201
212
|
);
|
|
@@ -205,7 +216,7 @@ async function PUT(req) {
|
|
|
205
216
|
const guardResult = await validateCrudMutationGuard(container, {
|
|
206
217
|
tenantId: scope.tenantId ?? "",
|
|
207
218
|
organizationId: scope.organizationId,
|
|
208
|
-
userId:
|
|
219
|
+
userId: auth.sub,
|
|
209
220
|
resourceKind: RESOURCE_KIND,
|
|
210
221
|
resourceId: scope.userId,
|
|
211
222
|
operation: "update",
|
|
@@ -220,7 +231,7 @@ async function PUT(req) {
|
|
|
220
231
|
if (widgets.length === 0) {
|
|
221
232
|
return NextResponse.json({ error: "Widget registry unavailable" }, { status: 503 });
|
|
222
233
|
}
|
|
223
|
-
const effectiveFeatures = await rbac.getEffectiveFeatures(
|
|
234
|
+
const effectiveFeatures = await rbac.getEffectiveFeatures(auth.sub, {
|
|
224
235
|
tenantId: scope.tenantId,
|
|
225
236
|
organizationId: scope.organizationId
|
|
226
237
|
});
|
|
@@ -266,7 +277,7 @@ async function PUT(req) {
|
|
|
266
277
|
await runCrudMutationGuardAfterSuccess(container, {
|
|
267
278
|
tenantId: scope.tenantId ?? "",
|
|
268
279
|
organizationId: scope.organizationId,
|
|
269
|
-
userId:
|
|
280
|
+
userId: auth.sub,
|
|
270
281
|
resourceKind: RESOURCE_KIND,
|
|
271
282
|
resourceId: scope.userId,
|
|
272
283
|
operation: "update",
|
|
@@ -289,7 +300,8 @@ const layoutGetDoc = {
|
|
|
289
300
|
}
|
|
290
301
|
],
|
|
291
302
|
errors: [
|
|
292
|
-
{ status: 401, description: "Authentication required", schema: dashboardsErrorSchema }
|
|
303
|
+
{ status: 401, description: "Authentication required", schema: dashboardsErrorSchema },
|
|
304
|
+
{ status: 403, description: "No user binding in the authenticated scope", schema: dashboardsErrorSchema }
|
|
293
305
|
]
|
|
294
306
|
};
|
|
295
307
|
const layoutPutDoc = {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/dashboards/api/layout/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { randomUUID } from 'node:crypto'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { DashboardLayout } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { dashboardLayoutSchema } from '@open-mercato/core/modules/dashboards/data/validators'\nimport { loadAllWidgets } from '@open-mercato/core/modules/dashboards/lib/widgets'\nimport { resolveAllowedWidgetIds } from '@open-mercato/core/modules/dashboards/lib/access'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n dashboardsTag,\n dashboardsErrorSchema,\n dashboardsOkSchema,\n dashboardLayoutStateSchema,\n} from '../openapi'\n\nconst DEFAULT_SIZE = 'md'\nconst RESOURCE_KIND = 'dashboards.layout'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view'] },\n PUT: { requireAuth: true, requireFeatures: ['dashboards.configure'] },\n}\n\ntype LayoutScope = {\n userId: string\n tenantId: string | null\n organizationId: string | null\n}\n\nasync function loadScopeLayout(em: any, scope: LayoutScope): Promise<DashboardLayout | null> {\n return await em.findOne(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n}\n\nfunction normalizeLayoutItems(items: any[]) {\n const list = Array.isArray(items) ? items : []\n const seenIds = new Set<string>()\n const sanitized = list\n .filter((item) => item && typeof item === 'object')\n .map((item) => ({\n id: String(item.id),\n widgetId: String(item.widgetId),\n order: Number.isInteger(item.order) ? Number(item.order) : undefined,\n priority: Number.isInteger(item.priority) ? Number(item.priority) : undefined,\n size: typeof item.size === 'string' ? item.size : undefined,\n settings: item.settings,\n }))\n .filter((item) => {\n if (!item.id || !item.widgetId) return false\n if (seenIds.has(item.id)) return false\n seenIds.add(item.id)\n return true\n })\n .sort((a, b) => {\n const aOrder = a.order ?? a.priority ?? 0\n const bOrder = b.order ?? b.priority ?? 0\n return aOrder - bOrder\n })\n .map((item, idx) => ({ ...item, order: idx, priority: idx }))\n return sanitized\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n // Use a fresh fork to avoid carrying over pending entities from other operations\n const em = (container.resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = container.resolve('rbacService') as any\n const url = new URL(req.url)\n\n const scope: LayoutScope = {\n userId: String(auth.sub),\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const widgets = await loadAllWidgets()\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedWidgets = widgets.filter((w) => allowedIds.includes(w.metadata.id))\n\n // An empty widget registry means the module registry has not been populated yet\n // (a boot race), not that this app has no widgets. Every write below is derived\n // from it, so a read request must persist nothing until it recovers \u2014 otherwise a\n // restart-recoverable glitch is written into saved layouts for good (#5041).\n // Note this keys off the registry, not off `allowedIds`: a user whose allowlist is\n // legitimately empty on a healthy registry is still pruned and seeded as before.\n const hasRegisteredWidgets = widgets.length > 0\n\n let layout = await loadScopeLayout(em, scope)\n let items = layout ? normalizeLayoutItems(layout.layoutJson) : []\n let hasChanged = false\n\n if (!layout) {\n const defaults = allowedWidgets.filter((widget) => widget.metadata.defaultEnabled)\n items = defaults.map((widget, index) => ({\n id: randomUUID(),\n widgetId: widget.metadata.id,\n order: index,\n priority: index,\n size: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n settings: widget.metadata.defaultSettings ?? undefined,\n }))\n if (hasRegisteredWidgets) {\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: items,\n })\n em.persist(layout)\n hasChanged = true\n }\n } else if (hasRegisteredWidgets) {\n const existingLayout = layout\n const filtered = items.filter((item) => allowedIds.includes(item.widgetId))\n if (filtered.length !== items.length) {\n hasChanged = true\n items = filtered\n }\n items = items.map((item, index) => (item.order !== index || item.priority !== index ? { ...item, order: index, priority: index } : item))\n if (\n existingLayout.layoutJson.length !== items.length ||\n items.some((item, idx) => existingLayout.layoutJson[idx]?.id !== item.id)\n ) {\n hasChanged = true\n }\n existingLayout.layoutJson = items\n layout = existingLayout\n }\n\n if (hasChanged) {\n await em.flush()\n }\n\n const canConfigure = authorizeFeatures(['dashboards.configure'], {\n grantedFeatures: effectiveFeatures,\n })\n\n let userEmail: string | null = null\n let userName: string | null = null\n let userLabel: string | null = null\n const user = await findOneWithDecryption(\n em,\n User,\n { id: scope.userId, deletedAt: null },\n undefined,\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },\n )\n if (user) {\n userName = user.name?.trim() ?? null\n userEmail = user.email ?? null\n userLabel = (userName && userName.length > 0 ? userName : userEmail) ?? null\n }\n if (!userLabel) {\n userLabel = scope.userId\n }\n\n const response = {\n layout: { items },\n allowedWidgetIds: allowedIds,\n canConfigure,\n context: {\n ...scope,\n userName,\n userEmail,\n userLabel,\n },\n widgets: allowedWidgets.map((widget) => ({\n id: widget.metadata.id,\n title: widget.metadata.title,\n description: widget.metadata.description ?? null,\n defaultSize: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n defaultEnabled: !!widget.metadata.defaultEnabled,\n defaultSettings: widget.metadata.defaultSettings ?? null,\n features: widget.metadata.features ?? [],\n moduleId: widget.moduleId,\n icon: widget.metadata.icon ?? null,\n loaderKey: widget.key,\n supportsRefresh: !!widget.metadata.supportsRefresh,\n })),\n }\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n const parsed = dashboardLayoutSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid layout payload', issues: parsed.error.issues }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = (resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = resolve('rbacService') as any\n\n const scope: LayoutScope = {\n userId: String(auth.sub),\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const canConfigure = await rbac.userHasAllFeatures(\n scope.userId,\n ['dashboards.configure'],\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (!canConfigure) {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: { items: parsed.data.items },\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const widgets = await loadAllWidgets()\n // The allowlist below is derived from the registry, and this handler persists the\n // filtered result unconditionally. An empty registry \u2014 the boot race behind #5041 \u2014\n // would drop every submitted item and save `[]` while answering `{ ok: true }`, so a\n // stale tab reordering a widget could erase the layout it just rendered. Fail the\n // write instead: the save is explicit, so the client must learn it did not happen\n // and retry, rather than be told a wipe succeeded.\n if (widgets.length === 0) {\n return NextResponse.json({ error: 'Widget registry unavailable' }, { status: 503 })\n }\n const effectiveFeatures = await rbac.getEffectiveFeatures(scope.userId, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedSet = new Set(allowedIds)\n\n const payloadItems = parsed.data.items\n const sanitized = payloadItems\n .map((item, index) => ({\n id: item.id,\n widgetId: item.widgetId,\n order: index,\n priority: index,\n size: item.size ?? DEFAULT_SIZE,\n settings: item.settings,\n }))\n .filter((item) => allowedSet.has(item.widgetId))\n\n const uniqueIds = new Set(sanitized.map((item) => item.id))\n if (uniqueIds.size !== sanitized.length) {\n return NextResponse.json({ error: 'Layout item IDs must be unique' }, { status: 400 })\n }\n\n let layout = await loadScopeLayout(em, scope)\n if (!layout) {\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: sanitized,\n })\n em.persist(layout)\n } else {\n layout.layoutJson = sanitized\n }\n await em.flush()\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: scope.userId,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true })\n}\n\nconst layoutGetDoc: OpenApiMethodDoc = {\n summary: 'Load the current dashboard layout',\n description: 'Returns the saved widget layout together with the widgets the current user is allowed to place.',\n tags: [dashboardsTag],\n responses: [\n {\n status: 200,\n description: 'Current dashboard layout and available widgets.',\n schema: dashboardLayoutStateSchema,\n },\n ],\n errors: [\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n ],\n}\n\nconst layoutPutDoc: OpenApiMethodDoc = {\n summary: 'Persist dashboard layout changes',\n description: 'Saves the provided widget ordering, sizes, and settings for the current user.',\n tags: [dashboardsTag],\n requestBody: {\n contentType: 'application/json',\n schema: dashboardLayoutSchema,\n description: 'List of dashboard widgets with ordering, sizing, and settings.',\n },\n responses: [\n { status: 200, description: 'Layout updated successfully.', schema: dashboardsOkSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid layout payload', schema: dashboardsErrorSchema },\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n { status: 403, description: 'Missing dashboards.configure feature', schema: dashboardsErrorSchema },\n { status: 503, description: 'Widget registry unavailable \u2014 the layout was not saved', schema: dashboardsErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dashboardsTag,\n summary: 'Manage personal dashboard layout',\n methods: {\n GET: layoutGetDoc,\n PUT: layoutPutDoc,\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,yBAAyB;AAClC,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,eAAe;AACrB,MAAM,gBAAgB;AAEf,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AAAA,EAC/D,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,sBAAsB,EAAE;AACtE;AAQA,eAAe,gBAAgB,IAAS,OAAqD;AAC3F,SAAO,MAAM,GAAG,QAAQ,iBAAiB;AAAA,IACvC,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,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AQ,IAAI,EAAU,KAAK,EAAE,OAAO,MAAM,mBAAmB,MAAM,YAAY,KAAK,CAAC;AAC3G,QAAM,OAAO,UAAU,QAAQ,aAAa;AAC5C,QAAM,MAAM,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { randomUUID } from 'node:crypto'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { DashboardLayout } from '@open-mercato/core/modules/dashboards/data/entities'\nimport { dashboardLayoutSchema } from '@open-mercato/core/modules/dashboards/data/validators'\nimport { loadAllWidgets } from '@open-mercato/core/modules/dashboards/lib/widgets'\nimport { resolveAllowedWidgetIds } from '@open-mercato/core/modules/dashboards/lib/access'\nimport { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveUserDataSubject } from '@open-mercato/core/modules/auth/lib/userDataSubject'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n dashboardsTag,\n dashboardsErrorSchema,\n dashboardsOkSchema,\n dashboardLayoutStateSchema,\n} from '../openapi'\n\nconst DEFAULT_SIZE = 'md'\nconst RESOURCE_KIND = 'dashboards.layout'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['dashboards.view'] },\n PUT: { requireAuth: true, requireFeatures: ['dashboards.configure'] },\n}\n\ntype LayoutScope = {\n userId: string\n tenantId: string | null\n organizationId: string | null\n}\n\nasync function loadScopeLayout(em: any, scope: LayoutScope): Promise<DashboardLayout | null> {\n return await em.findOne(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n })\n}\n\nfunction normalizeLayoutItems(items: any[]) {\n const list = Array.isArray(items) ? items : []\n const seenIds = new Set<string>()\n const sanitized = list\n .filter((item) => item && typeof item === 'object')\n .map((item) => ({\n id: String(item.id),\n widgetId: String(item.widgetId),\n order: Number.isInteger(item.order) ? Number(item.order) : undefined,\n priority: Number.isInteger(item.priority) ? Number(item.priority) : undefined,\n size: typeof item.size === 'string' ? item.size : undefined,\n settings: item.settings,\n }))\n .filter((item) => {\n if (!item.id || !item.widgetId) return false\n if (seenIds.has(item.id)) return false\n seenIds.add(item.id)\n return true\n })\n .sort((a, b) => {\n const aOrder = a.order ?? a.priority ?? 0\n const bOrder = b.order ?? b.priority ?? 0\n return aOrder - bOrder\n })\n .map((item, idx) => ({ ...item, order: idx, priority: idx }))\n return sanitized\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n // Use a fresh fork to avoid carrying over pending entities from other operations\n const em = (container.resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = container.resolve('rbacService') as any\n const userId = await resolveUserDataSubject(em, auth)\n if (!userId) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })\n }\n\n const scope: LayoutScope = {\n userId,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const effectiveFeatures = await rbac.getEffectiveFeatures(auth.sub, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const widgets = await loadAllWidgets()\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedWidgets = widgets.filter((w) => allowedIds.includes(w.metadata.id))\n\n // An empty widget registry means the module registry has not been populated yet\n // (a boot race), not that this app has no widgets. Every write below is derived\n // from it, so a read request must persist nothing until it recovers \u2014 otherwise a\n // restart-recoverable glitch is written into saved layouts for good (#5041).\n // Note this keys off the registry, not off `allowedIds`: a user whose allowlist is\n // legitimately empty on a healthy registry is still pruned and seeded as before.\n const hasRegisteredWidgets = widgets.length > 0\n\n let layout = await loadScopeLayout(em, scope)\n let items = layout ? normalizeLayoutItems(layout.layoutJson) : []\n let hasChanged = false\n\n if (!layout) {\n const defaults = allowedWidgets.filter((widget) => widget.metadata.defaultEnabled)\n items = defaults.map((widget, index) => ({\n id: randomUUID(),\n widgetId: widget.metadata.id,\n order: index,\n priority: index,\n size: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n settings: widget.metadata.defaultSettings ?? undefined,\n }))\n if (hasRegisteredWidgets && !auth.isApiKey) {\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: items,\n })\n em.persist(layout)\n hasChanged = true\n }\n } else if (hasRegisteredWidgets || auth.isApiKey) {\n const existingLayout = layout\n const filtered = items.filter((item) => allowedIds.includes(item.widgetId))\n if (filtered.length !== items.length) {\n hasChanged = true\n items = filtered\n }\n items = items.map((item, index) => (item.order !== index || item.priority !== index ? { ...item, order: index, priority: index } : item))\n if (\n existingLayout.layoutJson.length !== items.length ||\n items.some((item, idx) => existingLayout.layoutJson[idx]?.id !== item.id)\n ) {\n hasChanged = true\n }\n if (!auth.isApiKey) existingLayout.layoutJson = items\n layout = existingLayout\n }\n\n if (hasChanged && !auth.isApiKey) {\n await em.flush()\n }\n\n const canConfigure = authorizeFeatures(['dashboards.configure'], {\n grantedFeatures: effectiveFeatures,\n })\n\n let userEmail: string | null = null\n let userName: string | null = null\n let userLabel: string | null = null\n const user = await findOneWithDecryption(\n em,\n User,\n { id: scope.userId, deletedAt: null },\n undefined,\n { tenantId: scope.tenantId ?? null, organizationId: scope.organizationId ?? null },\n )\n if (user) {\n userName = user.name?.trim() ?? null\n userEmail = user.email ?? null\n userLabel = (userName && userName.length > 0 ? userName : userEmail) ?? null\n }\n if (!userLabel) {\n userLabel = scope.userId\n }\n\n const response = {\n layout: { items },\n allowedWidgetIds: allowedIds,\n canConfigure,\n context: {\n ...scope,\n userName,\n userEmail,\n userLabel,\n },\n widgets: allowedWidgets.map((widget) => ({\n id: widget.metadata.id,\n title: widget.metadata.title,\n description: widget.metadata.description ?? null,\n defaultSize: widget.metadata.defaultSize ?? DEFAULT_SIZE,\n defaultEnabled: !!widget.metadata.defaultEnabled,\n defaultSettings: widget.metadata.defaultSettings ?? null,\n features: widget.metadata.features ?? [],\n moduleId: widget.moduleId,\n icon: widget.metadata.icon ?? null,\n loaderKey: widget.key,\n supportsRefresh: !!widget.metadata.supportsRefresh,\n })),\n }\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })\n }\n const parsed = dashboardLayoutSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid layout payload', issues: parsed.error.issues }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const { resolve } = container\n const em = (resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })\n const rbac = resolve('rbacService') as any\n\n const userId = await resolveUserDataSubject(em, auth)\n if (!userId) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })\n }\n\n const scope: LayoutScope = {\n userId,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n }\n\n const canConfigure = await rbac.userHasAllFeatures(\n auth.sub,\n ['dashboards.configure'],\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n if (!canConfigure) {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: auth.sub,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: { items: parsed.data.items },\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const widgets = await loadAllWidgets()\n // The allowlist below is derived from the registry, and this handler persists the\n // filtered result unconditionally. An empty registry \u2014 the boot race behind #5041 \u2014\n // would drop every submitted item and save `[]` while answering `{ ok: true }`, so a\n // stale tab reordering a widget could erase the layout it just rendered. Fail the\n // write instead: the save is explicit, so the client must learn it did not happen\n // and retry, rather than be told a wipe succeeded.\n if (widgets.length === 0) {\n return NextResponse.json({ error: 'Widget registry unavailable' }, { status: 503 })\n }\n const effectiveFeatures = await rbac.getEffectiveFeatures(auth.sub, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n const allowedIds = await resolveAllowedWidgetIds(\n em,\n {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n features: effectiveFeatures,\n isSuperAdmin: false,\n },\n widgets,\n )\n const allowedSet = new Set(allowedIds)\n\n const payloadItems = parsed.data.items\n const sanitized = payloadItems\n .map((item, index) => ({\n id: item.id,\n widgetId: item.widgetId,\n order: index,\n priority: index,\n size: item.size ?? DEFAULT_SIZE,\n settings: item.settings,\n }))\n .filter((item) => allowedSet.has(item.widgetId))\n\n const uniqueIds = new Set(sanitized.map((item) => item.id))\n if (uniqueIds.size !== sanitized.length) {\n return NextResponse.json({ error: 'Layout item IDs must be unique' }, { status: 400 })\n }\n\n let layout = await loadScopeLayout(em, scope)\n if (!layout) {\n layout = em.create(DashboardLayout, {\n userId: scope.userId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n layoutJson: sanitized,\n })\n em.persist(layout)\n } else {\n layout.layoutJson = sanitized\n }\n await em.flush()\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: scope.tenantId ?? '',\n organizationId: scope.organizationId,\n userId: auth.sub,\n resourceKind: RESOURCE_KIND,\n resourceId: scope.userId,\n operation: 'update',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true })\n}\n\nconst layoutGetDoc: OpenApiMethodDoc = {\n summary: 'Load the current dashboard layout',\n description: 'Returns the saved widget layout together with the widgets the current user is allowed to place.',\n tags: [dashboardsTag],\n responses: [\n {\n status: 200,\n description: 'Current dashboard layout and available widgets.',\n schema: dashboardLayoutStateSchema,\n },\n ],\n errors: [\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n { status: 403, description: 'No user binding in the authenticated scope', schema: dashboardsErrorSchema },\n ],\n}\n\nconst layoutPutDoc: OpenApiMethodDoc = {\n summary: 'Persist dashboard layout changes',\n description: 'Saves the provided widget ordering, sizes, and settings for the current user.',\n tags: [dashboardsTag],\n requestBody: {\n contentType: 'application/json',\n schema: dashboardLayoutSchema,\n description: 'List of dashboard widgets with ordering, sizing, and settings.',\n },\n responses: [\n { status: 200, description: 'Layout updated successfully.', schema: dashboardsOkSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid layout payload', schema: dashboardsErrorSchema },\n { status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },\n { status: 403, description: 'Missing dashboards.configure feature', schema: dashboardsErrorSchema },\n { status: 503, description: 'Widget registry unavailable \u2014 the layout was not saved', schema: dashboardsErrorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: dashboardsTag,\n summary: 'Manage personal dashboard layout',\n methods: {\n GET: layoutGetDoc,\n PUT: layoutPutDoc,\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACv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WAAW;AAAA,IACT;AAAA,MACE,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAAA,EACF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,IACrF,EAAE,QAAQ,KAAK,aAAa,8CAA8C,QAAQ,sBAAsB;AAAA,EAC1G;AACF;AAEA,MAAM,eAAiC;AAAA,EACrC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,aAAa;AAAA,EACpB,aAAa;AAAA,IACX,aAAa;AAAA,IACb,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,mBAAmB;AAAA,EACzF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,sBAAsB;AAAA,IACpF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,sBAAsB;AAAA,IACrF,EAAE,QAAQ,KAAK,aAAa,wCAAwC,QAAQ,sBAAsB;AAAA,IAClG,EAAE,QAAQ,KAAK,aAAa,+DAA0D,QAAQ,sBAAsB;AAAA,EACtH;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.7763.1.caea616ebf",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -266,16 +266,16 @@
|
|
|
266
266
|
"zod": "^4.4.3"
|
|
267
267
|
},
|
|
268
268
|
"peerDependencies": {
|
|
269
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
270
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
271
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
269
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.7763.1.caea616ebf",
|
|
270
|
+
"@open-mercato/shared": "0.10.1-develop.7763.1.caea616ebf",
|
|
271
|
+
"@open-mercato/ui": "0.10.1-develop.7763.1.caea616ebf",
|
|
272
272
|
"react": "^19.0.0",
|
|
273
273
|
"react-dom": "^19.0.0"
|
|
274
274
|
},
|
|
275
275
|
"devDependencies": {
|
|
276
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
277
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
278
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
276
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.7763.1.caea616ebf",
|
|
277
|
+
"@open-mercato/shared": "0.10.1-develop.7763.1.caea616ebf",
|
|
278
|
+
"@open-mercato/ui": "0.10.1-develop.7763.1.caea616ebf",
|
|
279
279
|
"@testing-library/dom": "^10.4.1",
|
|
280
280
|
"@testing-library/jest-dom": "^7.0.1",
|
|
281
281
|
"@testing-library/react": "^16.3.3",
|
|
@@ -14,6 +14,7 @@ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
|
14
14
|
import { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'
|
|
15
15
|
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
16
16
|
import { getCommandInterceptorHttpRejection } from '@open-mercato/shared/lib/commands/errors'
|
|
17
|
+
import { resolveUserDataSubject } from '@open-mercato/core/modules/auth/lib/userDataSubject'
|
|
17
18
|
|
|
18
19
|
const logger = createLogger('auth').child({ component: 'profile' })
|
|
19
20
|
|
|
@@ -98,10 +99,18 @@ export async function GET(req: Request) {
|
|
|
98
99
|
try {
|
|
99
100
|
const container = await createRequestContainer()
|
|
100
101
|
const em = (container.resolve('em') as EntityManager)
|
|
102
|
+
const userId = await resolveUserDataSubject(em, auth)
|
|
103
|
+
if (!userId) {
|
|
104
|
+
return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })
|
|
105
|
+
}
|
|
101
106
|
const user = await findOneWithDecryption(
|
|
102
107
|
em,
|
|
103
108
|
User,
|
|
104
|
-
{
|
|
109
|
+
{
|
|
110
|
+
id: userId,
|
|
111
|
+
deletedAt: null,
|
|
112
|
+
...(auth.isApiKey ? { tenantId: auth.tenantId, ...(auth.orgId ? { organizationId: auth.orgId } : {}) } : {}),
|
|
113
|
+
},
|
|
105
114
|
undefined,
|
|
106
115
|
{ tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null },
|
|
107
116
|
)
|
|
@@ -126,6 +135,9 @@ export async function PUT(req: Request) {
|
|
|
126
135
|
if (!auth?.sub) {
|
|
127
136
|
return NextResponse.json({ error: translate('api.errors.unauthorized', 'Unauthorized') }, { status: 401 })
|
|
128
137
|
}
|
|
138
|
+
if (auth.isApiKey) {
|
|
139
|
+
return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })
|
|
140
|
+
}
|
|
129
141
|
try {
|
|
130
142
|
const body = await req.json().catch(() => ({}))
|
|
131
143
|
const parsed = buildUpdateSchema(translate).safeParse(body)
|
|
@@ -222,6 +234,7 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
222
234
|
responses: [
|
|
223
235
|
{ status: 200, description: 'Profile payload', schema: profileResponseSchema },
|
|
224
236
|
{ status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },
|
|
237
|
+
{ status: 403, description: 'No user binding in the authenticated scope', schema: z.object({ error: z.string() }) },
|
|
225
238
|
{ status: 404, description: 'User not found', schema: z.object({ error: z.string() }) },
|
|
226
239
|
],
|
|
227
240
|
},
|
|
@@ -236,6 +249,7 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
236
249
|
{ status: 200, description: 'Profile updated', schema: profileUpdateResponseSchema },
|
|
237
250
|
{ status: 400, description: 'Invalid payload', schema: z.object({ error: z.string() }) },
|
|
238
251
|
{ status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },
|
|
252
|
+
{ status: 403, description: 'Interactive session required', schema: z.object({ error: z.string() }) },
|
|
239
253
|
],
|
|
240
254
|
},
|
|
241
255
|
},
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
3
|
+
import type { AuthContext } from '@open-mercato/shared/lib/auth/server'
|
|
4
|
+
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
5
|
+
import { User } from '../data/entities'
|
|
6
|
+
|
|
7
|
+
const uuidSchema = z.string().uuid()
|
|
8
|
+
|
|
9
|
+
export async function resolveUserDataSubject(
|
|
10
|
+
em: EntityManager,
|
|
11
|
+
auth: NonNullable<AuthContext>,
|
|
12
|
+
): Promise<string | null> {
|
|
13
|
+
if (!auth.isApiKey) return auth.sub
|
|
14
|
+
if (!uuidSchema.safeParse(auth.userId).success || !uuidSchema.safeParse(auth.tenantId).success) return null
|
|
15
|
+
if (auth.orgId !== null && !uuidSchema.safeParse(auth.orgId).success) return null
|
|
16
|
+
|
|
17
|
+
const user = await findOneWithDecryption(
|
|
18
|
+
em,
|
|
19
|
+
User,
|
|
20
|
+
{
|
|
21
|
+
id: auth.userId,
|
|
22
|
+
tenantId: auth.tenantId,
|
|
23
|
+
...(auth.orgId ? { organizationId: auth.orgId } : {}),
|
|
24
|
+
deletedAt: null,
|
|
25
|
+
},
|
|
26
|
+
undefined,
|
|
27
|
+
{ tenantId: auth.tenantId, organizationId: auth.orgId },
|
|
28
|
+
)
|
|
29
|
+
return user?.id ?? null
|
|
30
|
+
}
|
|
@@ -2,6 +2,8 @@ import { NextResponse } from 'next/server'
|
|
|
2
2
|
import { z } from 'zod'
|
|
3
3
|
import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
4
4
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
5
|
+
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
6
|
+
import { resolveUserDataSubject } from '@open-mercato/core/modules/auth/lib/userDataSubject'
|
|
5
7
|
import { DashboardLayout } from '@open-mercato/core/modules/dashboards/data/entities'
|
|
6
8
|
import { dashboardLayoutItemPatchSchema } from '@open-mercato/core/modules/dashboards/data/validators'
|
|
7
9
|
import {
|
|
@@ -48,14 +50,20 @@ export async function PATCH(req: Request, ctx: { params?: { itemId?: string } })
|
|
|
48
50
|
const em = resolve('em') as any
|
|
49
51
|
const rbac = resolve('rbacService') as any
|
|
50
52
|
|
|
53
|
+
const userId = await resolveUserDataSubject(em, auth)
|
|
54
|
+
if (!userId) {
|
|
55
|
+
const { translate } = await resolveTranslations()
|
|
56
|
+
return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })
|
|
57
|
+
}
|
|
58
|
+
|
|
51
59
|
const scope = {
|
|
52
|
-
userId
|
|
60
|
+
userId,
|
|
53
61
|
tenantId: auth.tenantId ?? null,
|
|
54
62
|
organizationId: auth.orgId ?? null,
|
|
55
63
|
}
|
|
56
64
|
|
|
57
65
|
const canConfigure = await rbac.userHasAllFeatures(
|
|
58
|
-
|
|
66
|
+
auth.sub,
|
|
59
67
|
['dashboards.configure'],
|
|
60
68
|
{ tenantId: scope.tenantId, organizationId: scope.organizationId },
|
|
61
69
|
)
|
|
@@ -66,7 +74,7 @@ export async function PATCH(req: Request, ctx: { params?: { itemId?: string } })
|
|
|
66
74
|
const guardResult = await validateCrudMutationGuard(container, {
|
|
67
75
|
tenantId: scope.tenantId ?? '',
|
|
68
76
|
organizationId: scope.organizationId,
|
|
69
|
-
userId:
|
|
77
|
+
userId: auth.sub,
|
|
70
78
|
resourceKind: RESOURCE_KIND,
|
|
71
79
|
resourceId: layoutItemId,
|
|
72
80
|
operation: 'update',
|
|
@@ -105,7 +113,7 @@ export async function PATCH(req: Request, ctx: { params?: { itemId?: string } })
|
|
|
105
113
|
await runCrudMutationGuardAfterSuccess(container, {
|
|
106
114
|
tenantId: scope.tenantId ?? '',
|
|
107
115
|
organizationId: scope.organizationId,
|
|
108
|
-
userId:
|
|
116
|
+
userId: auth.sub,
|
|
109
117
|
resourceKind: RESOURCE_KIND,
|
|
110
118
|
resourceId: layoutItemId,
|
|
111
119
|
operation: 'update',
|
|
@@ -9,6 +9,8 @@ import { resolveAllowedWidgetIds } from '@open-mercato/core/modules/dashboards/l
|
|
|
9
9
|
import { authorizeFeatures } from '@open-mercato/shared/security/featurePolicy'
|
|
10
10
|
import { User } from '@open-mercato/core/modules/auth/data/entities'
|
|
11
11
|
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
12
|
+
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
13
|
+
import { resolveUserDataSubject } from '@open-mercato/core/modules/auth/lib/userDataSubject'
|
|
12
14
|
import {
|
|
13
15
|
runCrudMutationGuardAfterSuccess,
|
|
14
16
|
validateCrudMutationGuard,
|
|
@@ -80,15 +82,19 @@ export async function GET(req: Request) {
|
|
|
80
82
|
// Use a fresh fork to avoid carrying over pending entities from other operations
|
|
81
83
|
const em = (container.resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })
|
|
82
84
|
const rbac = container.resolve('rbacService') as any
|
|
83
|
-
const
|
|
85
|
+
const userId = await resolveUserDataSubject(em, auth)
|
|
86
|
+
if (!userId) {
|
|
87
|
+
const { translate } = await resolveTranslations()
|
|
88
|
+
return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })
|
|
89
|
+
}
|
|
84
90
|
|
|
85
91
|
const scope: LayoutScope = {
|
|
86
|
-
userId
|
|
92
|
+
userId,
|
|
87
93
|
tenantId: auth.tenantId ?? null,
|
|
88
94
|
organizationId: auth.orgId ?? null,
|
|
89
95
|
}
|
|
90
96
|
|
|
91
|
-
const effectiveFeatures = await rbac.getEffectiveFeatures(
|
|
97
|
+
const effectiveFeatures = await rbac.getEffectiveFeatures(auth.sub, {
|
|
92
98
|
tenantId: scope.tenantId,
|
|
93
99
|
organizationId: scope.organizationId,
|
|
94
100
|
})
|
|
@@ -128,7 +134,7 @@ export async function GET(req: Request) {
|
|
|
128
134
|
size: widget.metadata.defaultSize ?? DEFAULT_SIZE,
|
|
129
135
|
settings: widget.metadata.defaultSettings ?? undefined,
|
|
130
136
|
}))
|
|
131
|
-
if (hasRegisteredWidgets) {
|
|
137
|
+
if (hasRegisteredWidgets && !auth.isApiKey) {
|
|
132
138
|
layout = em.create(DashboardLayout, {
|
|
133
139
|
userId: scope.userId,
|
|
134
140
|
tenantId: scope.tenantId,
|
|
@@ -138,7 +144,7 @@ export async function GET(req: Request) {
|
|
|
138
144
|
em.persist(layout)
|
|
139
145
|
hasChanged = true
|
|
140
146
|
}
|
|
141
|
-
} else if (hasRegisteredWidgets) {
|
|
147
|
+
} else if (hasRegisteredWidgets || auth.isApiKey) {
|
|
142
148
|
const existingLayout = layout
|
|
143
149
|
const filtered = items.filter((item) => allowedIds.includes(item.widgetId))
|
|
144
150
|
if (filtered.length !== items.length) {
|
|
@@ -152,11 +158,11 @@ export async function GET(req: Request) {
|
|
|
152
158
|
) {
|
|
153
159
|
hasChanged = true
|
|
154
160
|
}
|
|
155
|
-
existingLayout.layoutJson = items
|
|
161
|
+
if (!auth.isApiKey) existingLayout.layoutJson = items
|
|
156
162
|
layout = existingLayout
|
|
157
163
|
}
|
|
158
164
|
|
|
159
|
-
if (hasChanged) {
|
|
165
|
+
if (hasChanged && !auth.isApiKey) {
|
|
160
166
|
await em.flush()
|
|
161
167
|
}
|
|
162
168
|
|
|
@@ -231,14 +237,20 @@ export async function PUT(req: Request) {
|
|
|
231
237
|
const em = (resolve('em') as any).fork({ clear: true, freshEventManager: true, useContext: true })
|
|
232
238
|
const rbac = resolve('rbacService') as any
|
|
233
239
|
|
|
240
|
+
const userId = await resolveUserDataSubject(em, auth)
|
|
241
|
+
if (!userId) {
|
|
242
|
+
const { translate } = await resolveTranslations()
|
|
243
|
+
return NextResponse.json({ error: translate('api.errors.forbidden', 'Forbidden') }, { status: 403 })
|
|
244
|
+
}
|
|
245
|
+
|
|
234
246
|
const scope: LayoutScope = {
|
|
235
|
-
userId
|
|
247
|
+
userId,
|
|
236
248
|
tenantId: auth.tenantId ?? null,
|
|
237
249
|
organizationId: auth.orgId ?? null,
|
|
238
250
|
}
|
|
239
251
|
|
|
240
252
|
const canConfigure = await rbac.userHasAllFeatures(
|
|
241
|
-
|
|
253
|
+
auth.sub,
|
|
242
254
|
['dashboards.configure'],
|
|
243
255
|
{ tenantId: scope.tenantId, organizationId: scope.organizationId },
|
|
244
256
|
)
|
|
@@ -249,7 +261,7 @@ export async function PUT(req: Request) {
|
|
|
249
261
|
const guardResult = await validateCrudMutationGuard(container, {
|
|
250
262
|
tenantId: scope.tenantId ?? '',
|
|
251
263
|
organizationId: scope.organizationId,
|
|
252
|
-
userId:
|
|
264
|
+
userId: auth.sub,
|
|
253
265
|
resourceKind: RESOURCE_KIND,
|
|
254
266
|
resourceId: scope.userId,
|
|
255
267
|
operation: 'update',
|
|
@@ -271,7 +283,7 @@ export async function PUT(req: Request) {
|
|
|
271
283
|
if (widgets.length === 0) {
|
|
272
284
|
return NextResponse.json({ error: 'Widget registry unavailable' }, { status: 503 })
|
|
273
285
|
}
|
|
274
|
-
const effectiveFeatures = await rbac.getEffectiveFeatures(
|
|
286
|
+
const effectiveFeatures = await rbac.getEffectiveFeatures(auth.sub, {
|
|
275
287
|
tenantId: scope.tenantId,
|
|
276
288
|
organizationId: scope.organizationId,
|
|
277
289
|
})
|
|
@@ -323,7 +335,7 @@ export async function PUT(req: Request) {
|
|
|
323
335
|
await runCrudMutationGuardAfterSuccess(container, {
|
|
324
336
|
tenantId: scope.tenantId ?? '',
|
|
325
337
|
organizationId: scope.organizationId,
|
|
326
|
-
userId:
|
|
338
|
+
userId: auth.sub,
|
|
327
339
|
resourceKind: RESOURCE_KIND,
|
|
328
340
|
resourceId: scope.userId,
|
|
329
341
|
operation: 'update',
|
|
@@ -349,6 +361,7 @@ const layoutGetDoc: OpenApiMethodDoc = {
|
|
|
349
361
|
],
|
|
350
362
|
errors: [
|
|
351
363
|
{ status: 401, description: 'Authentication required', schema: dashboardsErrorSchema },
|
|
364
|
+
{ status: 403, description: 'No user binding in the authenticated scope', schema: dashboardsErrorSchema },
|
|
352
365
|
],
|
|
353
366
|
}
|
|
354
367
|
|