Authorization
Titancore's Gate delegates authorization to application abilities and model policies. The authorization provider resolves the authenticated account from the application's JWT guard. Guests and missing abilities are denied.
Register AuthServiceProvider() with the authentication
provider. Register abilities after application startup or within your own
provider's Gate factory.
from titancore.facades import Gate
def view_dashboard(user: object) -> bool:
return isinstance(user, Administrator)
await Gate.define("view-dashboard", view_dashboard)
Here Administrator is your application account type. Callbacks receive the
authenticated account followed by the arguments supplied to the Gate.
Synchronous callbacks run in worker threads. Asynchronous callbacks are
awaited. A decision grants access only when it returns True.
Use await Gate.allows(ability, *arguments) and
await Gate.denies(ability, *arguments) for boolean decisions.
await Gate.authorize(ability, *arguments) raises AuthorizationError
when the action is denied. The HTTP kernel renders this exception as HTTP
403 without logging it as an unexpected server failure.
A policy groups decisions for an application model.
class ArticlePolicy:
def update(self, user: User, article: Article) -> bool:
return article.owner_id == user.get_auth_identifier()
def create(self, user: User) -> bool:
return user.is_administrator
await Gate.policy(Article, ArticlePolicy())
await Gate.authorize("update", article)
await Gate.authorize("create", Article)
The application supplies User, Article, and article. Instance policies
receive the account and model instance. Class policies receive the account
and any remaining arguments. Explicitly defined abilities take precedence
over policy methods. Missing policy methods and private method names are
denied.
await Gate.for_user(user) returns a Gate sharing the registered abilities
and policies while selecting that account explicitly. It leaves request
identity unchanged.
Protect routes using authentication followed by authorization.
from titancore.auth import Authenticate
from titancore.authorization import Authorize
from titancore.facades import Route
Route.get("/dashboard", dashboard).middleware(
[Authenticate(), Authorize("view-dashboard")]
)
The application supplies dashboard. Authentication failures return HTTP
401. Authorization failures return HTTP 403. For route-specific model
instances, retrieve the model in the handler and call Gate.authorize
there. Roles, permissions, and policy business rules remain application code.