Skip to content

Commit

Permalink
fix: issue with auth() in @default accidentally overrides "connec…
Browse files Browse the repository at this point in the history
…t" (#1248)
  • Loading branch information
ymc9 authored Apr 13, 2024
1 parent 81c7e87 commit 2a8db68
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
5 changes: 5 additions & 0 deletions packages/runtime/src/enhancements/default-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ class DefaultAuthHandler extends DefaultPrismaProxyHandler {
}

private setAuthDefaultValue(fieldInfo: FieldInfo, model: string, data: any, authDefaultValue: unknown) {
if (fieldInfo.isForeignKey && fieldInfo.relationField && fieldInfo.relationField in data) {
// if the field is a fk, and the relation field is already set, we should not override it
return;
}

if (fieldInfo.isForeignKey && !isUnsafeMutate(model, data, this.options.modelMeta)) {
// if the field is a fk, and the create payload is not unsafe, we need to translate
// the fk field setting to a `connect` of the corresponding relation field
Expand Down
21 changes: 18 additions & 3 deletions tests/integration/tests/enhancements/with-policy/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,10 +417,11 @@ describe('auth() runtime test', () => {
});

it('Default auth() with foreign key', async () => {
const { enhance, modelMeta } = await loadSchema(
const { enhance, prisma } = await loadSchema(
`
model User {
id String @id
email String @unique
posts Post[]
@@allow('all', true)
Expand All @@ -438,9 +439,23 @@ describe('auth() runtime test', () => {
`
);

await prisma.user.create({ data: { id: 'userId-1', email: '[email protected]' } });
await prisma.user.create({ data: { id: 'userId-2', email: '[email protected]' } });

const db = enhance({ id: 'userId-1' });
await expect(db.user.create({ data: { id: 'userId-1' } })).toResolveTruthy();
await expect(db.post.create({ data: { title: 'abc' } })).resolves.toMatchObject({ authorId: 'userId-1' });

// default auth effective
await expect(db.post.create({ data: { title: 'post1' } })).resolves.toMatchObject({ authorId: 'userId-1' });

// default auth ineffective due to explicit connect
await expect(
db.post.create({ data: { title: 'post2', author: { connect: { email: '[email protected]' } } } })
).resolves.toMatchObject({ authorId: 'userId-1' });

// default auth ineffective due to explicit connect
await expect(
db.post.create({ data: { title: 'post3', author: { connect: { email: '[email protected]' } } } })
).resolves.toMatchObject({ authorId: 'userId-2' });
});

it('Default auth() with nested user context value', async () => {
Expand Down

0 comments on commit 2a8db68

Please sign in to comment.