Ejemplo n.º 1
0
    def decorated_function(*args, **kwargs):
        """Retrieves the authentication information from Google Cloud Endpoints and passes it to user permissions service"""
        encoded_info = request.headers.get("X-Endpoint-API-UserInfo", None)
        if not encoded_info:
            raise APIException(status=401, title="User is not authenticated")

        info_json = base64_decode(encoded_info)
        # First parsing of the decoded header string
        user_info = json.loads(info_json)
        # Claims are given as a string by Cloud Endpoints so we have
        # to parse the claims attribute
        claims = json.loads(user_info.get("claims", "{}"))

        auth0_claims = claims.get("https://api.fluidly.com/app_metadata", {})
        internal_claims = claims.get("https://api.fluidly.com/internal_metadata", {})

        user_id_from_token = auth0_claims.get("userId", None)

        try:
            is_service_account = internal_claims.get("isServiceAccount", False)

            if not is_service_account and not check_admin_permissions(claims):
                raise APIException(status=403, title="User cannot access this resource")
        except (
            ValueError,
            UserPermissionsPayloadException,
            UserPermissionsRequestException,
        ):
            raise APIException(
                status=403, title="An issue occurred while fetching permissions"
            )

        g.user_id = user_id_from_token
        return f(*args, **kwargs)
Ejemplo n.º 2
0
 def decorated_function(*args, **kwargs):
     try:
         result = func(*args, **kwargs)
     except APIException as exception:
         raise exception
     except ValidationError as exception:
         raise APIException(
             title="Schema Validation Error",
             status=422,
             detail=exception.normalized_messages(),
         )
     except BadRequest as exception:
         raise APIException(title="Invalid Body",
                            status=400,
                            detail=exception.description)
     except Exception:
         raise APIException(status=500, title="An unknown error occurred")
     return result
Ejemplo n.º 3
0
def test_api_exception():
    try:
        raise APIException(
            title="Internal Server Error",
            status="500",
            detail="An internal server error occurred.",
        )
    except APIException as api_exception:
        assert api_exception.to_dict()["title"] == "Internal Server Error"
        assert api_exception.to_dict()["status"] == "500"
        assert api_exception.to_dict()["detail"] == "An internal server error occurred."
Ejemplo n.º 4
0
def test_handle_api_exception():
    error = APIException(
        title="Internal Server Error",
        status="500",
        detail="An internal server error occurred.",
    )

    response = handle_api_exception(error)

    assert response.response
    assert response.status == "500 INTERNAL SERVER ERROR"
    assert response.mimetype == "application/problem+json"
Ejemplo n.º 5
0
    def decorated_function(*args, **kwargs):
        """Retrieves the authentication information from Google Cloud Endpoints
        and passes it to user permissions service"""
        encoded_user_info = request.headers.get("X-Endpoint-API-UserInfo", None)
        if not encoded_user_info:
            raise APIException(status=401, title="User is not authenticated")

        decoded_user_info = base64_decode(encoded_user_info)
        user_info = json.loads(decoded_user_info)
        claims = json.loads(user_info.get("claims", "{}"))

        auth0_claims = claims.get("https://api.fluidly.com/app_metadata", {})
        internal_claims = claims.get("https://api.fluidly.com/internal_metadata", {})

        connection_id = request.view_args["connection_id"]
        user_id = auth0_claims.get("userId", None)

        try:
            is_service_account = internal_claims.get("isServiceAccount", False)

            if not is_service_account and not check_user_permissions(
                claims, connection_id
            ):
                raise APIException(status=403, title="User cannot access this resource")
        except (
            ValueError,
            UserPermissionsPayloadException,
            UserPermissionsRequestException,
        ):
            raise APIException(
                status=403, title="An issue occurred while fetching permissions"
            )

        g.connection_id = connection_id
        g.user_id = user_id
        return f(*args, **kwargs)
Ejemplo n.º 6
0
    def post_model_by_connection_id_query(table_name):
        model = get_model_by_tablename(base, table_name)
        if not model:
            return Response(status=404)
        try:
            payload = RequestSchema().loads(request.data)
        except (ValidationError, JSONDecodeError):
            raise APIException(status=422,
                               title="Request body has invalid json")

        raw_query = payload.get("query")
        query = snakify(raw_query)

        if not is_valid_query(model, query):
            return Response(response="Query is invalid", status=400)

        page = payload.get("page", 1)
        page_size = payload.get("page_size", DEFAULT_PAGE_SIZE)

        if page < 1:
            return Response(response="Pages start at 1", status=400)

        with db_session() as session:
            session.execute("set local statement_timeout = 10000")

            results = (session.query(model).filter_by(**query).offset(
                (page - 1) * page_size).limit(page_size).all())
            result_values = []

            if results:
                for m in results:
                    result_values.append(get_model_dict(m))

        return Response(
            response=json.dumps(
                {
                    "meta": {
                        "query": raw_query
                    },
                    "data": result_values
                },
                default=str),
            status=200,
            mimetype="application/json",
        )
Ejemplo n.º 7
0
def exception():
    raise APIException(status=500, title="An Api Exception occurred.")