diff --git a/packages/runtime/src/enhancements/default-auth.ts b/packages/runtime/src/enhancements/default-auth.ts index 78294f28b..56e43ab29 100644 --- a/packages/runtime/src/enhancements/default-auth.ts +++ b/packages/runtime/src/enhancements/default-auth.ts @@ -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 diff --git a/tests/integration/tests/enhancements/with-policy/auth.test.ts b/tests/integration/tests/enhancements/with-policy/auth.test.ts index 9079da045..0cac82e8a 100644 --- a/tests/integration/tests/enhancements/with-policy/auth.test.ts +++ b/tests/integration/tests/enhancements/with-policy/auth.test.ts @@ -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) @@ -438,9 +439,23 @@ describe('auth() runtime test', () => { ` ); + await prisma.user.create({ data: { id: 'userId-1', email: 'user1@abc.com' } }); + await prisma.user.create({ data: { id: 'userId-2', email: 'user2@abc.com' } }); + 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: 'user1@abc.com' } } } }) + ).resolves.toMatchObject({ authorId: 'userId-1' }); + + // default auth ineffective due to explicit connect + await expect( + db.post.create({ data: { title: 'post3', author: { connect: { email: 'user2@abc.com' } } } }) + ).resolves.toMatchObject({ authorId: 'userId-2' }); }); it('Default auth() with nested user context value', async () => {