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 scopes to Firebase auth #84

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
23 changes: 19 additions & 4 deletions fastapi_cloudauth/firebase.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from calendar import timegm
from datetime import datetime
from email.utils import parsedate_to_datetime
from typing import Any, Dict, Optional
from typing import Any, Dict, Optional, Set

import requests
from fastapi import HTTPException
Expand Down Expand Up @@ -39,6 +39,7 @@ def _set_expiration(self, resp: requests.Response) -> Optional[datetime]:
class FirebaseClaims(BaseModel):
user_id: str = Field(alias="user_id")
email: str = Field(None, alias="email")
scope: str = Field(None)


class FirebaseCurrentUser(UserInfoAuth):
Expand All @@ -48,7 +49,7 @@ class FirebaseCurrentUser(UserInfoAuth):

user_info = FirebaseClaims

def __init__(self, project_id: str, *args: Any, **kwargs: Any):
def __init__(self, project_id: str, required_scopes: Set[str] = {}, *args: Any, **kwargs: Any):
url = "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]"
jwks = JWKS(url=url)
super().__init__(
Expand All @@ -57,17 +58,31 @@ def __init__(self, project_id: str, *args: Any, **kwargs: Any):
user_info=self.user_info,
audience=project_id,
issuer=f"https://securetoken.google.com/{project_id}",
extra=FirebaseExtraVerifier(project_id=project_id),
extra=FirebaseExtraVerifier(
project_id=project_id,
required_scopes=required_scopes
),
**kwargs,
)


class FirebaseExtraVerifier(ExtraVerifier):
def __init__(self, project_id: str):
def __init__(self, project_id: str, required_scopes: Set[str]):
self._pjt_id = project_id
self.required_scopes = required_scopes

def __call__(self, claims: Dict[str, str], auto_error: bool = True) -> bool:
# auth_time must be past time
scopes_str = claims.get("scope")

scopes = scopes_str.split(' ') if scopes_str is not None else {}

for required_scope in self.required_scopes:
if required_scope not in scopes:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail=NOT_VERIFIED
)

if claims.get("auth_time"):
auth_time = int(claims["auth_time"])
now = timegm(datetime.utcnow().utctimetuple())
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,5 @@ profile = "black"
known_third_party = ["fastapi", "pydantic", "starlette"]

[build-system]
requires = ["poetry>=1.1.12"]
build-backend = "poetry.masonry.api"
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"