Files
connect/api/api/endpoints/auth.py
2025-11-06 23:34:47 +05:00

92 lines
2.5 KiB
Python

from fastapi import (
APIRouter,
Depends,
Response,
status,
Request,
)
from fastapi_jwt_auth import AuthJWT
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncConnection
from api.config import get_settings
from api.db.connection.session import get_connection_dep
from api.services.auth import authenticate_user
from api.services.endpoints.auth import AuthService
from api.schemas.endpoints.auth import Auth, Tokens
from api.error import create_access_error
api_router = APIRouter(
prefix="/auth",
tags=["User auth"],
)
class Settings(BaseModel):
authjwt_secret_key: str = get_settings().SECRET_KEY
# Configure application to store and get JWT from cookies
authjwt_token_location: set = {"headers"}
authjwt_cookie_domain: str = get_settings().DOMAIN
# Only allow JWT cookies to be sent over https
authjwt_cookie_secure: bool = get_settings().ENV == "prod"
# Enable csrf double submit protection. default is True
authjwt_cookie_csrf_protect: bool = False
authjwt_cookie_samesite: str = "lax"
@AuthJWT.load_config
def get_config():
return Settings()
@api_router.post("", response_model=Tokens)
async def login_for_access_token_endpoint(
user: Auth,
response: Response,
connection: AsyncConnection = Depends(get_connection_dep),
Authorize: AuthJWT = Depends(),
):
"""Авторизирует, выставляет токены в куки."""
authenticated_user = await authenticate_user(connection, user.login, user.password)
if not authenticated_user:
raise create_access_error(
message="Incorrect username or password",
status_code=status.HTTP_401_UNAUTHORIZED,
)
service = AuthService(connection)
tokens = await service.login(authenticated_user, Authorize)
return tokens
@api_router.post("/refresh", response_model=Tokens)
async def refresh_endpoint(
request: Request,
connection: AsyncConnection = Depends(get_connection_dep),
Authorize: AuthJWT = Depends(),
) -> Tokens:
service = AuthService(connection)
try:
Authorize.jwt_refresh_token_required()
current_user = Authorize.get_jwt_subject()
except Exception:
refresh_token = request.headers.get("Authorization").split(" ")[1]
await service.invalidate_refresh_token(refresh_token)
raise create_access_error(
message="Invalid refresh token",
status_code=status.HTTP_401_UNAUTHORIZED,
)
tokens = await service.refresh(current_user, Authorize)
return tokens