Rules
Rules
Rules are the basic building blocks of Entitled. Fundamentally, a Rule
is a
simple wrapper around a standard, boolean-returning Python function.
Semantically, Rules describes "facts" about your application and about the relationships between the various actors and resources of your app.
Writing Rules
is_admin = Rule("is_admin", lambda actor, resource, context: resource.owner = actor)
The Rule
constructor takes two parameters: a str
representing the rule's identifier, and a boolean-returning Callable
.
A Rule can (and likely should) also take two generic parameters: ActorModel
and ResourceModel
, identifying what type of actor object and resource object this rule applies. This serves primarily for type-hinting purposes, but also serves as checks for policies grouping as we'll discuss in another section.
is_admin = Rule[User, Organization]("is_admin", lamdba actor, resource, context: resource.owner = actor)
Using Rules
Rules are Callable
object themselves that defer to the underlying function, so using them is as simple as calling them on the relevant objects
if is_admin(user, post):
print("User authorized")
Alternatively, you can call on rule.authorize
. This function essentially accomplishes the same thing, but raises an UnauthorizedException
if the rule would return False
.