Skip to content

Commit

Permalink
fix: default auth without user context (#1015)
Browse files Browse the repository at this point in the history
  • Loading branch information
Azzerty23 authored Feb 22, 2024
1 parent 6d043a5 commit e5b5a0f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
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();
});
});

0 comments on commit e5b5a0f

Please sign in to comment.