Skip to content

Ent Privacy Layer: Data Access Control

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Ent Privacy Layer: Data Access Control. We cover key concepts, practical examples, and best practices.

Ent privacy layer -- Implement row-level access control in Ent using the privacy layer to filter queries by user permissions.

The Problem

Ent's privacy layer lets you define who can read, create, update, or delete data. Without it, all queries return all records.

Wrong

users, _ := client.User.Query().All(ctx)
// All users visible to everyone!

Output:

// No access control -- data leak
func (User) Policy() ent.Policy {
    return ent.Policy{
        Query: ent.QueryPolicy{
            privacy.AlwaysAllowIf(func(ctx context.Context) bool {
                return isAdmin(ctx)
            }),
            privacy.Filter(func(ctx context.Context, f *sql.Filter) error {
                f.Where("user_id = ?", userIDFromCtx(ctx))
                return nil
            }),
        },
    }
}

Output:

// Admin sees all. Regular user sees own records only.

Prevention

  • Define DenyIfNoRule as fallback
  • Use AllowIf/DenyIf with context-checking rules
  • Use PrivacyFilter for row-level restrictions
  • Attach user identity to context in middleware
  • Test privacy rules with mock context values

Common Mistakes with ent privacy

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Does Ent privacy work with GraphQL?**

Yes. Privacy rules apply to all queries including GraphQL.

Can privacy access mutation type?

Yes. Mutation interface exposes Create/Update/Delete type.

How to skip privacy for admins?

AlwaysAllowIf(isAdmin(ctx)) at top of policy chain.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro