Пример #1
0
def get_entity(id, action):
    entity, obj = fetch_entity(id)
    obj_or_404(entity)
    if entity.get('$bulk') and action == request.authz.WRITE:
        raise ImATeapot("Cannot write this entity.")
    require(request.authz.can(entity.get('collection_id'), action))
    return entity, obj
def test_render_error_page_passes_error_message_as_context(
        render_template, app_with_mocked_logger):
    render_template.side_effect = [
        TemplateNotFound('Oh dear'), "successful rendering"
    ]
    with app_with_mocked_logger.test_request_context('/'):
        exc_instance = ImATeapot()
        assert render_error_page(
            exc_instance,
            error_message="Hole in Teapot") == ("successful rendering", 500)
        assert render_template.call_args_list == [
            mock.call('errors/500.html', error_message="Hole in Teapot"),
            mock.call('toolkit/errors/500.html',
                      error_message="Hole in Teapot")
        ]
        assert app_with_mocked_logger.logger.warning.mock_calls == [
            mock.call(
                'Rendering error page',
                exc_info=True,
                extra={
                    'e': exc_instance,
                    'status_code': None,
                    'error_message': "Hole in Teapot",
                },
            )
        ]
Пример #3
0
def _get_json_data():
    data = request.get_json()

    if not data:
        raise ImATeapot('Invalid JSON Request Data')

    return data
def test_api_json_error_handler(app_with_mocked_logger):
    with app_with_mocked_logger.test_request_context('/'):
        try:
            raise ImATeapot("Simply teapot all over me!")
        except ImATeapot as e:
            response = json_error_handler(e)
            assert json.loads(response.get_data()) == {
                "error": "Simply teapot all over me!",
            }
            assert response.status_code == 418
            assert app_with_mocked_logger.logger.warning.mock_calls == []
Пример #5
0
def get_entity(id, action):
    entity, obj = fetch_entity(id)
    if obj is None:
        entity = obj_or_404(entity)
        # Apply roles-based security to dataset-sourced entities.
        request.authz.require(request.authz.check_roles(entity.get('roles')))
        # Cannot edit them:
        if action == request.authz.WRITE:
            raise ImATeapot("Cannot write this entity.")
    else:
        collections = request.authz.collections.get(action)
        request.authz.require(obj.collection_id in collections)
    return entity, obj
def test_render_error_page_for_unknown_status_code_defaults_to_500(
        render_template, app_with_mocked_logger):
    with app_with_mocked_logger.test_request_context('/'):
        exc_instance = ImATeapot()
        assert render_error_page(exc_instance) == (
            render_template.return_value, 500)
        assert render_template.call_args_list == [
            mock.call('errors/500.html', error_message=None)
        ]
        assert app_with_mocked_logger.logger.warning.mock_calls == [
            mock.call(
                'Rendering error page',
                exc_info=True,
                extra={
                    'e': exc_instance,
                    'status_code': None,
                    'error_message': None,
                },
            )
        ]
Пример #7
0
def create_hacker():
    """
    Creates a new Hacker.
    ---
    tags:
        - hacker
    summary: Create Hacker
    operationId: create_hacker
    requestBody:
        content:
            application/json:
                schema:
                    allOf:
                        - $ref: '#/components/schemas/Hacker'
                        - type: object
                          properties:
                            isaccepted:
                                readOnly: true
                            rsvp_status:
                                readOnly: true
                            resume_id:
                                type: string
            multipart/form-data:
                schema:
                    type: object
                    properties:
                        hacker:
                            deprecated: true
                            allOf:
                                - $ref: '#/components/schemas/Hacker'
                                - type: object
                                  description: >
                                    Deprecated,
                                    do not use `multipart/form-data`,
                                    use `application/json`
                                    and upload the resume through the
                                    `/api/hackers/resume/` POST endpoint.
                                  properties:
                                    isaccepted:
                                        readOnly: true
                                    rsvp_status:
                                        readOnly: true
                        resume:
                             deprecated: true
                             type: string
                             format: binary
                encoding:
                    hacker:
                        contentType: application/json
                    resume:
                        contentType: application/pdf
        description: Created Hacker Object
        required: true
    responses:
        201:
            description: OK
        400:
            description: Bad request.
        404:
            description: A resume with the provided id does not exist.
        409:
            description: Sorry, that email already exists.
        422:
            description: >
                Empty JSON object received or
                the required fields `/mlh/mlh_code_of_conduct` and
                `/mlh/mlh_privacy_and_contest_terms` are not `true`
        418:
            description: >
                A field has been provided that does not
                exist for this endpoint.
        5XX:
            description: Unexpected error.
    """
    if "multipart/form-data" in request.content_type:
        try:
            data = json.loads(request.form.get("hacker"))
        except JSONDecodeError:
            raise BadRequest("Invalid JSON sent in hacker form part.")
    elif request.content_type == "application/json":
        data = request.get_json()
    else:
        raise UnsupportedMediaType()

    resume = None

    if data is None:
        raise BadRequest("No Hacker data received!")

    if not data:
        raise UnprocessableEntity()

    if "birthday" in data:
        try:
            data["birthday"] = dateutil.parser.parse(data["birthday"])
        except ParserError:
            raise BadRequest("Invalid birthday, must be in ISO8601 format")

    if "date" in data:
        del data["date"]
    """Check for mlh authorization checkboxes"""
    no_mlh_msg = ("Hacker must agree to the MLH Code of Conduct, "
                  "the MLH Privacy Policy, "
                  "and the MLH Contest Terms and Conditions "
                  "by marking the fields `/mlh/mlh_code_of_conduct`, and "
                  "`/mlh/mlh_privacy_and_contest_terms` as `true`")

    if "mlh" not in data:
        raise UnprocessableEntity(no_mlh_msg)

    if (not data["mlh"].get("mlh_code_of_conduct")
            or not data["mlh"].get("mlh_privacy_and_contest_terms")):
        raise UnprocessableEntity(no_mlh_msg)

    if "resume" in request.files:
        resume = request.files["resume"]

        if resume.content_type != "application/pdf":
            raise UnsupportedMediaType()

    if "resume_id" in data:
        with sentry_sdk.start_span(
                op="db.findOne",
                description="Get Existing Resume Document") as span:
            span.set_data("db.query", {"_id": data["resume_id"]})
            try:
                resume_doc = Resume.objects.get(id=data["resume_id"])
            except ValidationError:
                raise BadRequest(
                    f"{data['resume_id']} is not a valid ObjectId.")
            except DoesNotExist:
                raise NotFound(f"Resume with id `{data['resume_id']}` "
                               "does not exist, it may have expired.")
    elif resume:
        with sentry_sdk.start_span(op="db.insertOne",
                                   description="Create new empty Resume"):
            resume_doc = Resume(attached=True)
    else:
        resume_doc = None

    with sentry_sdk.start_span(op="db.insertOne", description="Create Hacker"):
        try:
            hacker = Hacker.createOne(**data)

            if resume and resume_doc:
                hacker.resume = resume_doc

                with sentry_sdk.start_span(
                        op="db.gridfs.put",
                        description="Put resume into GridFS"):
                    hacker.resume.file.put(resume,
                                           content_type="application/pdf")

                with sentry_sdk.start_span(op="db.updateOne",
                                           description="Save resume document"):

                    hacker.resume.save()
            elif "resume_id" in data and resume_doc:
                with sentry_sdk.start_span(op="db.updateOne",
                                           description="Save resume document"):
                    hacker.resume = resume_doc

                    hacker.resume.attached = True

                    hacker.resume.save()

            hacker.save()

        except NotUniqueError:
            raise Conflict("Sorry, that email already exists.")
        except ValidationError:
            raise BadRequest()
        except FieldDoesNotExist:
            raise ImATeapot("Request contains fields that do not exist "
                            "for the current resource.")

    res = {"status": "success", "message": "Hacker was created!"}

    if "multipart/form-data" in request.content_type:
        res = make_response(res)
        res.headers["Deprecation"] = (
            "The use of multipart/form-data is deprecated,"
            " use `application/json` and upload the resume through the "
            "/api/hackers/resume/ POST endpoint.")

    return res, 201
Пример #8
0
def make_coffee():
    raise ImATeapot()
Пример #9
0
 def on_run_files(self, request):
     log.debug("In run_files endpoint")
     raise ImATeapot()
Пример #10
0
 def raise_teapot(app, req):
     raise ImATeapot()
Пример #11
0
 def raise_418(app, req):
     raise ImATeapot()