Ejemplo n.º 1
0
def write_message(ag_name, ag, user_ag):
    subject = request.values.get('subject')
    message = request.values.get('message')
    email = request.values.get('email')
    if subject is None and not bool(re.match(MessageRegex.subject, subject)):
        return PreconditionFailed(description='subject')
    if message is None and not bool(re.match(MessageRegex.message, message)):
        return PreconditionFailed(description='message')
    new_message = AGMessage()
    new_message.subject = subject
    new_message.message = message
    new_message.ag_id = ag.id
    db.session.add(new_message)
    db.session.flush()
    for user in ag.actual_users:
        new_assoc = UserAGMessage()
        new_assoc.user_id = user.id
        new_assoc.message_id = new_message.id
        new_assoc.read = False
        db.session.add(new_assoc)
    if email is not None:
        mail.ag_mail(agmessage=new_message, ag=ag)
    db.session.commit()
    flash('Successfully send message', 'success')
    return redirect(url_for('ag.ag_dashboard', ag_name=ag_name))
Ejemplo n.º 2
0
    def __verify_hackathon(self, hackathon_name):
        """validate the event_start_time and event_end_time of a hackathon

        Will return None if hackathon not found or current time is not between its start time and end time
        """
        hackathon = self.hackathon_manager.get_hackathon_by_name(hackathon_name)
        if hackathon:
            if HackathonConfig.CLOUD_PROVIDER not in hackathon.config:
                raise PreconditionFailed("No cloud resource is configured for this hackathon.")
            if self.util.get_now() < hackathon.event_end_time:
                return hackathon
            else:
                raise PreconditionFailed("Hackathon was already ended")
        else:
            raise NotFound("Hackathon with name %s not found" % hackathon_name)
Ejemplo n.º 3
0
def lookup(
    model: CommonColumns,
    record_id: Union[int, str],
    check_etag: bool = False,
    find_func: Optional[Callable[[Union[int, str]], BaseModel]] = None,
):
    """
    Search the `model` relation in the database for a record with id `record_id`. 
    If `check_etag` is true, only proceed with the lookup if the client-provided 
    etag matches the etag on the record if a record is found.
    """
    if not find_func:
        find_func = model.find_by_id

    if check_etag:
        etag = request.headers.get(ETAG_HEADER)
        if not etag:
            raise PreconditionRequired(
                "request must provide an If-Match header")

    record = find_func(record_id)
    if not record:
        raise NotFound()

    if check_etag:
        if etag != record._etag:
            raise PreconditionFailed(
                "provided ETag does not match the stored ETag for this record")

    return record
Ejemplo n.º 4
0
def get_auth_with_validation(token):
    """
    Validates Authorization token (Bearer) via auth service.
    This method is automatically called by connection for http methods with defined authorization
    in openapi file.
    :param token: Authorization token (from Authorization header_
    :return: RFC7662 compliant dict (with user details under 'sub' key)
    """
    try:
        company_id = connexion.request.headers['X-Company-ID']
        UUID(
            company_id
        )  # try to parse to see if valid uuid, connexion validates it after auth

        # some external validation
        user_data = 'call to external validator'

        return {'scope': 'documents presigned_url', 'sub': user_data}
    except (TypeError, ValueError):
        raise BadRequest(
            description=
            'All ids in request, whether params or in-body, must be valid UUID.'
        )
    except KeyError:
        raise PreconditionFailed(description='Missing X-Company-ID header.')
    except HTTPError as ex:
        msg = ex.response.json().get('message')
        err_msg = msg if msg else ex.response.text
        raise Unauthorized(err_msg)
 def update(self, model, expected_version_id, date=None, client_id=None):
     if not expected_version_id:
         raise PreconditionFailed(
             'If-Match header missing when updating resource')
     existing_obj = model.key.get()
     if not existing_obj:
         raise NotFound('{} with key {} does not exist'.format(
             self.model_name, model.key))
     if existing_obj.last_modified:
         version_id = self.make_version_id(existing_obj.last_modified)
         if version_id != expected_version_id:
             raise PreconditionFailed(
                 'If-Match header was {}; stored version was {}'.format(
                     expected_version_id, version_id))
     model.last_modified = None
     return self.store(model, date, client_id)
Ejemplo n.º 6
0
def abort_job(id):
    """Abort a job by API Job ID.

    Args:
        id (str): Job ID to be aborted

    Returns: None
    """
    # Attempt is unused in aborting because only one attempt can be running at
    # a time.
    proj_id, job_id, task_id, _ = job_ids.api_to_dsub(id, _provider_type())
    provider = providers.get_provider(_provider_type(), proj_id, _auth_token())

    # TODO(bryancrampton): Add flag to ddel to support deleting only
    # 'singleton' tasks.
    status = get_job(id).status

    # TODO(https://github.com/googlegenomics/dsub/issues/81): Remove this
    # provider-specific logic
    if isinstance(provider, stub.StubJobProvider):
        status = status[0]

    if status != job_statuses.ApiStatus.RUNNING:
        raise PreconditionFailed(
            'Job already in terminal status `{}`'.format(status))

    # TODO(https://github.com/googlegenomics/dsub/issues/92): Remove this
    # hacky re-routing of stdout once dsub removes it from the python API
    deleted = execute_redirect_stdout(
        lambda: ddel.ddel_tasks(provider=provider,
                                job_ids={job_id},
                                task_ids={task_id} if task_id else None))
    if len(deleted) != 1:
        raise InternalServerError('Failed to abort dsub job')
Ejemplo n.º 7
0
    def create_new_hackathon(self, context):
        """Create new hackathon based on the http body

        Hackathon name is unique so duplicated names are not allowd.

        :type context: Context
        :param context: the body of http request that contains fields to create a new hackathon

        :rtype: dict
        """
        if Hackathon.objects(name=context.name).count() > 0:
            raise PreconditionFailed("hackathon name already exists")

        self.log.debug("add a new hackathon:" + context.name)
        new_hack = self.__create_hackathon(g.user, context)

        self.create_hackathon_notice(
            new_hack.id, HACK_NOTICE_EVENT.HACK_CREATE,
            HACK_NOTICE_CATEGORY.HACKATHON)  # hackathon create

        # init data is for local only
        if self.util.is_local():
            self.__create_default_data_for_local(new_hack)

        return new_hack.dic()
Ejemplo n.º 8
0
def _enforce_cli_version():
    """
    If the current request appears to come from the CLI and not the Portal, enforce the configured
    minimum CLI version.

    Raises:
        BadRequest if could not parse the User-Agent string
        PreconditionFailed if too low CLI version
    """
    user_agent = request.headers.get("User-Agent")

    # e.g., during testing no User-Agent header is supplied
    if not user_agent:
        return

    try:
        client, client_version = user_agent.split("/", 1)
    except ValueError:
        logger.error(f"Unrecognized user-agent string format: {user_agent}")
        raise BadRequest("could not parse User-Agent string")

    # The CLI sets the User-Agent header to `cidc-cli/{version}`,
    # so we can assess whether the requester needs to update their CLI.
    is_old_cli = client == "cidc-cli" and version.parse(
        client_version) < version.parse(app.config["MIN_CLI_VERSION"])

    if is_old_cli:
        logger.info("cancelling request: detected outdated CLI")
        message = (
            "You appear to be using an out-of-date version of the CIDC CLI. "
            "Please upgrade to the most recent version:\n"
            "    pip3 install --upgrade cidc-cli")
        raise PreconditionFailed(message)
Ejemplo n.º 9
0
    def start_pre_alloc_exprs(self, user, template_name, hackathon_name=None, pre_alloc_num=0):
        self.log.debug("start_pre_alloc_exprs: %d " % pre_alloc_num)
        if pre_alloc_num == 0:
            return

        hackathon = self.__verify_hackathon(hackathon_name)
        template = self.__verify_template(hackathon, template_name)

        starter = self.get_starter(hackathon, template)
        if not starter:
            raise PreconditionFailed("either template not supported or hackathon resource not configured")

        while pre_alloc_num > 0:
            context = starter.start_expr(Context(
                template=template,
                user=user,
                hackathon=hackathon,
                pre_alloc_enabled=True))

            if context == None:
                self.log.debug("pre_alloc_num left: %d " % pre_alloc_num)
                break
            else:
                self.__report_expr_status(context.experiment)
                pre_alloc_num -= 1
Ejemplo n.º 10
0
  def _validate_update(self, session, obj, existing_obj):
    """Validates that an update is OK before performing it. (Not applied on insert.)

    By default, validates that the object already exists, and if an expected version ID is provided,
    that it matches.
    """
    if not existing_obj:
      raise NotFound('%s with id %s does not exist' % (self.model_type.__name__, id))
    if existing_obj.version != obj.version:
      raise PreconditionFailed('Expected version was %s; stored version was %s' % \
                               (obj.version, existing_obj.version))
    self._validate_model(session, obj)
Ejemplo n.º 11
0
    def __start_new_expr(self, hackathon, template, user):
        starter = self.get_starter(hackathon, template)

        if not starter:
            raise PreconditionFailed(
                "either template not supported or hackathon resource not configured"
            )

        context = starter.start_expr(
            Context(template=template, user=user, hackathon=hackathon))

        return self.__report_expr_status(context.experiment)
Ejemplo n.º 12
0
    def __check_hackathon_event_time(self, hackathon_name):
        """validate the event_start_time and event_end_time of a hackathon

        Will return None if hackathon not found or current time is not between its start time and end time
        """
        hackathon = self.hackathon_manager.get_hackathon_by_name(
            hackathon_name)
        if hackathon:
            if self.util.get_now() < hackathon.event_end_time:
                return hackathon
            else:
                raise PreconditionFailed("Hackathon was already ended")
        else:
            return None
Ejemplo n.º 13
0
 def set_pipeline_in_progress(self):
   with self.session() as session:
     running_version = self.get_version_in_progress_with_session(session)
     if running_version:
       if running_version.date + METRICS_LOCK_TIMEOUT <= clock.CLOCK.now():
         logging.warning("Metrics version %s timed out; breaking lock." %
                         running_version.metricsVersionId)
         running_version.inProgress = False
         session.merge(running_version)
       else:
         # If the timeout hasn't elapsed, don't allow a new pipeline to start.
         raise PreconditionFailed('Metrics pipeline is already running.')
     new_version = MetricsVersion(inProgress=True, dataVersion=SERVING_METRICS_DATA_VERSION)
     self.insert_with_session(session, new_version)
   return new_version.metricsVersionId
Ejemplo n.º 14
0
    def __verify_template(self, hackathon, template_name):
        template = self.template_library.get_template_info_by_name(template_name)
        if not template:
            raise NotFound("template cannot be found by name '%s'" % template_name)

        if not hackathon:
            # hackathon is None means it's starting expr for template testing
            return template

        hackathon_templates = hackathon.templates
        template_ids = [t.id for t in hackathon_templates]
        if template.id not in template_ids:
            raise PreconditionFailed("template '%s' not allowed for hackathon '%s'" % (template_name, hackathon.name))

        return template
Ejemplo n.º 15
0
    def put(self, service_provider_id, requirement_id):
        accept = request.headers.get('accept')
        if not (accept in ('application/rdf+xml', 'application/json',
                           'application/ld+json', 'application/xml',
                           'application/atom+xml')):
            raise UnsupportedMediaType

        content = request.headers.get('content-type')
        if not (content in ('application/rdf+xml', 'application/json',
                            'application/ld+json', 'application/xml',
                            'application/atom+xml')):
            raise UnsupportedMediaType

        endpoint_url = url_for('{}.{}'.format(request.blueprint,
                                              self.endpoint),
                               service_provider_id=service_provider_id,
                               requirement_id=requirement_id)
        base_url = '{}{}'.format(request.url_root.rstrip('/'), endpoint_url)

        etag = request.headers.get(key='If-Match', default=None, type=str)

        rq = CsvRequirementRepository('specs')
        r = rq.find(requirement_id)
        r.about = base_url

        if not r:
            raise NotFound()
        # elif r.identifier != requirement_id:
        #     raise Conflict()
        elif not etag:
            raise BadRequest()
        else:
            dig = r.digestion()
            if dig != etag.strip("\""):
                raise PreconditionFailed()

        g = Graph()
        try:
            data = g.parse(data=request.data, format='xml')
        except SAXParseException:
            raise NotAcceptable()

        req = update_requirement(requirement_id, data)
        if isinstance(req, Requirement):
            req.to_rdf(self.graph, base_url, attributes)
            return self.create_response(self.graph)
        else:
            return make_response(req.description, req.code)
Ejemplo n.º 16
0
def gift_purchase(purchase_uuid, customer_mail_address):
    """
    Replace the customer mail address of a purchase with a new one
    """
    result = db.session.query(Purchase) \
        .filter(Purchase.purchase_date > dt.utcnow() - td(minutes=2)) \
        .filter(Purchase.purchase_gifted == False) \
        .filter(Purchase.purchase_code_uuid == purchase_uuid) \
        .first()
    if result is not None:
        if result.purchase_customer_mail_address == customer_mail_address:
            raise PreconditionFailed('Customer is trying to gift his own purchase')
        result.purchase_customer_mail_address = customer_mail_address
        result.purchase_gifted = True
        db.session.commit()
        return "", 204
    else:
        raise NotFound()
Ejemplo n.º 17
0
    def __check_template_status(self, hackathon, template_name):
        template = self.template_library.get_template_info_by_name(
            template_name)
        if not template:
            raise NotFound("template cannot be found by name '%s'" %
                           template_name)

        if not hackathon:
            # hackathon is None means it's starting expr for template testing
            return template

        hackathon_templates = self.hackathon_template_manager.get_templates_by_hackathon_id(
            hackathon.id)
        template_ids = [h.template_id for h in hackathon_templates]
        if template.id not in template_ids:
            raise PreconditionFailed(
                "template '%s' not allowed for hackathon '%s'" %
                (template_name, hackathon.name))

        return template
Ejemplo n.º 18
0
    def create_new_hackathon(self, context):
        """Create new hackathon based on the http body

        Hackathon name is unique so duplicated names are not allowd.

        :type context: Context
        :param context: the body of http request that contains fields to create a new hackathon

        :rtype: dict
        """
        hackathon = self.__get_hackathon_by_name(context.name)
        if hackathon is not None:
            raise PreconditionFailed("hackathon name already exists")

        self.log.debug("add a new hackathon:" + repr(context))
        new_hack = self.__create_hackathon(context)

        # todo remove the following line ASAP
        self.__test_data(new_hack)

        return new_hack.dic()
Ejemplo n.º 19
0
    def create_new_hackathon(self, context):
        """Create new hackathon based on the http body

        Hackathon name is unique so duplicated names are not allowd.

        :type context: Context
        :param context: the body of http request that contains fields to create a new hackathon

        :rtype: dict
        """
        hackathon = self.get_hackathon_by_name(context.name)
        if hackathon is not None:
            raise PreconditionFailed("hackathon name already exists")

        self.log.debug("add a new hackathon:" + context.name)
        new_hack = self.__create_hackathon(context)

        # init data is for local only
        if self.util.is_local():
            self.__create_default_data_for_local(new_hack)

        return new_hack.dic()
Ejemplo n.º 20
0
Archivo: app.py Proyecto: denz/ldp
    def dispatch_request(self):
        req = _request_ctx_stack.top.request

        if req.routing_exception is not None:
            self.raise_routing_exception(req)

        if req.url_rule.bound_to is not None:
            rule = req.url_rule.bound_to
        else:
            rule = req.url_rule

        rvars = rule.resource_vars

        req.resource_adapters = {}
        for varname, value in req.view_args.items():
            if varname in rvars:
                req.resource_adapters[varname] = \
                    self.resource_adapter_class(req,
                                                self,
                                                req.view_args[varname],
                                                req.url_rule.context,
                                                req.url_rule.pool,
                                                req.url_rule.selectors)
                if req.url_rule.bound_to\
                        and varname == req.url_rule.bound_to.primary_resource:
                    req.resource_adapters['resource'] \
                        = req.resource_adapters[varname]

        for varname in req.resource_adapters:
            resource = req.resource_adapters[varname].resource
            if resource is None and req.method is not 'PUT':
                raise NotFound('Resource %s' % req.view_args[varname])
            req.view_args[varname] = resource
        if 'If-Match' in req.headers:
            if req.headers['If-Match'] != aggregated_etag(req):
                req.routing_exception = PreconditionFailed('Resource changed')
                self.raise_routing_exception(req)
        return super(LDP, self).dispatch_request()
Ejemplo n.º 21
0
    def _validate_patch_update(self, model, resource, expected_version):
        if expected_version != model.version:
            raise PreconditionFailed('Expected version was %s; stored version was %s' % \
                                     (expected_version, model.version))
        required_cancelled_fields = [
            'amendedReason', 'cancelledInfo', 'status'
        ]
        required_restored_fields = ['amendedReason', 'restoredInfo', 'status']
        if 'status' not in resource:
            raise BadRequest('status of cancelled/restored is required')

        if resource['status'] == 'cancelled':
            if model.orderStatus == BiobankOrderStatus.CANCELLED:
                raise BadRequest(
                    'Can not cancel an order that is already cancelled.')
            for field in required_cancelled_fields:
                if field not in resource:
                    raise BadRequest(
                        '%s is required for a cancelled biobank order' % field)
            if 'site' not in resource[
                    'cancelledInfo'] or 'author' not in resource[
                        'cancelledInfo']:
                raise BadRequest(
                    'author and site are required for cancelledInfo')

        elif resource['status'] == 'restored':
            if model.orderStatus != BiobankOrderStatus.CANCELLED:
                raise BadRequest(
                    'Can not restore an order that is not cancelled.')
            for field in required_restored_fields:
                if field not in resource:
                    raise BadRequest(
                        '%s is required for a restored biobank order' % field)
            if 'site' not in resource[
                    'restoredInfo'] or 'author' not in resource['restoredInfo']:
                raise BadRequest(
                    'author and site are required for restoredInfo')