Skip to content

Commit 1bceed2

Browse files
committed
support both api key and oauth
1 parent f4e245a commit 1bceed2

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

backend/app/api/deps.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,28 @@
1717
from app.crud.api_key import get_api_key_by_value
1818
from app.models import TokenPayload, User, UserProjectOrg, UserOrganization, ProjectUser, Project, Organization
1919

20-
# reusable_oauth2 = OAuth2PasswordBearer(
21-
# tokenUrl=f"{settings.API_V1_STR}/login/access-token"
22-
# )
20+
reusable_oauth2 = OAuth2PasswordBearer(
21+
tokenUrl=f"{settings.API_V1_STR}/login/access-token",
22+
auto_error= False
23+
)
2324

2425

2526
def get_db() -> Generator[Session, None, None]:
2627
with Session(engine) as session:
2728
yield session
2829

29-
api_key_header = APIKeyHeader(name="Authorization", auto_error=False)
30+
api_key_header = APIKeyHeader(name="X-API-KEY", auto_error=False)
3031
SessionDep = Annotated[Session, Depends(get_db)]
31-
# TokenDep = Annotated[str, Depends(reusable_oauth2)]
32+
TokenDep = Annotated[str, Depends(reusable_oauth2)]
3233

3334
def get_current_user(
3435
session: SessionDep,
35-
auth_header: str = Security(api_key_header),
36+
token: TokenDep,
37+
api_key: Annotated[str, Depends(api_key_header)],
3638
) -> UserOrganization:
3739
"""Authenticate user via API Key first, fallback to JWT token."""
3840

39-
if auth_header.startswith("ApiKey "):
40-
api_key = auth_header.split(" ", 1)[1]
41+
if api_key:
4142
api_key_record = get_api_key_by_value(session, api_key)
4243
if not api_key_record:
4344
raise HTTPException(status_code=401, detail="Invalid API Key")
@@ -51,9 +52,8 @@ def get_current_user(
5152
# Return UserOrganization model with organization ID
5253
return UserOrganization(**user.model_dump(), organization_id=api_key_record.organization_id)
5354

54-
if auth_header.startswith("Bearer "):
55+
if token:
5556
try:
56-
token = auth_header.split(" ", 1)[1]
5757
payload = jwt.decode(
5858
token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
5959
)
@@ -70,7 +70,8 @@ def get_current_user(
7070
raise HTTPException(status_code=400, detail="Inactive user")
7171

7272
return UserOrganization(**user.model_dump(), organization_id=None)
73-
raise HTTPException(status_code=401, detail="Invalid Authorization header format")
73+
74+
raise HTTPException(status_code=401, detail="Invalid Authorization format")
7475

7576
CurrentUser = Annotated[UserOrganization, Depends(get_current_user)]
7677

0 commit comments

Comments
 (0)