Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 16 additions & 3 deletions app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from collections.abc import AsyncGenerator
from typing import Annotated

from fastapi import Depends, HTTPException, status
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import ValidationError
from sqlalchemy.ext.asyncio import AsyncSession
Expand All @@ -17,7 +17,10 @@
from app.schemas.token import TokenPayload
from app.schemas.user import SystemRole

reusable_oauth2 = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login")
# auto_error=False: cookie tabanlı auth kullanıldığında Bearer token isteğe bağlıdır
reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/auth/login", auto_error=False
)


async def get_db() -> AsyncGenerator[AsyncSession, None]:
Expand All @@ -27,12 +30,22 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:


async def get_current_user(
request: Request,
Comment thread
cursor[bot] marked this conversation as resolved.
db: Annotated[AsyncSession, Depends(get_db)],
token: Annotated[str, Depends(reusable_oauth2)],
bearer_token: Annotated[str | None, Depends(reusable_oauth2)] = None,
) -> User:
"""
Get current authenticated user from JWT token.
Cookie takes priority; falls back to Authorization Bearer header.
"""
token = request.cookies.get("access_token") or bearer_token
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ErrorMessages.INVALID_TOKEN,
headers={"WWW-Authenticate": "Bearer"},
)

Comment thread
cursor[bot] marked this conversation as resolved.
try:
# Check if token is blacklisted
if await is_token_blacklisted(db, token):
Expand Down
28 changes: 27 additions & 1 deletion app/api/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ async def login_access_token(
password=form_data.password,
)

# Set access token in HttpOnly cookie
response.set_cookie(
key="access_token",
value=result.access_token,
httponly=True,
secure=settings.ENVIRONMENT != "local",
samesite="lax",
max_age=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
path="/",
)

# Set refresh token in HttpOnly cookie
response.set_cookie(
key="refresh_token",
Expand Down Expand Up @@ -86,6 +97,7 @@ async def login_access_token(
@router.post("/refresh", response_model=Token, status_code=status.HTTP_200_OK)
async def refresh_token(
request: Request,
response: Response,
session: SessionDep,
) -> Token:
"""
Expand All @@ -99,9 +111,22 @@ async def refresh_token(
)

try:
return await refresh_token_service(
result = await refresh_token_service(
request=request, session=session, refresh_token=refresh_token_cookie
)

# Set new access token in HttpOnly cookie
response.set_cookie(
key="access_token",
value=result.access_token,
httponly=True,
secure=settings.ENVIRONMENT != "local",
samesite="lax",
max_age=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
path="/",
)
Comment thread
cursor[bot] marked this conversation as resolved.

return result
except HTTPException:
raise
except Exception as e:
Expand Down Expand Up @@ -129,6 +154,7 @@ async def logout(request: Request, response: Response, session: SessionDep) -> M
request=request, session=session, refresh_token=refresh_token
)

response.delete_cookie(key="access_token", path="/")
response.delete_cookie(
key="refresh_token",
path=f"{settings.API_V1_STR}/auth/refresh",
Expand Down