Ent Privacy Layer: Data Access Control
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
Right
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
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead 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
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