Skip to content

Commit

Permalink
fix: Policy generator error for Auth() with multiple level member access
Browse files Browse the repository at this point in the history
  • Loading branch information
jiashengguo committed Jan 2, 2024
1 parent 9d6a33e commit d0f0a01
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -461,8 +461,9 @@ export class ExpressionWriter {
this.writer.write(`db.${lowerCaseFirst(containingModel.name)}.fields.${expr.target.ref.name}`);
}

private isAuthOrAuthMemberAccess(expr: Expression) {
return isAuthInvocation(expr) || (isMemberAccessExpr(expr) && isAuthInvocation(expr.operand));
private isAuthOrAuthMemberAccess(expr: Expression): boolean {
// recursive check for auth().x.y.z
return isAuthInvocation(expr) || (isMemberAccessExpr(expr) && this.isAuthOrAuthMemberAccess(expr.operand));
}

private writeOperator(operator: ComparisonOperator, fieldAccess: Expression, writeOperand: () => void) {
Expand Down
32 changes: 32 additions & 0 deletions tests/integration/tests/plugins/policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,36 @@ model M {
expect.objectContaining({ AND: [{ AND: [] }, { value: { gt: 0 } }] })
);
});
it('auth() multiple level member access', async () => {
const model = `
model User {
id Int @id @default(autoincrement())
cart Cart?
}
model Cart {
id Int @id @default(autoincrement())
tasks Task[]
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
model Task {
id Int @id @default(autoincrement())
cart Cart @relation(fields: [cartId], references: [id])
cartId Int
value Int
@@allow('read', auth().cart.tasks?[id == 123] && value >10)
}
`;

const { policy } = await loadSchema(model);
expect(policy.guard.task.read({ user: { cart: { tasks: [{ id: 1 }] } } })).toEqual(
expect.objectContaining({ AND: [{ OR: [] }, { value: { gt: 10 } }] })
);

expect(policy.guard.task.read({ user: { cart: { tasks: [{ id: 123 }] } } })).toEqual(
expect.objectContaining({ AND: [{ AND: [] }, { value: { gt: 10 } }] })
);
});
});

0 comments on commit d0f0a01

Please sign in to comment.