Exemple #1
0
def get_auth_router(
    backend: BaseAuthentication,
    user_db: BaseUserDatabase[models.BaseUserDB],
    authenticator: Authenticator,
    requires_verification: bool = False,
) -> APIRouter:
    """Generate a router with login/logout routes for an authentication backend."""
    router = APIRouter()
    get_current_user = authenticator.current_user(
        active=True, verified=requires_verification
    )

    @router.post("/login")
    async def login(
        response: Response, credentials: OAuth2PasswordRequestForm = Depends()
    ):
        user = await user_db.authenticate(credentials)

        if user is None or not user.is_active:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=ErrorCode.LOGIN_BAD_CREDENTIALS,
            )
        if requires_verification and not user.is_verified:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=ErrorCode.LOGIN_USER_NOT_VERIFIED,
            )
        return await backend.get_login_response(user, response)

    if backend.logout:

        @router.post("/logout")
        async def logout(response: Response, user=Depends(get_current_user)):
            return await backend.get_logout_response(user, response)

    return router
def get_users_router(
    user_db: BaseUserDatabase[models.BaseUserDB],
    user_model: Type[models.BaseUser],
    user_update_model: Type[models.BaseUserUpdate],
    user_db_model: Type[models.BaseUserDB],
    authenticator: Authenticator,
    after_update: Optional[Callable[[models.UD, Dict[str, Any], Request],
                                    None]] = None,
    requires_verification: bool = False,
) -> APIRouter:
    """Generate a router with the authentication routes."""
    router = APIRouter()

    get_current_active_user = authenticator.current_user(
        active=True, verified=requires_verification)
    get_current_superuser = authenticator.current_user(
        active=True, verified=requires_verification, superuser=True)

    async def _get_or_404(id: UUID4) -> models.BaseUserDB:
        user = await user_db.get(id)
        if user is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
        return user

    async def _update_user(user: models.BaseUserDB,
                           update_dict: Dict[str, Any], request: Request):
        for field in update_dict:
            if field == "password":
                hashed_password = get_password_hash(update_dict[field])
                user.hashed_password = hashed_password
            else:
                setattr(user, field, update_dict[field])
        updated_user = await user_db.update(user)
        if after_update:
            await run_handler(after_update, updated_user, update_dict, request)
        return updated_user

    @router.get("/me", response_model=user_model)
    async def me(
            user: user_db_model = Depends(
                get_current_active_user),  # type: ignore
    ):
        return user

    @router.patch("/me", response_model=user_model)
    async def update_me(
            request: Request,
            updated_user: user_update_model,  # type: ignore
            user: user_db_model = Depends(
                get_current_active_user),  # type: ignore
    ):
        updated_user = cast(
            models.BaseUserUpdate,
            updated_user,
        )  # Prevent mypy complain
        updated_user_data = updated_user.create_update_dict()
        updated_user = await _update_user(user, updated_user_data, request)

        return updated_user

    @router.get(
        "/{id:uuid}",
        response_model=user_model,
        dependencies=[Depends(get_current_superuser)],
    )
    async def get_user(id: UUID4):
        return await _get_or_404(id)

    @router.patch(
        "/{id:uuid}",
        response_model=user_model,
        dependencies=[Depends(get_current_superuser)],
    )
    async def update_user(
            id: UUID4,
            updated_user: user_update_model,
            request: Request  # type: ignore
    ):
        updated_user = cast(
            models.BaseUserUpdate,
            updated_user,
        )  # Prevent mypy complain
        user = await _get_or_404(id)
        updated_user_data = updated_user.create_update_dict_superuser()
        return await _update_user(user, updated_user_data, request)

    @router.delete(
        "/{id:uuid}",
        status_code=status.HTTP_204_NO_CONTENT,
        dependencies=[Depends(get_current_superuser)],
    )
    async def delete_user(id: UUID4):
        user = await _get_or_404(id)
        await user_db.delete(user)
        return None

    return router
Exemple #3
0
def get_users_router(
    user_db: BaseUserDatabase[models.BaseUserDB],
    user_model: Type[models.BaseUser],
    user_update_model: Type[models.BaseUserUpdate],
    user_db_model: Type[models.BaseUserDB],
    authenticator: Authenticator,
    after_update: Optional[Callable[[models.UD, Dict[str, Any], Request],
                                    None]] = None,
    requires_verification: bool = False,
    validate_password: Optional[ValidatePasswordProtocol] = None,
) -> APIRouter:
    """Generate a router with the authentication routes."""
    router = APIRouter()

    get_current_active_user = authenticator.current_user(
        active=True, verified=requires_verification)
    get_current_superuser = authenticator.current_user(
        active=True, verified=requires_verification, superuser=True)

    async def _get_or_404(id: UUID4) -> models.BaseUserDB:
        user = await user_db.get(id)
        if user is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
        return user

    async def _check_unique_email(
            updated_user: user_update_model,  # type: ignore
    ) -> None:
        updated_user = cast(models.BaseUserUpdate,
                            updated_user)  # Prevent mypy complain
        if updated_user.email:
            user = await user_db.get_by_email(updated_user.email)
            if user is not None:
                raise HTTPException(
                    status.HTTP_400_BAD_REQUEST,
                    detail=ErrorCode.UPDATE_USER_EMAIL_ALREADY_EXISTS,
                )

    async def _update_user(user: models.BaseUserDB,
                           update_dict: Dict[str, Any], request: Request):
        for field in update_dict:
            if field == "password":
                password = update_dict[field]
                if validate_password:
                    await validate_password(password, user)
                hashed_password = get_password_hash(password)
                user.hashed_password = hashed_password
            else:
                setattr(user, field, update_dict[field])
        updated_user = await user_db.update(user)
        if after_update:
            await run_handler(after_update, updated_user, update_dict, request)
        return updated_user

    @router.get("/me", response_model=user_model)
    async def me(
            user: user_db_model = Depends(
                get_current_active_user),  # type: ignore
    ):
        return user

    @router.patch(
        "/me",
        response_model=user_model,
        dependencies=[
            Depends(get_current_active_user),
            Depends(_check_unique_email)
        ],
    )
    async def update_me(
            request: Request,
            updated_user: user_update_model,  # type: ignore
            user: user_db_model = Depends(
                get_current_active_user),  # type: ignore
    ):
        updated_user = cast(
            models.BaseUserUpdate,
            updated_user,
        )  # Prevent mypy complain
        updated_user_data = updated_user.create_update_dict()

        try:
            return await _update_user(user, updated_user_data, request)
        except InvalidPasswordException as e:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "code": ErrorCode.UPDATE_USER_INVALID_PASSWORD,
                    "reason": e.reason,
                },
            )

    @router.get(
        "/{id:uuid}",
        response_model=user_model,
        dependencies=[Depends(get_current_superuser)],
    )
    async def get_user(id: UUID4):
        return await _get_or_404(id)

    @router.patch(
        "/{id:uuid}",
        response_model=user_model,
        dependencies=[
            Depends(get_current_superuser),
            Depends(_check_unique_email)
        ],
    )
    async def update_user(
            id: UUID4,
            updated_user: user_update_model,
            request: Request  # type: ignore
    ):
        updated_user = cast(
            models.BaseUserUpdate,
            updated_user,
        )  # Prevent mypy complain
        user = await _get_or_404(id)
        updated_user_data = updated_user.create_update_dict_superuser()

        try:
            return await _update_user(user, updated_user_data, request)
        except InvalidPasswordException as e:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "code": ErrorCode.UPDATE_USER_INVALID_PASSWORD,
                    "reason": e.reason,
                },
            )

    @router.delete(
        "/{id:uuid}",
        status_code=status.HTTP_204_NO_CONTENT,
        dependencies=[Depends(get_current_superuser)],
    )
    async def delete_user(id: UUID4):
        user = await _get_or_404(id)
        await user_db.delete(user)
        return None

    return router
Exemple #4
0
def get_users_router(
    get_user_manager: UserManagerDependency[models.UC, models.UD],
    user_model: Type[models.U],
    user_update_model: Type[models.UU],
    user_db_model: Type[models.UD],
    authenticator: Authenticator,
    requires_verification: bool = False,
) -> APIRouter:
    """Generate a router with the authentication routes."""
    router = APIRouter()

    get_current_active_user = authenticator.current_user(
        active=True, verified=requires_verification)
    get_current_superuser = authenticator.current_user(
        active=True, verified=requires_verification, superuser=True)

    async def get_user_or_404(
        id: UUID4,
        user_manager: BaseUserManager[models.UC,
                                      models.UD] = Depends(get_user_manager),
    ) -> models.UD:
        try:
            return await user_manager.get(id)
        except UserNotExists:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)

    @router.get(
        "/me",
        response_model=user_model,
        name="users:current_user",
        responses={
            status.HTTP_401_UNAUTHORIZED: {
                "description": "Missing token or inactive user.",
            },
        },
    )
    async def me(
            user: user_db_model = Depends(
                get_current_active_user),  # type: ignore
    ):
        return user

    @router.patch(
        "/me",
        response_model=user_model,
        dependencies=[Depends(get_current_active_user)],
        name="users:current_user",
        responses={
            status.HTTP_401_UNAUTHORIZED: {
                "description": "Missing token or inactive user.",
            },
            status.HTTP_400_BAD_REQUEST: {
                "model": ErrorModel,
                "content": {
                    "application/json": {
                        "examples": {
                            ErrorCode.UPDATE_USER_EMAIL_ALREADY_EXISTS: {
                                "summary":
                                "A user with this email already exists.",
                                "value": {
                                    "detail":
                                    ErrorCode.UPDATE_USER_EMAIL_ALREADY_EXISTS
                                },
                            },
                            ErrorCode.UPDATE_USER_INVALID_PASSWORD: {
                                "summary": "Password validation failed.",
                                "value": {
                                    "detail": {
                                        "code":
                                        ErrorCode.UPDATE_USER_INVALID_PASSWORD,
                                        "reason":
                                        "Password should be"
                                        "at least 3 characters",
                                    }
                                },
                            },
                        }
                    }
                },
            },
        },
    )
    async def update_me(
        request: Request,
        user_update: user_update_model,  # type: ignore
        user: user_db_model = Depends(get_current_active_user),  # type: ignore
        user_manager: BaseUserManager[models.UC,
                                      models.UD] = Depends(get_user_manager),
    ):
        try:
            return await user_manager.update(user_update,
                                             user,
                                             safe=True,
                                             request=request)
        except InvalidPasswordException as e:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "code": ErrorCode.UPDATE_USER_INVALID_PASSWORD,
                    "reason": e.reason,
                },
            )
        except UserAlreadyExists:
            raise HTTPException(
                status.HTTP_400_BAD_REQUEST,
                detail=ErrorCode.UPDATE_USER_EMAIL_ALREADY_EXISTS,
            )

    @router.get(
        "/{id:uuid}",
        response_model=user_model,
        dependencies=[Depends(get_current_superuser)],
        name="users:user",
        responses={
            status.HTTP_401_UNAUTHORIZED: {
                "description": "Missing token or inactive user.",
            },
            status.HTTP_403_FORBIDDEN: {
                "description": "Not a superuser.",
            },
            status.HTTP_404_NOT_FOUND: {
                "description": "The user does not exist.",
            },
        },
    )
    async def get_user(user=Depends(get_user_or_404)):
        return user

    @router.patch(
        "/{id:uuid}",
        response_model=user_model,
        dependencies=[Depends(get_current_superuser)],
        name="users:user",
        responses={
            status.HTTP_401_UNAUTHORIZED: {
                "description": "Missing token or inactive user.",
            },
            status.HTTP_403_FORBIDDEN: {
                "description": "Not a superuser.",
            },
            status.HTTP_404_NOT_FOUND: {
                "description": "The user does not exist.",
            },
            status.HTTP_400_BAD_REQUEST: {
                "model": ErrorModel,
                "content": {
                    "application/json": {
                        "examples": {
                            ErrorCode.UPDATE_USER_EMAIL_ALREADY_EXISTS: {
                                "summary":
                                "A user with this email already exists.",
                                "value": {
                                    "detail":
                                    ErrorCode.UPDATE_USER_EMAIL_ALREADY_EXISTS
                                },
                            },
                            ErrorCode.UPDATE_USER_INVALID_PASSWORD: {
                                "summary": "Password validation failed.",
                                "value": {
                                    "detail": {
                                        "code":
                                        ErrorCode.UPDATE_USER_INVALID_PASSWORD,
                                        "reason":
                                        "Password should be"
                                        "at least 3 characters",
                                    }
                                },
                            },
                        }
                    }
                },
            },
        },
    )
    async def update_user(
        user_update: user_update_model,  # type: ignore
        request: Request,
        user=Depends(get_user_or_404),
        user_manager: BaseUserManager[models.UC,
                                      models.UD] = Depends(get_user_manager),
    ):
        try:
            return await user_manager.update(user_update,
                                             user,
                                             safe=False,
                                             request=request)
        except InvalidPasswordException as e:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail={
                    "code": ErrorCode.UPDATE_USER_INVALID_PASSWORD,
                    "reason": e.reason,
                },
            )
        except UserAlreadyExists:
            raise HTTPException(
                status.HTTP_400_BAD_REQUEST,
                detail=ErrorCode.UPDATE_USER_EMAIL_ALREADY_EXISTS,
            )

    @router.delete(
        "/{id:uuid}",
        status_code=status.HTTP_204_NO_CONTENT,
        response_class=Response,
        dependencies=[Depends(get_current_superuser)],
        name="users:user",
        responses={
            status.HTTP_401_UNAUTHORIZED: {
                "description": "Missing token or inactive user.",
            },
            status.HTTP_403_FORBIDDEN: {
                "description": "Not a superuser.",
            },
            status.HTTP_404_NOT_FOUND: {
                "description": "The user does not exist.",
            },
        },
    )
    async def delete_user(
        user=Depends(get_user_or_404),
        user_manager: BaseUserManager[models.UC,
                                      models.UD] = Depends(get_user_manager),
    ):
        await user_manager.delete(user)
        return None

    return router