85 lines
2.9 KiB
Python
85 lines
2.9 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from src.core.config import settings
|
|
from src.db.session import get_db
|
|
from src.domain.schemas import LoginRequest, RefreshRequest, Token
|
|
from src.services.auth_service import AuthService
|
|
|
|
# if not settings.DEBUG:
|
|
# from raisa_fastapi_protected_api import UserInfo, get_user_dependency
|
|
|
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
|
|
|
|
|
# if settings.DEBUG:
|
|
|
|
@router.post("/login", response_model=Token)
|
|
async def login(
|
|
login_data: LoginRequest,
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
auth_service = AuthService(db)
|
|
token = await auth_service.authenticate_user(login_data.username, login_data.password)
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Неверное имя пользователя или пароль",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
return token
|
|
|
|
# else:
|
|
|
|
# @router.post("/login", response_model=Token)
|
|
# async def login(
|
|
# login_data: LoginRequest,
|
|
# db: AsyncSession = Depends(get_db),
|
|
# user: UserInfo = Depends(get_user_dependency),
|
|
# ):
|
|
# auth_service = AuthService(db)
|
|
# token = await auth_service.authenticate_user_via_email(user.email)
|
|
# if not token:
|
|
# raise HTTPException(
|
|
# status_code=status.HTTP_401_UNAUTHORIZED,
|
|
# detail="Неверное имя пользователя или пароль",
|
|
# headers={"WWW-Authenticate": "Bearer"},
|
|
# )
|
|
# return token
|
|
|
|
|
|
@router.post("/login-form", response_model=Token)
|
|
async def login_form(request: Request, db: AsyncSession = Depends(get_db)):
|
|
form = await request.form()
|
|
username = form.get("username")
|
|
password = form.get("password")
|
|
if not username or not password:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail="username/password required",
|
|
)
|
|
auth_service = AuthService(db)
|
|
token = await auth_service.authenticate_user(username, password)
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Неверное имя пользователя или пароль",
|
|
)
|
|
return token
|
|
|
|
|
|
@router.post("/refresh", response_model=Token)
|
|
async def refresh_token(
|
|
refresh_data: RefreshRequest,
|
|
db: AsyncSession = Depends(get_db),
|
|
):
|
|
auth_service = AuthService(db)
|
|
token = await auth_service.refresh_token(refresh_data.refresh_token)
|
|
if not token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Недействительный refresh токен",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
return token
|