Ejemplo n.º 1
0
def jquery_wtform_validator(class_, context, request):
    """
    Reusable server-side validator for jquery validator requests.

    Parameters
        class_ -- a wtform class
        context -- request context
        request -- http request

    Returns an HTTP OK response with the JSON validation status:
        * true -- passed
        * string -- error message

    More info: http://jqueryvalidation.org/remote-method
    """
    field = request.GET.get('validate')
    if not field or not hasattr(class_, field):
        return HTTPOk(
            json=_(u'Unknown field: {field}', mapping={'field': field}))
    form = class_.from_json({field: request.GET.get(field)})
    if not form.validate() and field in form.errors:
        # Send only the first error, jquery validation doesn't support lists
        return HTTPOk(json=form.errors[field][0])
    else:
        return HTTPOk(json=True)
Ejemplo n.º 2
0
def check_celery(request):
    '''
    GET request that executes a task via celery and retrieve result to verify celery service
    is functioning

    :param request:  Pyramid request object
    '''
    if pyramid.threadlocal.get_current_registry().settings is not None:
        queue = pyramid.threadlocal.get_current_registry().settings.get(
            'pdf.health_check.job.queue')
        timeout = float(
            pyramid.threadlocal.get_current_registry().settings.get(
                'pdf.celery_timeout'))
    else:
        queue = 'health_check'
        timeout = 10.0
    try:
        celery_response = health_check.apply_async(queue=queue)
        heartbeat_message = celery_response.get(timeout=timeout)
    except Exception as e:
        logger.error("Heartbeat failed at celery. Check celery. %s", str(e))
        return HTTPServerError()

    if heartbeat_message[0:9] == 'heartbeat':
        return HTTPOk()
    else:
        logger.error("Heartbeat failed at celery. Check celery.")
        return HTTPServerError()
Ejemplo n.º 3
0
    def adicional_delete(self):
        t = self.context
        Session.delete(t)

        msg = 'Registro deletado'
        res = dumps(dict(data=dict(code=200, message=msg)), ensure_ascii=False)
        return HTTPOk(body=res, content_type='application/json; charset=UTF-8')
Ejemplo n.º 4
0
    def render(self):  # pragma: no cover
        """Returns the generated JavaScript file.

        Returns:
            pyramid.httpexceptions.HTTPOk: HTTP response with JavaScript file as content.
        """
        return HTTPOk(body=self.run_())
Ejemplo n.º 5
0
    def view_set(self):
        questions = self.request.question_set.questions
        question_ids = [q.id for q in questions]

        template_vars = {
            'page_title': 'Viewing Question Set',
            'username': self.request.username,
            'question_set_description': self.request.question_set.description,
            'question_set_id': self.request.question_set.id,
            'questions': questions,
            'question_choices': forms.get_question_select_options(self.request.route_url('question_creation_form')),
            'csrf_token': self.request.session.get_csrf_token(),
        }
        if question_ids:
            reorder_form = forms.ReorderResourceForm(self.request, question_ids, 'Reorder')
        if self.request.method == 'GET':
            if question_ids:
                template_vars['reorder_form'] = reorder_form
            return template_vars
        elif self.request.method == 'POST' and question_ids:
            try:
                appstruct = reorder_form.validate(self.request.POST)
                self.request.question_set.reorder(appstruct, self.request.db)
                return HTTPOk()
            except ValueError as _:
                return HTTPClientError()
            return HTTPFound(self.request.route_url('profile'))
        else:
            return HTTPClientError()
Ejemplo n.º 6
0
def do_password_change(request):
    token = request.json_body.get('token') or ''
    password1 = request.json_body.get('password1', '').strip()
    password2 = request.json_body.get('password2', '').strip()
    localizer = request.localizer
    if password1 is '' or password2 is '' or password2 != password1:
        error = localizer.translate(
            _("The passwords that were entered are mismatched!"))
        raise JSONError(error, ErrorTypes.PASSWORD)

    # TODO: Check password quality!
    user, validity = verify_password_change_token(token)
    token_date = get_data_token_time(token)
    old_token = (user is None or token_date is None
                 or (user.last_login and token_date < user.last_login))

    if (validity != Validity.VALID or old_token):
        # V-, V+P+W-B-L-: Invalid or obsolete token (obsolete+logged in treated later.)
        # Offer to send a new token
        if validity != Validity.VALID:
            error = localizer.translate(
                _("This link is not valid. Do you want us to send another?"))
        else:
            error = localizer.translate(
                _("This link has been used. Do you want us to send another?"))
        raise JSONError(error, validity)
    user.password_p = password1
    user.successful_login()
    headers = remember(request, user.id)
    request.response.headerlist.extend(headers)
    return HTTPOk()
Ejemplo n.º 7
0
def cancel_job_batch(request):
    # type: (PyramidRequest) -> AnyResponseType
    """
    Dismiss operation for multiple jobs.

    Note:
        Will only stop tracking jobs when underlying remote provider services do not support cancel operation.
    """
    try:
        body = sd.DeleteJobsBodySchema().deserialize(request.json)
        jobs = body["jobs"]
    except Invalid as exc:
        raise HTTPUnprocessableEntity(json={"code": Invalid.__name__, "description": str(exc)})
    except Exception as exc:
        raise HTTPBadRequest(json={"code": "Could not parse request body.", "description": str(exc)})

    store = get_db(request).get_store(StoreJobs)
    found_jobs = []
    for job_id in jobs:
        try:
            job = store.fetch_by_id(job_id)
        except JobNotFound as exc:
            LOGGER.debug("Job [%s] not found, cannot be dismissed: [%s]", job_id, exc)
            continue
        found_jobs.append(job.id)
        try:
            dismiss_job_task(job, request)
        except JobNotFound as exc:
            LOGGER.debug("Job [%s] cannot be dismissed: %s.", job_id, exc.description)

    body["description"] = "Following jobs have been successfully dismissed."
    body = sd.BatchDismissJobsBodySchema().deserialize({"jobs": found_jobs})
    return HTTPOk(json=body)
Ejemplo n.º 8
0
def get_bill_list(request):
    """
    Get list of bills IDs.
    """
    store = get_db(request).get_store(StoreBills)
    bills = store.list_bills()
    return HTTPOk(json={"bills": [b.id for b in bills]})
Ejemplo n.º 9
0
def delete_local_process(request):
    # type: (PyramidRequest) -> AnyViewResponse
    """
    Unregister a local process.
    """
    db = get_db(request)
    proc_store = db.get_store(StoreProcesses)
    process = get_process(request=request)
    process_id = process.id
    if not process.mutable:
        raise HTTPForbidden(json={
            "title": "Process immutable.",
            "type": "ProcessImmutable",
            "detail": "Cannot delete an immutable process.",
            "status": HTTPForbidden.code,
            "cause": {"mutable": False}
        })
    job_store = db.get_store(StoreJobs)
    jobs, total = job_store.find_jobs(process=process_id, status=Status.RUNNING, page=None, limit=None)
    if total != 0:
        raise HTTPForbidden(json={
            "title": "ProcessBusy",
            "type": "ProcessBusy",
            "detail": "Process with specified identifier is in use by a least one job and cannot be undeployed.",
            "status": HTTPForbidden.code,
            "cause": {"jobs": [str(job.id) for job in jobs]}
        })
    if proc_store.delete_process(process_id, visibility=Visibility.PUBLIC):
        return HTTPOk(json={
            "description": sd.OkDeleteProcessResponse.description,
            "identifier": process_id,
            "undeploymentDone": True,
        })
    LOGGER.error("Existing process [%s] should have been deleted with success status.", process_id)
    raise HTTPForbidden("Deletion of process has been refused by the database or could not have been validated.")
Ejemplo n.º 10
0
def set_process_visibility(request):
    # type: (PyramidRequest) -> AnyViewResponse
    """
    Set the visibility of a registered local process.
    """
    visibility = Visibility.get(request.json.get("value"))
    process_id = request.matchdict.get("process_id")
    if not isinstance(process_id, str):
        raise HTTPUnprocessableEntity("Invalid process identifier.")
    if visibility not in Visibility:
        raise HTTPBadRequest(f"Invalid visibility value specified: {visibility!s}")

    try:
        store = get_db(request).get_store(StoreProcesses)
        process = store.fetch_by_id(process_id)
        if not process.mutable:
            raise HTTPForbidden("Cannot change the visibility of builtin process.")
        store.set_visibility(process_id, visibility)
        return HTTPOk(json={u"value": visibility})
    except TypeError:
        raise HTTPBadRequest("Value of visibility must be a string.")
    except ValueError:
        raise HTTPUnprocessableEntity(f"Value of visibility must be one of : {Visibility.values()!s}")
    except ProcessNotFound as ex:
        raise HTTPNotFound(str(ex))
Ejemplo n.º 11
0
def get_process_visibility(request):
    # type: (PyramidRequest) -> AnyViewResponse
    """
    Get the visibility of a registered local process.
    """
    process = get_process(request=request)
    return HTTPOk(json={u"value": process.visibility})
Ejemplo n.º 12
0
def get_local_process_payload(request):
    # type: (PyramidRequest) -> AnyViewResponse
    """
    Get a registered local process payload definition.
    """
    process = get_process(request=request)
    return HTTPOk(json=process.payload or {})
Ejemplo n.º 13
0
 def test_commit_veto(self):
     rsp1 = DummyResponse(HTTPOk().status, dict())
     self.assert_false(commit_veto(None, rsp1))
     rsp2 = DummyResponse(HTTPRedirection().status, dict())
     self.assert_true(commit_veto(None, rsp2))
     rsp3 = DummyResponse(HTTPRedirection().status, {'x-tm': 'commit'})
     self.assert_false(commit_veto(None, rsp3))
Ejemplo n.º 14
0
def update_sequence(request):
    """runs when adding a new sequence
    """
    logged_in_user = get_logged_in_user(request)

    sequence_id = request.params.get('sequence_id')
    sequence = Sequence.query.filter_by(id=sequence_id).first()

    name = request.params.get('name')
    code = request.params.get('code')

    status_id = request.params.get('status_id')
    status = Status.query.filter_by(id=status_id).first()

    if sequence and code and name and status:
        # get descriptions
        description = request.params.get('description')

        #update the sequence
        sequence.name = name
        sequence.code = code
        sequence.description = description
        sequence.status = status
        sequence.updated_by = logged_in_user
        sequence.date_updated = datetime.datetime.now()

        DBSession.add(sequence)

    else:
        logger.debug('there are missing parameters')
        logger.debug('name      : %s' % name)
        logger.debug('status    : %s' % status)
        HTTPServerError()

    return HTTPOk()
Ejemplo n.º 15
0
    def pedido_get_list(self):
        offset = int(self.request.GET.get('start', 0))
        limit = int(self.request.GET.get('size', 10))
        sort = self.request.GET.get('sort', 'finalizacao')
        order = self.request.GET.get('order', 'asc')
        cliente = self.request.GET.get('cliente')

        pedidos = Pedido.list(self.current_user.empresa_id, offset, limit,
                              sort, order, cliente)
        total = Pedido.total(self.current_user.empresa_id, cliente)[0]
        schema = PedidoSchema(many=is_iterable_but_not_string(pedidos),
                              strict=True)
        schema.context['user'] = self.request.user

        result = schema.dump(pedidos)

        if pedidos:
            res = dumps(dict(
                data=dict(code=200, totalItems=total, pedidos=result.data)),
                        ensure_ascii=False)
            return HTTPOk(body=res,
                          content_type='application/json; charset=UTF-8')

        msg = 'Nenhum registro encontrado'
        res = dumps(dict(error=dict(code=404, message=msg)),
                    ensure_ascii=False)
        return HTTPNotFound(body=res,
                            content_type='application/json; charset=UTF-8')
Ejemplo n.º 16
0
def get_quote_list(request):
    """
    Get list of quotes IDs.
    """

    page = int(request.params.get("page", "0"))
    limit = int(request.params.get("limit", "10"))
    filters = {
        "process_id":
        request.params.get("process", None)
        or request.matchdict.get("process_id", None),
        "page":
        page,
        "limit":
        limit,
        "sort":
        request.params.get("sort", sort.SORT_CREATED),
    }
    store = get_db(request).get_store(StoreQuotes)
    items, count = store.find_quotes(**filters)
    return HTTPOk(
        json={
            "count": count,
            "page": page,
            "limit": limit,
            "quotes": [quote.id for quote in items]
        })
def update_user(request):
    # ID
    user_id = request.matchdict.get('user_id')
    current_user_from_db = DBSession().query(User).filter_by(
        id=user_id).first()
    # First Name
    if request.matchdict.get('first_name'):
        new_first_name = request.matchdict.get('first_name')
    else:
        new_first_name = current_user_from_db.first_name
    # Last Name
    if request.matchdict.get('last_name'):
        new_last_name = request.matchdict.get('last_name')
    else:
        new_last_name = current_user_from_db.last_name

    # Created At
    createdAt = current_user_from_db.created_at

    with transaction.manager:
        DBSession.query(User).filter_by(id=user_id).update({
            "first_name":
            new_first_name,
            "last_name":
            new_last_name,
            "created_at":
            createdAt
        })
        return HTTPOk()
Ejemplo n.º 18
0
def api_gateway_auth(request):
    try:
        fullname = request.POST['username']
        password = request.POST['password']
    except KeyError:
        return HTTPBadRequest('Require username/password')

    if '/' in fullname:
        username, profilename = fullname.split('/', 1)
    else:
        username = fullname
        profilename = None

    user = DBSession.query(User).filter_by(username=username).first()
    if not user or not user.check_password(password) or not user.is_active:
        return HTTPForbidden('Invalid username or password.')
    if not user.is_paid:
        return HTTPForbidden('Free account')

    if profilename:
        profile = DBSession.query(Profile) \
                           .filter_by(name=profilename, uid=user.id).first()
        if not profile:
            return HTTPForbidden('Unknown profile')
    return HTTPOk(empty_body=True)
Ejemplo n.º 19
0
def do_password_change(request):
    token = request.json_body.get('token') or ''
    password = request.json_body.get('password') or ''
    # TODO: Check password quality!
    localizer = request.localizer
    user, validity = verify_password_change_token(token)
    token_date = get_data_token_time(token)
    old_token = (
        user is None or token_date is None or (
            user.last_login and token_date < user.last_login))

    if (validity != Validity.VALID or old_token):
        # V-, V+P+W-B-L-: Invalid or obsolete token (obsolete+logged in treated later.)
        # Offer to send a new token
        if validity != Validity.VALID:
            error = localizer.translate(_(
                "This link is not valid. Do you want us to send another?"))
        else:
            error = localizer.translate(_(
                "This link has been used. Do you want us to send another?"))
        raise JSONError(error, validity)
    user.password_p = password
    user.last_login = datetime.utcnow()
    headers = remember(request, user.id)
    request.response.headerlist.extend(headers)
    return HTTPOk()
Ejemplo n.º 20
0
def get_provider(request):
    # type: (PyramidRequest) -> AnyViewResponse
    """
    Get a provider definition (GetCapabilities).
    """
    service, _ = get_service(request)
    return HTTPOk(json=service.summary(request))
Ejemplo n.º 21
0
def get_job_stats(request):
    # type: (PyramidRequest) -> AnyResponseType
    """
    Retrieve the statistics of a job.
    """
    job = get_job(request)
    raise_job_dismissed(job, request)
    if job.status not in JOB_STATUS_CATEGORIES[StatusCategory.FINISHED] or job.status != Status.SUCCEEDED:
        raise JobStatisticsNotFound(json={
            "title": "NoJobStatistics",
            "type": "no-job-statistics",  # unofficial
            "detail": "Job statistics are only available for completed and successful jobs.",
            "status": JobStatisticsNotFound.code,
            "cause": {"status": job.status},
        })
    stats = job.statistics
    if not stats:  # backward compatibility for existing jobs before feature was added
        raise JobStatisticsNotFound(json={
            "title": "NoJobStatistics",
            "type": "no-job-statistics",  # unofficial
            "detail": "Job statistics were not collected for this execution.",
            "status": JobStatisticsNotFound.code,
            "cause": "Empty statistics."
        })
    body = sd.JobStatisticsSchema().deserialize(stats)
    return HTTPOk(json=body)
Ejemplo n.º 22
0
def bulk_delete_json(context, request):
    """
    Deletes forms in bulk
    """
    check_csrf_token(request)
    db_session = request.db_session

    class DeleteForm(Form):
        forms = wtforms.FieldList(
            ModelField(db_session=db_session, class_=datastore.Entity),
            validators=[wtforms.validators.DataRequired()])

    form = DeleteForm.from_json(request.json_body)

    if not form.validate():
        raise HTTPBadRequest(json={'errors': wtferrors(form)})

    entity_ids = [entity.id for entity in form.forms.data]

    external = context.__parent__.__tablename__
    key = context.__parent__.id

    (db_session.query(datastore.Entity).filter(
        datastore.Entity.id.in_(
            db_session.query(datastore.Context.entity_id).filter(
                datastore.Context.entity_id.in_(entity_ids)).filter(
                    datastore.Context.external == external).filter(
                        datastore.Context.key == key))).delete('fetch'))

    db_session.flush()

    return HTTPOk()
Ejemplo n.º 23
0
def purl_ideas(request):
    slug = request.matchdict['discussion_slug']
    discussion = Discussion.default_db.query(Discussion)\
        .filter_by(slug=slug).first()
    if not discussion:
        raise HTTPNotFound()
    furl = FrontendUrls(discussion)
    idea_id = furl.getRequestedIdeaId(request)
    idea = get_named_object(idea_id)
    phase = discussion.current_discussion_phase()
    if (discussion.preferences['landing_page'] and (
            phase is None or not phase.interface_v1)):
        if not idea:
            # If no idea is found, redirect to new home instead of 404
            # TODO: Determine if this is acceptable practice
            return HTTPSeeOther(location=request.route_url(
                'new_home', discussion_slug=discussion.slug))

        return HTTPSeeOther(
            location=urljoin(
                discussion.get_base_url(),
                furl.get_frontend_url(
                    'idea',
                    phase=phase.identifier,
                    themeId=idea.graphene_id())
            )
        )
    # V1 Idea
    return HTTPOk(
        location=request.route_url(
            'purl_ideas',
            discussion_slug=discussion.slug,
            remainder=quote_plus(type(idea).uri_generic(idea.id))
        )
    )
Ejemplo n.º 24
0
def WhoIsRequest(request):
    #
    # BACnet コマンド操作用インスタンス取得
    #
    app = request.registry.bacnetd.application
    bacnet = BACnetSimpleClient(app)

    #
    # Timeout の 取得
    #
    timeout = 10
    if 'timeout' in request.GET and request.GET['timeout'].isdigit():
        timeout = int(request.GET['timeout'])

    #
    # WhoIsRequest の 送信
    #
    bacnet.WhoIsRequest()

    #
    # WhoIsRequest を 投げてから最初の IAmRequestを受け取るまで待つ
    #
    try:
        device_id = app.responseQueue.get(timeout=timeout)
        return HTTPOk(json_body={'device_id': device_id})
    except Exception:
        #
        # タイムアウトを通知
        #
        return HTTPRequestTimeout()
Ejemplo n.º 25
0
def get_job_status(request):
    """
    Retrieve the status of a job.
    """
    job = get_job(request)
    job_status = job.json(request, self_link="status")
    return HTTPOk(json=job_status)
Ejemplo n.º 26
0
 def get_extract_by_id(self):
     time.sleep(2)
     if self._request.matchdict.get('egrid') == 'CH1234':
         with open('samples/extract.json') as f:
             content = json.loads(f.read())
         return HTTPOk(json_body=content)
     return HTTPServerError('An error occurred.')
Ejemplo n.º 27
0
    def adicional_update(self):
        json_body = self.request.json_body
        schema = AdicionalSchema(many=False, strict=True)
        schema.context['user'] = self.request.user
        schema.context['adicional'] = self.context

        try:
            adicional = schema.load(json_body)
        except ValidationError as err:
            errors = err.messages

            error_list = []
            for k, v in errors.items():
                error_list.append({'field': k, 'message': v})

            msg = 'Dados inválidos'
            res = dumps(
                dict(error=dict(code=400, message=msg, errors=error_list)),
                ensure_ascii=False)
            return HTTPBadRequest(
                body=res, content_type='application/json; charset=UTF-8')

        # com a deserialização ok a atualização é permitida
        self.context.descricao = adicional.data.descricao
        self.context.valor = adicional.data.valor

        # objeto de retorno precisa ser serializado
        result = schema.dump(self.context)

        res = dumps(dict(data=dict(code=200, adicional=result.data)),
                    ensure_ascii=False)
        return HTTPOk(body=res, content_type='application/json; charset=UTF-8')
Ejemplo n.º 28
0
def set_process_visibility(request):
    """
    Set the visibility of a registered local process.
    """
    visibility_value = request.json.get("value")
    process_id = request.matchdict.get("process_id")
    if not isinstance(process_id, str):
        raise HTTPUnprocessableEntity("Invalid process identifier.")
    if not isinstance(visibility_value, str):
        raise HTTPUnprocessableEntity(
            "Invalid visibility value specified. String expected.")
    if visibility_value not in VISIBILITY_VALUES:
        raise HTTPBadRequest("Invalid visibility value specified: {!s}".format(
            visibility_value))

    try:
        store = get_db(request).get_store(StoreProcesses)
        process = store.fetch_by_id(process_id)
        if process.type == PROCESS_BUILTIN:
            raise HTTPForbidden(
                "Cannot change the visibility of builtin process.")
        store.set_visibility(process_id, visibility_value)
        return HTTPOk(json={u"value": visibility_value})
    except TypeError:
        raise HTTPBadRequest("Value of visibility must be a string.")
    except ValueError:
        raise HTTPUnprocessableEntity(
            "Value of visibility must be one of : {!s}".format(
                list(VISIBILITY_VALUES)))
    except ProcessNotFound as ex:
        raise HTTPNotFound(str(ex))
Ejemplo n.º 29
0
def delete_schema_json(context, request):
    check_csrf_token(request)
    db_session = request.db_session
    schema_name = request.matchdict.get('schema')

    (exists, ) = (db_session.query(
        db_session.query(models.Study).filter(
            models.Study.schemata.any(name=schema_name)).filter(
                models.Study.id == context.id).exists()).one())

    if not exists:
        raise HTTPNotFound()

    # Remove from cycles
    db_session.execute(models.cycle_schema_table.delete().where(
        models.cycle_schema_table.c.cycle_id.in_(
            db_session.query(models.Cycle.id).filter_by(
                study=context).subquery())
        & models.cycle_schema_table.c.schema_id.in_(
            db_session.query(datastore.Schema.id).filter_by(
                name=schema_name).subquery())))

    # Remove from study
    db_session.execute(models.study_schema_table.delete().where(
        (models.study_schema_table.c.study_id == context.id)
        & (models.study_schema_table.c.schema_id.in_(
            db_session.query(datastore.Schema.id).filter_by(
                name=schema_name).subquery()))))

    mark_changed(db_session)

    # Expire relations so they load their updated values
    db_session.expire_all()

    return HTTPOk()
Ejemplo n.º 30
0
def admin_ui(request: PyramidRequest):
    admin_resource = get_admin(request.root)
    api_info_url = request.resource_url(
        admin_resource['api_info.json']).rstrip('/')
    admin_params = [f'"apiInfoUrl": "{api_info_url}"']

    auth_provider = http_client = ''
    ui_settings = get_admin_ui_settings(request.registry)
    if ui_settings.auth_provider:
        auth_provider = ui_settings.auth_provider.code
        admin_params.append(
            f'"getAuthProvider": {ui_settings.auth_provider.name}')
    if ui_settings.http_client:
        http_client = ui_settings.http_client.code
        admin_params.append(f'"getHttpClient": {ui_settings.http_client.name}')

    admin_params = ','.join(admin_params)
    admin_ui_params = TEMPLATE.format(
        auth_provider=auth_provider,
        http_client=http_client,
        admin_params=f'{{{admin_params}}}',
    )
    html = ui_settings.index_html_tpl.replace('__ADMIN_PARAMS__',
                                              admin_ui_params)
    response = HTTPOk(content_type='text/html', conditional_response=True)
    response.text = html
    response.md5_etag()
    return response