diff --git a/packages/runtime/src/enhancements/default-auth.ts b/packages/runtime/src/enhancements/default-auth.ts index cce9af782..bbbd35861 100644 --- a/packages/runtime/src/enhancements/default-auth.ts +++ b/packages/runtime/src/enhancements/default-auth.ts @@ -15,7 +15,7 @@ import { DefaultPrismaProxyHandler, PrismaProxyActions, makeProxy } from './prox export function withDefaultAuth( prisma: DbClient, options: InternalEnhancementOptions, - context?: EnhancementContext + context: EnhancementContext = {} ): DbClient { return makeProxy( prisma, @@ -32,14 +32,10 @@ class DefaultAuthHandler extends DefaultPrismaProxyHandler { prisma: DbClientContract, model: string, options: InternalEnhancementOptions, - private readonly context?: EnhancementContext + private readonly context: EnhancementContext ) { super(prisma, model, options); - if (!this.context?.user) { - throw new Error(`Using \`auth()\` in \`@default\` requires a user context`); - } - this.userContext = this.context.user; } @@ -95,6 +91,9 @@ class DefaultAuthHandler extends DefaultPrismaProxyHandler { } private getDefaultValueFromAuth(fieldInfo: FieldInfo) { + if (!this.userContext) { + throw new Error(`Evaluating default value of field \`${fieldInfo.name}\` requires a user context`); + } return fieldInfo.defaultValueProvider?.(this.userContext); } } diff --git a/tests/integration/tests/enhancements/with-policy/auth.test.ts b/tests/integration/tests/enhancements/with-policy/auth.test.ts index f5b4e2f4f..e1fff4f73 100644 --- a/tests/integration/tests/enhancements/with-policy/auth.test.ts +++ b/tests/integration/tests/enhancements/with-policy/auth.test.ts @@ -505,4 +505,33 @@ describe('With Policy: auth() test', () => { ]) ); }); + + it('Default auth() without user context', async () => { + const { enhance } = await loadSchema( + ` + model User { + id String @id + posts Post[] + + @@allow('all', true) + } + + model Post { + id String @id @default(uuid()) + title String + author User @relation(fields: [authorId], references: [id]) + authorId String @default(auth().id) + + @@allow('all', true) + } + ` + ); + + const db = enhance(); + await expect(db.user.create({ data: { id: 'userId-1' } })).toResolveTruthy(); + await expect(db.post.create({ data: { title: 'title' } })).rejects.toThrow( + 'Evaluating default value of field `authorId` requires a user context' + ); + await expect(db.post.findMany({})).toResolveTruthy(); + }); });