Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions packages/runtime/src/enhancements/default-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { DefaultPrismaProxyHandler, PrismaProxyActions, makeProxy } from './prox
export function withDefaultAuth<DbClient extends object>(
prisma: DbClient,
options: InternalEnhancementOptions,
context?: EnhancementContext
context: EnhancementContext = {}
): DbClient {
return makeProxy(
prisma,
Expand All @@ -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;
}

Expand Down Expand Up @@ -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);
}
}
29 changes: 29 additions & 0 deletions tests/integration/tests/enhancements/with-policy/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});