Coverage for src / lexigram / contracts / auth / guard.py: 100%
11 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-08-19 05:41 +0800
« prev ^ index » next coverage.py v7.13.5, created at 2026-08-19 05:41 +0800
1"""GuardProtocol and authentication protocols.
3Protocols for authentication and authorization middleware.
4"""
6from __future__ import annotations
8from typing import Any, Protocol, runtime_checkable
11@runtime_checkable
12class AuthenticatorProtocol(Protocol):
13 """Protocol for request authentication.
15 Authenticators extract and validate credentials from requests.
16 """
18 async def authenticate(self, request: Any) -> Any | None:
19 """Authenticate a request.
21 Args:
22 request: The incoming request.
24 Returns:
25 Authenticated user if valid, None otherwise.
26 """
27 ...
30@runtime_checkable
31class AuthorizerProtocol(Protocol):
32 """Protocol for authorization decisions.
34 Authorizers determine if an authenticated user can perform
35 a specific action on a resource.
36 """
38 async def authorize(
39 self,
40 user: Any,
41 action: str,
42 resource: Any,
43 ) -> bool:
44 """Check if user is authorized for action on resource.
46 Args:
47 user: Authenticated user.
48 action: Action to perform (e.g., "read", "write", "delete").
49 resource: Target resource.
51 Returns:
52 True if authorized.
53 """
54 ...
56 async def check_access(
57 self,
58 user: Any,
59 allowed_roles: set[str],
60 resource: str | None = None,
61 action: str | None = None,
62 ) -> bool:
63 """Check if user has access based on roles and permissions.
65 Args:
66 user: Authenticated user.
67 allowed_roles: Set of roles that grant access.
68 resource: Target resource (optional).
69 action: Action to perform (optional).
71 Returns:
72 True if access is granted.
73 """
74 ...
76 async def can(self, user: Any, action: str, resource: str) -> bool:
77 """Check if user can perform action on resource.
79 Args:
80 user: Authenticated user.
81 action: Action to perform.
82 resource: Target resource.
84 Returns:
85 True if authorized.
86 """
87 ...
89 async def can_view(self, user: Any, resource: str, record: Any = None) -> bool: ...
91 async def can_create(self, user: Any, resource: str) -> bool: ...
93 async def can_update(
94 self, user: Any, resource: str, record: Any = None
95 ) -> bool: ...
97 async def can_delete(
98 self, user: Any, resource: str, record: Any = None
99 ) -> bool: ...
101 async def can_execute_action(
102 self, user: Any, resource: str, action: str, record: Any | None = None
103 ) -> bool: ...
105 def set_roles(self, roles: dict[str, Any]) -> None: ...
107 def register_role(self, name: str, role: Any) -> None: ...
109 def remove_role(self, name: str) -> None: ...
111 async def sync_from_db(self, container: Any) -> None: ...
114__all__ = ["AuthenticatorProtocol", "AuthorizerProtocol"]