Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add is_admin Dependency #227

Merged
merged 1 commit into from
Feb 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 21 additions & 5 deletions aana/api/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,21 @@
from aana.exceptions.api_service import AdminOnlyAccess


def is_admin(request: Request) -> bool:
"""Check if the user is an admin.

Args:
request (Request): The request object

Returns:
bool: True if the user is an admin, False otherwise
"""
if aana_settings.api_service.enabled:
api_key_info: ApiKey = request.state.api_key_info
return api_key_info.is_admin if api_key_info else False
return True


def require_admin_access(request: Request) -> bool:
"""Check if the user is an admin. If not, raise an exception.

Expand All @@ -16,11 +31,9 @@ def require_admin_access(request: Request) -> bool:
Raises:
AdminOnlyAccess: If the user is not an admin
"""
if aana_settings.api_service.enabled:
api_key_info: ApiKey = request.state.api_key_info
is_admin = api_key_info.is_admin if api_key_info else False
if not is_admin:
raise AdminOnlyAccess()
_is_admin = is_admin(request)
if not _is_admin:
raise AdminOnlyAccess()
return True


Expand All @@ -38,6 +51,9 @@ def extract_user_id(request: Request) -> str | None:
AdminAccessDependency = Annotated[bool, Depends(require_admin_access)]
""" Dependency to check if the user is an admin. If not, it will raise an exception. """

IsAdminDependency = Annotated[bool, Depends(is_admin)]
""" Dependency to check if the user is an admin. """

UserIdDependency = Annotated[str | None, Depends(extract_user_id)]
""" Dependency to get the user ID. """

Expand Down