def __init__(
        self,
        db: BaseUserDatabase,
        auth_backends: Sequence[BaseAuthentication],
        user_model: Type[models.BaseUser],
        user_create_model: Type[models.BaseUserCreate],
        user_update_model: Type[models.BaseUserUpdate],
        user_db_model: Type[models.BaseUserDB],
        reset_password_token_secret: str,
        reset_password_token_lifetime_seconds: int = 3600,
    ):
        self.db = db
        self.authenticator = Authenticator(auth_backends, db)
        self.router = get_user_router(
            self.db,
            user_model,
            user_create_model,
            user_update_model,
            user_db_model,
            self.authenticator,
            reset_password_token_secret,
            reset_password_token_lifetime_seconds,
        )
        self.oauth_routers = []
        self._user_db_model = user_db_model
        self._event_handlers = defaultdict(list)

        self.get_current_user = self.authenticator.get_current_user
        self.get_current_active_user = self.authenticator.get_current_active_user
        self.get_current_superuser = self.authenticator.get_current_superuser
    async def _get_test_auth_client(
        backends: List[AuthenticationBackend],
        get_enabled_backends: Optional[DependencyCallable[
            Sequence[AuthenticationBackend]]] = None,
    ) -> AsyncGenerator[httpx.AsyncClient, None]:
        app = FastAPI()
        authenticator = Authenticator(backends, get_user_manager)

        @app.get("/test-current-user")
        def test_current_user(user: UserDB = Depends(
            authenticator.current_user(
                get_enabled_backends=get_enabled_backends)), ):
            return user

        @app.get("/test-current-active-user")
        def test_current_active_user(user: UserDB = Depends(
            authenticator.current_user(
                active=True, get_enabled_backends=get_enabled_backends)), ):
            return user

        @app.get("/test-current-superuser")
        def test_current_superuser(user: UserDB = Depends(
            authenticator.current_user(
                active=True,
                superuser=True,
                get_enabled_backends=get_enabled_backends,
            )), ):
            return user

        async for client in get_test_client(app):
            yield client
Beispiel #3
0
    async def _get_test_auth_client(
        backends: List[BaseAuthentication],
    ) -> AsyncGenerator[httpx.AsyncClient, None]:
        app = FastAPI()
        authenticator = Authenticator(backends, mock_user_db)

        @app.get("/test-current-user")
        def test_current_user(user: UserDB = Depends(authenticator.current_user())):
            return user

        @app.get("/test-current-active-user")
        def test_current_active_user(
            user: UserDB = Depends(authenticator.current_user(active=True)),
        ):
            return user

        @app.get("/test-current-superuser")
        def test_current_superuser(
            user: UserDB = Depends(
                authenticator.current_user(active=True, superuser=True)
            ),
        ):
            return user

        async for client in get_test_client(app):
            yield client
    def __init__(
        self,
        db: BaseUserDatabase,
        auth_backends: Sequence[BaseAuthentication],
        user_model: Type[models.BaseUser],
        user_create_model: Type[models.BaseUserCreate],
        user_update_model: Type[models.BaseUserUpdate],
        user_db_model: Type[models.BaseUserDB],
    ):
        self.db = db
        self.authenticator = Authenticator(auth_backends, db)

        self._user_model = user_model
        self._user_db_model = user_db_model
        self._user_create_model = user_create_model
        self._user_update_model = user_update_model
        self._user_db_model = user_db_model

        self.get_current_user = self.authenticator.get_current_user
        self.get_current_active_user = self.authenticator.get_current_active_user
        self.get_current_superuser = self.authenticator.get_current_superuser
        self.get_optional_current_user = self.authenticator.get_optional_current_user
        self.get_optional_current_active_user = (
            self.authenticator.get_optional_current_active_user)
        self.get_optional_current_superuser = (
            self.authenticator.get_optional_current_superuser)
def test_app_client(mock_user_db, mock_authentication, event_handler) -> TestClient:
    mock_authentication_bis = MockAuthentication(name="mock-bis")
    authenticator = Authenticator(
        [mock_authentication, mock_authentication_bis], mock_user_db
    )

    user_router = get_user_router(
        mock_user_db,
        User,
        UserCreate,
        UserUpdate,
        UserDB,
        authenticator,
        SECRET,
        LIFETIME,
    )

    user_router.add_event_handler(Event.ON_AFTER_REGISTER, event_handler)
    user_router.add_event_handler(Event.ON_AFTER_FORGOT_PASSWORD, event_handler)
    user_router.add_event_handler(Event.ON_AFTER_UPDATE, event_handler)

    app = FastAPI()
    app.include_router(user_router)

    return TestClient(app)
Beispiel #6
0
async def test_app_client(mock_user_db, mock_authentication,
                          get_test_client) -> httpx.AsyncClient:
    mock_authentication_bis = MockAuthentication(name="mock-bis")
    authenticator = Authenticator(
        [mock_authentication, mock_authentication_bis], mock_user_db)

    mock_auth_router = get_auth_router(mock_authentication, mock_user_db,
                                       authenticator)
    mock_bis_auth_router = get_auth_router(mock_authentication_bis,
                                           mock_user_db, authenticator)

    app = FastAPI()
    app.include_router(mock_auth_router, prefix="/mock")
    app.include_router(mock_bis_auth_router, prefix="/mock-bis")

    return await get_test_client(app)
    def __init__(
        self,
        get_user_manager: UserManagerDependency[models.UC, models.UD],
        auth_backends: Sequence[AuthenticationBackend],
        user_model: Type[models.U],
        user_create_model: Type[models.UC],
        user_update_model: Type[models.UU],
        user_db_model: Type[models.UD],
    ):
        self.authenticator = Authenticator(auth_backends, get_user_manager)

        self._user_model = user_model
        self._user_db_model = user_db_model
        self._user_create_model = user_create_model
        self._user_update_model = user_update_model

        self.get_user_manager = get_user_manager
        self.current_user = self.authenticator.current_user
async def test_app_client(
        mock_user_db, mock_authentication,
        get_test_client) -> AsyncGenerator[httpx.AsyncClient, None]:
    mock_authentication_bis = MockAuthentication(name="mock-bis")
    authenticator = Authenticator(
        [mock_authentication, mock_authentication_bis], mock_user_db)

    mock_auth_router = get_auth_router(mock_authentication, mock_user_db,
                                       authenticator)
    mock_bis_auth_router = get_auth_router(mock_authentication_bis,
                                           mock_user_db, authenticator)

    app = FastAPI()
    app.include_router(mock_auth_router, prefix="/mock")
    app.include_router(mock_bis_auth_router, prefix="/mock-bis")

    async for client in get_test_client(app):
        yield client
    def _app_factory(requires_verification: bool) -> FastAPI:
        mock_authentication_bis = get_mock_authentication(name="mock-bis")
        authenticator = Authenticator(
            [mock_authentication, mock_authentication_bis], get_user_manager)

        user_router = get_users_router(
            get_user_manager,
            User,
            UserUpdate,
            UserDB,
            authenticator,
            requires_verification=requires_verification,
        )

        app = FastAPI()
        app.include_router(user_router)

        return app
Beispiel #10
0
async def test_app_client(mock_user_db, mock_authentication, after_update,
                          get_test_client) -> httpx.AsyncClient:
    mock_authentication_bis = MockAuthentication(name="mock-bis")
    authenticator = Authenticator(
        [mock_authentication, mock_authentication_bis], mock_user_db)

    user_router = get_users_router(
        mock_user_db,
        User,
        UserUpdate,
        UserDB,
        authenticator,
        after_update,
    )

    app = FastAPI()
    app.include_router(user_router)

    return await get_test_client(app)
    async def _get_test_app_client(redirect_url: str = None) -> httpx.AsyncClient:
        mock_authentication_bis = MockAuthentication(name="mock-bis")
        authenticator = Authenticator(
            [mock_authentication, mock_authentication_bis], mock_user_db_oauth
        )

        oauth_router = get_oauth_router(
            oauth_client,
            mock_user_db_oauth,
            UserDB,
            authenticator,
            SECRET,
            redirect_url,
            after_register,
        )

        app = FastAPI()
        app.include_router(oauth_router)

        return await get_test_client(app)
    def _app_factory(requires_verification: bool) -> FastAPI:
        mock_authentication_bis = MockAuthentication(name="mock-bis")
        authenticator = Authenticator(
            [mock_authentication, mock_authentication_bis], mock_user_db)

        user_router = get_users_router(
            mock_user_db,
            User,
            UserUpdate,
            UserDB,
            authenticator,
            after_update,
            requires_verification=requires_verification,
            validate_password=validate_password,
        )

        app = FastAPI()
        app.include_router(user_router)

        return app
    def _get_test_app_client(redirect_url: str = None) -> TestClient:
        mock_authentication_bis = MockAuthentication(name="mock-bis")
        authenticator = Authenticator(
            [mock_authentication, mock_authentication_bis], mock_user_db_oauth)

        oauth_router = get_oauth_router(
            oauth_client,
            mock_user_db_oauth,
            UserDB,
            authenticator,
            SECRET,
            redirect_url,
        )

        oauth_router.add_event_handler(Event.ON_AFTER_REGISTER, event_handler)

        app = FastAPI()
        app.include_router(oauth_router)

        return TestClient(app)
    def __init__(
        self,
        db: BaseUserDatabase,
        auth_backends: Sequence[BaseAuthentication],
        user_model: Type[models.BaseUser],
        user_create_model: Type[models.BaseUserCreate],
        user_update_model: Type[models.BaseUserUpdate],
        user_db_model: Type[models.BaseUserDB],
        validate_password: Optional[ValidatePasswordProtocol] = None,
    ):
        self.db = db
        self.authenticator = Authenticator(auth_backends, db)

        self._user_model = user_model
        self._user_db_model = user_db_model
        self._user_create_model = user_create_model
        self._user_update_model = user_update_model
        self._user_db_model = user_db_model

        self.create_user = get_create_user(db, user_db_model)
        self.verify_user = get_verify_user(db)
        self.get_user = get_get_user(db)

        self.validate_password = validate_password

        self.current_user = self.authenticator.current_user
        self.get_current_user = self.authenticator.get_current_user
        self.get_current_active_user = self.authenticator.get_current_active_user
        self.get_current_verified_user = self.authenticator.get_current_verified_user
        self.get_current_superuser = self.authenticator.get_current_superuser
        self.get_current_verified_superuser = (
            self.authenticator.get_current_verified_superuser)
        self.get_optional_current_user = self.authenticator.get_optional_current_user
        self.get_optional_current_active_user = (
            self.authenticator.get_optional_current_active_user)
        self.get_optional_current_verified_user = (
            self.authenticator.get_optional_current_verified_user)
        self.get_optional_current_superuser = (
            self.authenticator.get_optional_current_superuser)
        self.get_optional_current_verified_superuser = (
            self.authenticator.get_optional_current_verified_superuser)
Beispiel #15
0
async def test_app_client(
        mock_user_db, mock_authentication, after_update,
        get_test_client) -> AsyncGenerator[httpx.AsyncClient, None]:
    mock_authentication_bis = MockAuthentication(name="mock-bis")
    authenticator = Authenticator(
        [mock_authentication, mock_authentication_bis], mock_user_db)

    user_router = get_users_router(
        mock_user_db,
        User,
        UserUpdate,
        UserDB,
        authenticator,
        after_update,
    )

    app = FastAPI()
    app.include_router(user_router)

    async for client in get_test_client(app):
        yield client
Beispiel #16
0
    async def _get_test_app_client(
        redirect_url: str = None, ) -> AsyncGenerator[httpx.AsyncClient, None]:
        mock_authentication_bis = MockAuthentication(name="mock-bis")
        authenticator = Authenticator(
            [mock_authentication, mock_authentication_bis], mock_user_db_oauth)

        oauth_router = get_oauth_router(
            oauth_client,
            mock_user_db_oauth,
            UserDB,
            authenticator,
            SECRET,
            redirect_url,
            after_register,
        )

        app = FastAPI()
        app.include_router(oauth_router)

        async for client in get_test_client(app):
            yield client
Beispiel #17
0
    def _get_test_auth_client(
            backends: List[BaseAuthentication]) -> TestClient:
        app = FastAPI()
        authenticator = Authenticator(backends, mock_user_db)

        @app.get("/test-current-user")
        def test_current_user(
                user: UserDB = Depends(authenticator.get_current_user), ):
            return user

        @app.get("/test-current-active-user")
        def test_current_active_user(
                user: UserDB = Depends(
                    authenticator.get_current_active_user), ):
            return user

        @app.get("/test-current-superuser")
        def test_current_superuser(
                user: UserDB = Depends(authenticator.get_current_superuser), ):
            return user

        return TestClient(app)
    def _app_factory(requires_verification: bool) -> FastAPI:
        mock_authentication_bis = MockAuthentication(name="mock-bis")
        authenticator = Authenticator(
            [mock_authentication, mock_authentication_bis], mock_user_db)

        mock_auth_router = get_auth_router(
            mock_authentication,
            mock_user_db,
            authenticator,
            requires_verification=requires_verification,
        )
        mock_bis_auth_router = get_auth_router(
            mock_authentication_bis,
            mock_user_db,
            authenticator,
            requires_verification=requires_verification,
        )

        app = FastAPI()
        app.include_router(mock_auth_router, prefix="/mock")
        app.include_router(mock_bis_auth_router, prefix="/mock-bis")

        return app
Beispiel #19
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
Beispiel #21
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
Beispiel #22
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
Beispiel #23
0
def get_auth_router(
    backend: AuthenticationBackend,
    get_user_manager: UserManagerDependency[models.UC, models.UD],
    authenticator: Authenticator,
    requires_verification: bool = False,
) -> APIRouter:
    """Generate a router with login/logout routes for an authentication backend."""
    router = APIRouter()
    get_current_user_token = authenticator.current_user_token(
        active=True, verified=requires_verification)

    login_responses: OpenAPIResponseType = {
        status.HTTP_400_BAD_REQUEST: {
            "model": ErrorModel,
            "content": {
                "application/json": {
                    "examples": {
                        ErrorCode.LOGIN_BAD_CREDENTIALS: {
                            "summary":
                            "Bad credentials or the user is inactive.",
                            "value": {
                                "detail": ErrorCode.LOGIN_BAD_CREDENTIALS
                            },
                        },
                        ErrorCode.LOGIN_USER_NOT_VERIFIED: {
                            "summary": "The user is not verified.",
                            "value": {
                                "detail": ErrorCode.LOGIN_USER_NOT_VERIFIED
                            },
                        },
                    }
                }
            },
        },
        **backend.transport.get_openapi_login_responses_success(),
    }

    @router.post(
        "/login",
        name=f"auth:{backend.name}.login",
        responses=login_responses,
    )
    async def login(
        response: Response,
        credentials: OAuth2PasswordRequestForm = Depends(),
        user_manager: BaseUserManager[models.UC,
                                      models.UD] = Depends(get_user_manager),
        strategy: Strategy[models.UC,
                           models.UD] = Depends(backend.get_strategy),
    ):
        user = await user_manager.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.login(strategy, user, response)

    logout_responses: OpenAPIResponseType = {
        **{
            status.HTTP_401_UNAUTHORIZED: {
                "description": "Missing token or inactive user."
            }
        },
        **backend.transport.get_openapi_logout_responses_success(),
    }

    @router.post("/logout",
                 name=f"auth:{backend.name}.logout",
                 responses=logout_responses)
    async def logout(
        response: Response,
        user_token: Tuple[models.UD, str] = Depends(get_current_user_token),
        strategy: Strategy[models.UC,
                           models.UD] = Depends(backend.get_strategy),
    ):
        user, token = user_token
        return await backend.logout(strategy, user, token, response)

    return router