64 lines
1.9 KiB
Python
64 lines
1.9 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from fastapi_users.router import ErrorCode
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from .auth import fastapi_users, auth_backend, get_user_manager
|
|
from app.database.models import RbacPapel
|
|
from app.rbac.schemas import UserRead, UserCreate, UserRoles
|
|
from fastapi_users.exceptions import UserAlreadyExists, InvalidPasswordException
|
|
from app.database.session import get_db
|
|
|
|
router = APIRouter(
|
|
prefix="/autenticacao",
|
|
tags=["Autenticação"], )
|
|
|
|
|
|
# Rotas de autenticação
|
|
|
|
@router.post("/register", response_model=UserRead)
|
|
async def register(user: UserCreate, roles: UserRoles, session: AsyncSession = Depends(get_db),
|
|
user_manager=Depends(get_user_manager)):
|
|
try:
|
|
created_user = await user_manager.create(user)
|
|
# Associação dos papéis ao usuário criado
|
|
for papel_id in roles.papeis:
|
|
papel = await session.get(RbacPapel, papel_id)
|
|
if papel:
|
|
created_user.papeis.append(papel)
|
|
else:
|
|
raise HTTPException(status_code=404, detail=f"Papel com ID {papel_id} não encontrado")
|
|
|
|
await session.commit()
|
|
await session.refresh(created_user)
|
|
return created_user
|
|
|
|
except UserAlreadyExists:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=ErrorCode.REGISTER_USER_ALREADY_EXISTS,
|
|
|
|
)
|
|
|
|
except InvalidPasswordException as e:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail={
|
|
"code": ErrorCode.REGISTER_INVALID_PASSWORD,
|
|
"reason": e.reason,
|
|
},
|
|
|
|
)
|
|
|
|
|
|
router.include_router(
|
|
fastapi_users.get_auth_router(auth_backend)
|
|
)
|
|
|
|
router.include_router(
|
|
fastapi_users.get_reset_password_router(),
|
|
|
|
)
|
|
router.include_router(
|
|
fastapi_users.get_verify_router(UserRead),
|
|
|
|
)
|