Skip to content

Commit 42361ae

Browse files
committed
Added a _required_ decoded token dependency.
1 parent 14097ff commit 42361ae

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

fastapi_firebase/auth.py

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import typing
2-
import fastapi
32

3+
import fastapi
44
import firebase_admin
55
import pydantic
66
from fastapi import Depends, Security
@@ -12,25 +12,44 @@
1212

1313
token = HTTPBearer(
1414
scheme_name="firebaseIdToken",
15+
bearerFormat="JWT",
16+
description="The firebase Id token, provided by client SDK.",
1517
)
1618
_failed_auth_headers = {"WWW-Authenticate": "Bearer"}
1719

1820

1921
def validate_token(
20-
credential: HTTPAuthorizationCredentials = Security(token),
22+
credential: typing.Optional[HTTPAuthorizationCredentials] = Security(token),
2123
app: firebase_admin.App = Depends(firebase_app),
22-
) -> typing.Dict[str, typing.Any]:
24+
) -> typing.Optional[typing.Dict[str, typing.Any]]:
25+
if credential is None:
26+
return None
27+
2328
try:
2429
return auth.verify_id_token(credential.credentials, app)
25-
except auth.InvalidIdTokenError:
26-
raise fastapi.HTTPException(401, "Invalid token received.", _failed_auth_headers)
27-
except auth.UserDisabledError:
28-
raise fastapi.HTTPException(403, "The user has been disabled.")
2930
except auth.RevokedIdTokenError:
3031
raise fastapi.HTTPException(403, "The token has been revoked.")
3132
except auth.ExpiredIdTokenError:
3233
raise fastapi.HTTPException(403, "The token has expired.")
34+
except auth.InvalidIdTokenError:
35+
raise fastapi.HTTPException(401, "Invalid token received.", _failed_auth_headers)
36+
except auth.UserDisabledError:
37+
raise fastapi.HTTPException(403, "The user has been disabled.")
38+
3339

40+
def token_info(token: typing.Optional[typing.Dict[str, typing.Any]] = Depends(validate_token)):
41+
if token is None:
42+
return None
3443

35-
def token_info(token: typing.Dict[str, typing.Any] = Depends(validate_token)):
3644
return pydantic.parse_obj_as(TokenData, token)
45+
46+
47+
def required_token_info(info: TokenData = fastapi.Depends(token_info)):
48+
if info is None:
49+
raise fastapi.HTTPException(
50+
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
51+
detail="Not authenticated",
52+
headers={"www-authenticate": "Bearer"},
53+
)
54+
55+
return info

0 commit comments

Comments
 (0)