Esempio n. 1
0
def delete_row(table_name, uids):
    """
    Deletes a row in a table

    :param table_name: Name of the table
    :param uids: Array with uids
    :param nickname: Current nickname of the user
    :param _tn: Translator
    :return: Empty string or error message
    """
    LOG.debug("%s %s", table_name, uids)
    table = table_mapper[table_name.lower()]['table']
    try:
        # check if there is a table, where uid is not the PK!
        if table_name.lower() == 'settings':
            uid = DBDiscussionSession.query(User).filter_by(nickname=uids[0]).first().uid
            DBDiscussionSession.query(table).filter_by(author_uid=uid).delete()
        elif table_name.lower() == 'premise':
            DBDiscussionSession.query(table).filter(Premise.premisegroup_uid == uids[0],
                                                    Premise.statement_uid == uids[1]).delete()
        else:
            DBDiscussionSession.query(table).filter_by(uid=uids[0]).delete()

    except IntegrityError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy IntegrityError: ' + str(e))
    except ProgrammingError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy ProgrammingError: ' + str(e))

    DBDiscussionSession.flush()
    transaction.commit()
    return True
Esempio n. 2
0
def update_row(table_name, uids, keys, values):
    """
    Updates the data in a specific row of an table

    :param table_name: Name of the table
    :param uids: Array with uids
    :param keys: Array with keys
    :param values: Array with values
    :return: Empty string or error message
    """
    table = table_mapper[table_name.lower()]['table']
    _tn = Translator('en')
    try:
        update_dict = __update_row_dict(table, values, keys, _tn)
    except ProgrammingError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy ProgrammingError: ' + str(e))

    try:
        __update_row(table, table_name, uids, update_dict)
    except IntegrityError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy IntegrityError: ' + str(e))
    except ProgrammingError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy ProgrammingError: ' + str(e))

    DBDiscussionSession.flush()
    transaction.commit()
    return True
Esempio n. 3
0
    def _oauth2_login(self, user: static.User) -> pyramid.response.Response:
        self.request.user_ = user
        LOG.debug(
            "Call OAuth create_authorization_response with:\nurl: %s\nmethod: %s\nbody:\n%s",
            self.request.current_route_url(_query=self.request.GET),
            self.request.method,
            self.request.body,
        )
        headers, body, status = oauth2.get_oauth_client(
            self.request.registry.settings).create_authorization_response(
                self.request.current_route_url(_query=self.request.GET),
                self.request.method,
                self.request.body,
                self.request.headers,
            )
        if hasattr(self.request, "tm"):
            self.request.tm.commit()
        LOG.debug(
            "OAuth create_authorization_response return\nstatus: %s\nbody:\n%s",
            status, body)

        if status == 302:
            raise HTTPFound(location=headers["Location"])
        if status != 200:
            if body:
                raise exception_response(status, details=body)
            raise exception_response(status)
        return set_common_headers(
            self.request,
            "login",
            Cache.PRIVATE_NO,
            response=Response(body, headers=headers.items()),
        )
Esempio n. 4
0
def request_params(request):
    try:
        params = NestedMultiDict(request.GET, request.POST)
    except UnicodeDecodeError:
        response = exception_response(422)
        response.body = dumps(
            error_handler(
                request, response.code, {
                    'location': 'body',
                    'name': 'data',
                    'description': 'Could not decode params'
                }))
        response.content_type = 'application/json'
        raise response
    except Exception as e:
        response = exception_response(422)
        response.body = dumps(
            error_handler(
                request, response.code, {
                    'location': 'body',
                    'name': str(e.__class__.__name__),
                    'description': str(e)
                }))
        response.content_type = 'application/json'
        raise response
    return params
Esempio n. 5
0
def status(request):
    """Check the Web Runner and Scrapyd Status"""

    settings = request.registry.settings

    scrapyd_baseurl = settings[SCRAPYD_BASE_URL_KEY]
    scrapyd_interf = Scrapyd(scrapyd_baseurl)

    output = scrapyd_interf.get_operational_status()

    if request.params:
        items = [x.split(':', 1) for x in request.params.getall('return')]
        output = dict_filter(output, items)

        if 'application/json' in request.accept:
            pass
        elif 'text/plain' in request.accept:
            request.override_renderer = 'string'
            if len(output) != 1:
                raise exc.exception_response(406)
            else:
                output = output.values()[0]
                if not isinstance(output, numbers.Number) \
                        and type(output) != type('a'):
                    raise exc.exception_response(406)

        else:
            raise exc.exception_response(406)

    return output
def update_post(dom, request):
    post_id = dom.find('Body/UpdatePost/id').text

    post = MemoryDb.get_post(post_id, get_ip(request))
    if not post:
        raise exception_response(404)

    if MemoryDb.is_post_read_only(post_id):
        raise exception_response(403)

    post.title = dom.find('Body/UpdatePost/title').text
    post.content = dom.find('Body/UpdatePost/content').text
    post.view_count = int(dom.find('Body/UpdatePost/viewCount').text)

    resp_xml = """<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <UpdatePostResponse xmlns="http://tempuri.org/">
      <UpdatePostResult>
        <Id>{}</Id>
        <Title>{}</Title>
        <Published>{}</Published>
        <Content>{}</Content>
        <ViewCount>{}</ViewCount>
      </UpdatePostResult>
    </UpdatePostResponse>
  </soap:Body>
</soap:Envelope>""".format(post.id, post.title, post.published, post.content, post.view_count)

    return Response(body=resp_xml, content_type='text/xml')
Esempio n. 7
0
    def oauth2token(self) -> pyramid.response.Response:
        LOG.debug(
            "Call OAuth create_token_response with:\nurl: %s\nmethod: %s\nbody:\n%s",
            self.request.current_route_url(_query=self.request.GET),
            self.request.method,
            self.request.body,
        )
        headers, body, status = oauth2.get_oauth_client(
            self.request.registry.settings).create_token_response(
                self.request.current_route_url(_query=self.request.GET),
                self.request.method,
                self.request.body,
                self.request.headers,
                {},
            )
        LOG.debug("OAuth create_token_response return status: %s", status)

        if hasattr(self.request, "tm"):
            self.request.tm.commit()

        # All requests to /token will return a json response, no redirection.
        if status != 200:
            if body:
                raise exception_response(status, detail=body)
            raise exception_response(status)
        return set_common_headers(
            self.request,
            "login",
            Cache.PRIVATE_NO,
            response=Response(body, headers=headers.items()),
        )
Esempio n. 8
0
 def view(self, id=None):
     id = self.request.matchdict["id"]
     if id is None:
         raise exc.exception_response(400)
     data = model.meta.DBSession.query(tables.LigandHetnam)
     self.request.tmpl_context.record = data.get(int(id))
     if self.request.tmpl_context.record is None:
         raise exc.exception_response(400)
     return {}
Esempio n. 9
0
    def create_user(self):
        """Create new user

        This view creates a new user based on the following request params:
        * email :
            The email of the new user to be created
        * referral : optional
            A referral token created by another user
        """

        email = self.request.params.get('email')
        if not re.search(self.EMAIL_REGEX, email):
            return exception_response(400, explanation='Invalid email address')

        referral = self.request.params.get('referral')
        if referral:
            try:
                UUID(referral, version=4)
            except ValueError:
                return exception_response(400, explanation='Invalid referral')

            new_user = User(email=email,
                            referral=referral,
                            balance=self.SIGNUP_REWARD)
        else:
            new_user = User(email=email)

        try:
            db = self.request.dbsession
            db.add(new_user)

            if referral:
                referral_obj = db.query(Referral).filter_by(
                    id=referral).first()
                referral_obj.num_referrals += 1

                referring_user = db.query(User).filter_by(
                    id=referral_obj.user_id).first()
                referring_user.total_referrals += 1
                if referring_user.referral:
                    referral_bonus = self.SIGNUP_REWARD
                else:
                    referral_bonus = 0
                referring_user.balance = \
                    referring_user.total_referrals // self.NUM_REFERRALS_PER_REWARD * self.REWARD_PER_REFERRAL + referral_bonus

            db.flush()
            db.refresh(new_user)

        except IntegrityError as integrity_error:
            explanation = integrity_error.args[0].split('DETAIL: ')[1]
            return exception_response(400, explanation=explanation)
        except DBAPIError as db_error:
            return exception_response(500)
        return {'id': new_user.id}
Esempio n. 10
0
def thumbnail(request):
    try:
        document = get_request_document(request)
        params = get_preview_generator_params(request, document)
        return FileResponse(document.get_jpeg_preview(params), content_type='image/jpeg')
    except DocumentTooBig:
        raise exception_response(509)
    except DocumentNotPreviewable:
        raise exception_response(403)
    except DocumentUnauthorized:
        raise exception_response(401)
Esempio n. 11
0
 def update(self):
     collection = self.context.__parent__
     try:
         values = self._update_values_from_request()
     except NotImplementedError: # pragma: no cover
         raise exception_response(501)
     except InvalidResource, ex:
         raise exception_response(
             400,
             body=unicode(ex)
         )
Esempio n. 12
0
def validation_context(request, response=None):
    try:
        yield
    except (
            exceptions.RequestValidationError,
            exceptions.ResponseValidationError,
            exceptions.PathNotFoundError,
    ):
        raise exception_response(206)
    except Exception:
        raise exception_response(400)
Esempio n. 13
0
def validation_context(request, response=None):
    try:
        yield
    except (
        exceptions.RequestValidationError,
        exceptions.ResponseValidationError,
        exceptions.PathNotFoundError,
    ):
        raise exception_response(206)
    except Exception:
        raise exception_response(400)
def request_params(request):
    try:
        params = NestedMultiDict(request.GET, request.POST)
    except UnicodeDecodeError:
        response = exception_response(422)
        response.body = dumps(error_handler(request, response.code, {"location": "body", "name": "data", "description": "could not decode params"}))
        response.content_type = 'application/json'
        raise response
    except Exception, e:
        response = exception_response(422)
        response.body = dumps(error_handler(request, response.code, {"location": "body", "name": str(e.__class__.__name__), "description": str(e)}))
        response.content_type = 'application/json'
        raise response
Esempio n. 15
0
def divide(request):
    """ Divides the parameter operands and returns the result
		If second operand is zero, raise 400 error"""
    a = request.params['operand1']
    b = request.params['operand2']
    # if one of the operand is missing raise 400 error
    if (not (a) or not (b)):
        raise exception_response(
            400,
            explanation=
            "Operand1 and operand2 are required to perform operation")
    if (float(b) == 0):
        raise exception_response(
            400, explanation="Division by zero is not possible")
    return {"result": Calculator.divide(a, b)}
Esempio n. 16
0
def login(request):
    user_payload = request.json
    user = User.query.filter_by(username=user_payload["username"]).one_or_none()
    if not user:
        return exception_response(404, detail="Usuario nao encontrado")

    if not user.verify_password(user_payload["password"]):
        return exception_response(404, detail="Password invalido")

    claims = {"username": user.username, "email": user.email}
    policy = request.registry.queryUtility(IAuthenticationPolicy)
    token = policy.encode_jwt(request, claims=claims)
    token = token.decode(encoding='UTF-8')

    return {"token": token}
Esempio n. 17
0
    def first_or_404(self):

        obj = self.first()
        if obj is None:
            raise exception_response(404)

        return obj
Esempio n. 18
0
    def first_or_404(self):

        obj = self.first()
        if obj is None:
            raise exception_response(404)

        return obj
Esempio n. 19
0
def quote1(request):
    save_session(request)
    try:
        quote_number = int(request.matchdict['quote_number'])
        return {'quotes': Quote.get_quotes(quote_number=quote_number)}
    except ValueError as e:
        raise exc.exception_response(404)
Esempio n. 20
0
 def get_task(self):
     try:
         run = self.request.rundb.get_run(self.request.matchdict["id"])
         task_id = self.request.matchdict["task_id"]
         if task_id.endswith("bad"):
             task_id = int(task_id[:-3])
             task = copy.deepcopy(run["bad_tasks"][task_id])
         else:
             task_id = int(task_id)
             task = copy.deepcopy(run["tasks"][task_id])
     except:
         raise exception_response(404)
     if "worker_info" in task:
         worker_info = task["worker_info"]
         # Do not reveal the unique_key.
         if "unique_key" in worker_info:
             unique_key = worker_info["unique_key"]
             worker_info["unique_key"] = unique_key[0:8] + "..."
         # Do not reveal remote_addr.
         if "remote_addr" in worker_info:
             worker_info["remote_addr"] = "?.?.?.?"
     if "last_updated" in task:
         # json does not know about datetime
         task["last_updated"] = str(task["last_updated"])
     if "residual" in task:
         # json does not know about infinity
         if task["residual"] == float("inf"):
             task["residual"] = "inf"
     return task
Esempio n. 21
0
File: api.py Progetto: ercchy/h
 def _invoke_subrequest(self, subreq):
     request = self.request
     subreq.session = request.session
     result = request.invoke_subrequest(subreq)
     if result.status_int > 400:
         raise exception_response(result.status_int)
     return result
Esempio n. 22
0
 def __call__(self):
     new_user = IUser(self.request)
     checks = component.subscribers((new_user,), IRedundancyCheck)
     if any([check.check(new_user, self.request) for check in checks]) or\
        not self.context.insert(new_user, check_member=True):
         return exception_response(409)
     return HTTPCreated()
Esempio n. 23
0
def download_pgn(request):
    pgn = request.rundb.get_pgn(request.matchdict['id'])
    if pgn == None:
        raise exc.exception_response(404)
    if '.pgn' in request.matchdict['id']:
        request.response.content_type = 'application/x-chess-pgn'
    return pgn
Esempio n. 24
0
def login(request: Request) -> Response:
    """User logs in using GitHub."""
    response = Response()
    result = request.authomatic.login(WebObAdapter(request, response), "github")
    if result is None:
        return response
    if result.error:
        return exception_response(401, json_body={"error": result.error.message})

    result.user.update()
    username = result.user.username
    user = User.by_username(username, db=request.db)
    if user is None:
        return exception_response(401, json_body={"error": "Not authorized."})

    return Response(json_body={"token": request.create_jwt_token(str(user.id))})
Esempio n. 25
0
def main_table(request):
    """
    View configuration for the content view. Only logged in user can reach this page.

    :param request: current webservers request
    :return: dictionary with title and project name as well as a value, weather the user is logged in
    """
    LOG.debug("Entering the main_table method from the admin interface.")

    ui_locales = get_language_from_cookie(request)
    extras_dict = DictionaryHelper(
        ui_locales).prepare_extras_dict_for_normal_page(
            request.registry, request.application_url, request.path,
            request.validated['user'])
    table_name = request.matchdict['table']
    if not table_name.lower() in lib.table_mapper:
        return exception_response(400)
    table_dict = lib.get_table_dict(table_name, request.application_url)

    return {
        'language': str(ui_locales),
        'title': 'Admin - ' + table_name,
        'project': project_name,
        'extras': extras_dict,
        'table': table_dict,
        'discussion': {
            'broke_limit': False
        }
    }
Esempio n. 26
0
def test_openapi_view_validate_HTTPExceptions():
    """Test that raised HTTPExceptions are validated against the spec.

    I.e. create a dummy view that raises 403 Forbidden. The openapi integration
    should re-raise it as InvalidResponse because 403 is not on the list of
    responses in MINIMAL_DOCUMENT.
    """
    with testConfig() as config:
        config.include("pyramid_openapi3")

        with tempfile.NamedTemporaryFile() as document:
            document.write(MINIMAL_DOCUMENT)
            document.seek(0)

            config.pyramid_openapi3_spec(
                document.name, route="/foo.yaml", route_name="foo_api_spec"
            )

        config.add_route("foo", "/foo")
        view = lambda *arg: (_ for _ in ()).throw(  # noqa: E731
            exception_response(403, json_body="Forbidden")
        )
        config.add_view(openapi=True, renderer="json", view=view, route_name="foo")

        request_interface = config.registry.queryUtility(IRouteRequest, name="foo")
        view = config.registry.adapters.registered(
            (IViewClassifier, request_interface, Interface), IView, name=""
        )
        request = DummyRequest(config=config)
        request.matched_route = DummyRoute(name="foo", pattern="/foo")

        with pytest.raises(InvalidResponse) as exc:
            view(request=request, context=None)

        assert str(exc.value) == "Unknown response http status: 403"
Esempio n. 27
0
 def post(self):
     headers, body, status = self.oauth.create_revocation_response(
         self.request.url, self.request.method, self.request.POST, self.request.headers)
     if status == 200:
         return {}
     else:
         raise exception_response(status, body=body)
Esempio n. 28
0
def restore(request):
    """Restore a Post_History entry as the current version."""
    session = DBSession()
    context = get_context(request)
    uid = context['user'].uid

    id = request.matchdict['id']
    page = request.matchdict['page']
    version = request.matchdickt['version']

    try:
        entry = session.query(Post_History)\
                       .filter(Post_History.id == id)\
                       .filter(Post_History.page == page)\
                       .order_by(expression.desc(Post_History.changed_on))\
                       .limit(1)\
                       .offset(version)\
                       .one()
    except sqlalchemy.orm.exc.NoResultFound:
        return exception_response(404)

    current = session.query(Post).get(id)
    additions = entry.restore(context['user'], current)
    session.addall(additions)

    context['msg'].append('Post restored succesfully.')
    msgs = [('msg', m) for m in context['msg']]
    return HTTPFound(location=request.route_url('post', id=entry.id, page=page,
                                                _query=msgs))
Esempio n. 29
0
def download_pgn(request):
  pgn = request.rundb.get_pgn(request.matchdict['id'])
  if pgn == None:
    raise exc.exception_response(404)
  if '.pgn' in request.matchdict['id']:
    request.response.content_type = 'application/x-chess-pgn'
  return pgn
Esempio n. 30
0
File: api_auth.py Progetto: eiro10/h
 def post(self):
     headers, body, status = self.oauth.create_revocation_response(
         self.request.url, self.request.method, self.request.POST, self.request.headers)
     if status == 200:
         return {}
     else:
         raise exception_response(status, body=body)
Esempio n. 31
0
 def error_handler(self, exc, request):
     req = request.cw_request
     if isinstance(exc, httpexceptions.HTTPException):
         request.response = exc
     elif isinstance(exc, PublishException) and exc.status is not None:
         request.response = httpexceptions.exception_response(exc.status)
     else:
         request.response = httpexceptions.HTTPInternalServerError()
     request.response.cache_control = 'no-cache'
     vreg = request.registry['cubicweb.registry']
     excinfo = sys.exc_info()
     req.reset_message()
     if req.ajax_request:
         content = self.appli.ajax_error_handler(req, exc)
     else:
         try:
             req.data['ex'] = exc
             req.data['excinfo'] = excinfo
             errview = vreg['views'].select('error', req)
             template = self.appli.main_template_id(req)
             content = vreg['views'].main_template(req,
                                                   template,
                                                   view=errview)
         except Exception:
             content = vreg['views'].main_template(req, 'error-template')
     log.exception(exc)
     request.response.body = content
     return request.response
Esempio n. 32
0
File: auth.py Progetto: toirl/ringo
def reset_password(request):
    settings = request.registry.settings
    if not is_pwreminder_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    success = False
    token = request.matchdict.get('token')
    user, password = password_reset(token, request.db)
    if password:
        mailer = Mailer(request)
        recipient = user.profile[0].email
        subject = _('Password has been reseted')
        values = {'password': password,
                  'app_name': get_app_title(),
                  'email': settings['mail.default_sender'],
                  '_': _}
        mail = Mail([recipient],
                    subject,
                    template="password_reminder",
                    values=values)
        mailer.send(mail)
        msg = _("Password was resetted and sent to the users email address."
                " Please check your email.")
        success = True
    else:
        msg = _("Password was not resetted. Maybe the request"
                " token was not valid?")
    return {'msg': msg, 'success': success}
Esempio n. 33
0
def forgot_password(request):
    settings = request.registry.settings
    if not is_pwreminder_enabled(settings):
        raise exc.exception_response(503)
    handle_history(request)
    _ = request.translate
    config = Config(load(get_path_to_form_config('auth.xml')))
    form_config = config.get_form('forgot_password')
    form = Form(form_config, csrf_token=request.session.get_csrf_token(),
                translate=_)
    complete = False
    if request.POST:
        if form.validate(request.params):
            username = form.data.get('login')
            user = request_password_reset(username, request.db)
            if user:
                mailer = Mailer(request)
                recipient = user.profile[0].email
                token = user.reset_tokens[-1]
                subject = _('Password reset request')
                values = {'url': request.route_url('reset_password',
                                                   token=token),
                          'app_name': get_app_title(),
                          'email': settings['mail.default_sender'],
                          '_': _}
                mail = Mail([recipient],
                            subject,
                            template="password_reset_request",
                            values=values)
                mailer.send(mail)
            msg = _("Password reset token has been sent to the users "
                    "email address. Please check your email.")
            request.session.flash(msg, 'success')
            complete = True
    return {'form': form.render(), 'complete': complete}
Esempio n. 34
0
def reset_password(request):
    settings = request.registry.settings
    if not is_pwreminder_enabled(settings):
        raise exc.exception_response(503)
    _ = request.translate
    success = False
    token = request.matchdict.get('token')
    user, password = password_reset(token, request.db)
    if password:
        mailer = Mailer(request)
        recipient = user.profile[0].email
        subject = _('Password has been reseted')
        values = {
            'password': password,
            'app_name': get_app_title(),
            'email': settings['mail.default_sender'],
            '_': _
        }
        mail = Mail([recipient],
                    subject,
                    template="password_reminder",
                    values=values)
        mailer.send(mail)
        msg = _("Password was resetted and sent to the users email address."
                " Please check your email.")
        success = True
    else:
        msg = _("Password was not resetted. Maybe the request"
                " token was not valid?")
    return {'msg': msg, 'success': success}
Esempio n. 35
0
def openapi_validation_error(context: t.Union[RequestValidationError,
                                              ResponseValidationError],
                             request: Request) -> Response:
    """Render any validation errors as JSON."""
    if isinstance(context, RequestValidationError):
        logger.warning(context)
    if isinstance(context, ResponseValidationError):
        logger.error(context)

    extract_errors = request.registry.settings[
        "pyramid_openapi3_extract_errors"]
    errors = list(extract_errors(request, context.errors))

    # If validation failed for request, it is user's fault (-> 400), but if
    # validation failed for response, it is our fault (-> 500)
    if isinstance(context, RequestValidationError):
        status_code = 400
        for error in context.errors:
            if isinstance(error, InvalidSecurity):
                status_code = 401

    if isinstance(context, ResponseValidationError):
        status_code = 500

    return exception_response(status_code, json_body=errors)
Esempio n. 36
0
 def _invoke_subrequest(self, subreq):
     request = self.request
     subreq.session = request.session
     result = request.invoke_subrequest(subreq)
     if result.status_int > 400:
         raise exception_response(result.status_int)
     return result
Esempio n. 37
0
 def download_pgn(self):
     pgn = self.request.rundb.get_pgn(self.request.matchdict["id"])
     if pgn is None:
         raise exception_response(404)
     if ".pgn" in self.request.matchdict["id"]:
         self.request.response.content_type = "application/x-chess-pgn"
     return pgn
Esempio n. 38
0
def notfound(request: Request) -> HTTPNotFound:
    """Catch url traversal and db lookup errors and respond with a nice JSON error.

    Without this, not-found errors that get to WSGI level return HTML that says
    404 Not Found.
    """
    return exception_response(404, json_body={"errors": {"body": ["Not Found"]}})
Esempio n. 39
0
def unauthorized(request: Request) -> HTTPUnauthorized:
    """Catch permission errors and respond with a nice JSON error.

    Without this, permission errors that get to WSGI level return HTML that says
    403 Forbidden.
    """
    return exception_response(401, json_body={"errors": {"body": ["Unauthorized"]}})
Esempio n. 40
0
    def error(self, code, message='', **kwargs):
        from pyramid.httpexceptions import exception_response

        raise exception_response(code, detail=message, headers={
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET',
        })
Esempio n. 41
0
    def get_giria(self):
        """Return `giria` instance specific, by `state` and `giria` argument"""
        state = State.objects(code=self.state).first()
        giria = Giria.objects(state=state, giria=self.giria).first()

        if giria:
            return giria
        return exception_response(404)
Esempio n. 42
0
def _tus_resumable_header(request):
    tr = request.headers.get('Tus-Resumable')
    if tr is None:
        return False
    elif tr == "1.0.0":
        return True
    else:
        raise exc.exception_response(412)
Esempio n. 43
0
 def handle_error(self, error):
     """Handles errors during parsing. Aborts the current HTTP request and
     responds with a 400 error.
     """
     logger.error(error)
     status_code = getattr(error, 'status_code', 400)
     data = getattr(error, 'data', {})
     raise exception_response(status_code, detail=text_type(error), **data)
Esempio n. 44
0
 def create(self):
     try:
         values = self._create_values_from_request()
     except InvalidResource, ex:
         raise exception_response(
             400,
             body=unicode(ex),
         )
Esempio n. 45
0
    def get_one(cls, id_=None, query=None):
        if id_ is not None:
            query = cls.query.get(int(id_))

        if query == None:
            raise exception_response(404)
        else:
            return query
Esempio n. 46
0
def abort(request, code, body):
    # if no Accept header is set, then force */*, otherwise the exception
    # will be returned as text/plain, which causes easy_install/setuptools
    # to fail improperly
    request.headers.setdefault("Accept", "*/*")
    if "application/json" in request.headers.get("Accept", ""):
        apireturn(code, body)
    threadlog.error(body)
    raise exception_response(code, explanation=body, headers=meta_headers)
Esempio n. 47
0
def view_calculation(request):
    """

    View for looking up calculations.

    """

    # Get the key
    matches = request.matchdict
    hashkey = matches['one']

    # Look up the key
    calculation = request.dbsession.query(models.Calculation) \
        .filter_by(hashkey=hashkey).first()

    if calculation is None:
        raise httpexceptions.exception_response(404)

    # Get from database
    # workpath = 'molcalc/data/'+hashkey + '/'

    # Check if calculation exists
    # if not os.path.exists(workpath):
    #     raise httpexceptions.exception_response(404)

    data = {}

    # with open(workpath + "start.sdf", 'r') as sdffile:
    #     sdfstr = sdffile.read()
    #     data['sdf'] = sdfstr
    #
    # molobj, status = cheminfo.sdfstr_to_molobj(sdfstr)
    # smiles = cheminfo.molobj_to_smiles(molobj)

    data["hashkey"] = calculation.hashkey
    data["smiles"] = calculation.smiles
    data["sdf"] = calculation.sdf
    data["svg"] = calculation.svg
    data["name"] = ""

    if hashkey == "404":
        raise httpexceptions.exception_response(404)

    return data
Esempio n. 48
0
def publish(context, request):
    topic_mode = request.POST.get('hub.mode', '')
    topic_urls = request.POST.getall('hub.url')

    bad_data = False
    error_msg = None

    if not topic_mode or topic_mode != 'publish':
        bad_data = True
        error_msg = "Invalid or unspecified mode."

    if not topic_urls:
        bad_data = True
        error_msg = "No topic URLs provided"

    hub = request.root

    for topic_url in topic_urls:
        try:
            hub.publish(topic_url)
        except ValueError:
            bad_data = True
            error_msg = "Malformed URL: %s" % topic_url

    if not bad_data:
        topics = [
            topic
            for (url, topic) in hub.topics.items()
            if url in topic_urls
        ]
        # XXX: Currently this is needed to ensure the listener gets
        #      the latest data.
        hub.fetch_content(topic_urls, request.application_url)
        hub.notify_listeners(topics)
        hub.fetch_all_content(request.application_url)

    if bad_data and error_msg:
        return exception_response(400,
                                  body=error_msg,
                                  headers=[('Content-Type', 'text/plain')])

    hub.notify_subscribers()

    return exception_response(204)
Esempio n. 49
0
    def wrapper(*args, **kwargs):
        # We could be called with (context, request) or just (request,)
        request = args[0]
        if len(args) > 1:
            request = args[1]
        if request.method != "POST":
            response = exception_response(405)
            response.headers.extend([('Allow', 'POST')])
            return response

        content_type = request.headers.get('Content-Type', None)
        if (content_type != "application/x-www-form-urlencoded"):
            response = exception_response(406)
            response.headers.extend(
                [('Accept', 'application/x-www-form-urlencoded')]
            )
            return response

        return fn(*args, **kwargs)
Esempio n. 50
0
    def _invoke_subrequest(self, subreq):
        request = self.request
        token = api.token.TokenController(request)()
        subreq.headers['X-Annotator-Auth-Token'] = token
        result = request.invoke_subrequest(subreq)

        if result.status_int > 400:
            raise exception_response(result.status_int)

        return result
Esempio n. 51
0
def listen(context, request):
    listener_url = request.POST.get('listener.callback', '')
    error_msg = ''

    if not listener_url:
        error_msg = "Malformed URL: %s" % listener_url

    hub = request.root

    try:
        hub.register_listener(listener_url)
    except ValueError as e:
        error_msg = str(e)

    if error_msg:
        return exception_response(400,
                                  body=error_msg,
                                  headers=[('Content-Type', 'text/plain')])
    return exception_response(200)
Esempio n. 52
0
File: store.py Progetto: mrienstra/h
    def _invoke_subrequest(self, subreq):
        request = self.request
        # XXX: This should be available more easily somewhere, like the session.
        token = api.token.TokenController(request)()
        subreq.headers['X-Annotator-Auth-Token'] = token
        result = request.invoke_subrequest(subreq)

        if result.status_int > 400:
            raise exception_response(result.status_int)

        return result
Esempio n. 53
0
 def handle_exception(request):
     try:
         return func(request)
     except exception as e:
         if not isinstance(e, HTTPException):
             raise exception_response(
                 status_code,
                 detail=error_message or repr(e)
             )
         else:
             raise e
Esempio n. 54
0
def oid_authentication_callback(context, request, success_dict):
    """\
    success_dict = {
        'identity_url': info.identity_url,
        'ax': {},
        'sreg': {}
    }
    """
    LOG.debug("looking for user")
    user = find_user('open_id', success_dict['identity_url'])
    if user:
        LOG.info("found user")
        # use standard auth callback to populate session
        #authentication_callback(user.id, request)
        remember(request, user.id)
        LOG.debug("redirecting to %s", request.route_url('admin'))
        return exception_response(302, location=request.route_url('admin'))
    else:
        LOG.debug("invalid login")
        error_response = "This login is not authorized.\nEmail this to [email protected]: '%s'" % success_dict['identity_url']
        return exception_response(401, body=error_response)
def get_validation_session(session_code):
    """Return validation session by its code.

    :param session_code: validation session uuid
    :type session_code: string
    """
    query = DBSession.query(ValidationSessionModel).filter(
        ValidationSessionModel.code == session_code
    )
    if query.count() != 1:
        raise exception_response(404)
    return query.first()
Esempio n. 56
0
def settings_save(request):
    module = request.matchdict.get('module')
    Session = sqlahelper.get_session()
    setting = Session.query(Setting).get(module)
    for k, v in request.POST.items():
        if k == 'save':
            continue
        setting.config[k] = v
    Session.merge(setting)
    Session.commit()
    raise exception_response(
        302,
        location=request.route_url('settings')
    )
Esempio n. 57
0
def bazarek(request):
    user = User.get(request.matchdict.get('id', 0))
    sef = request.matchdict.get('sef', 'secret_sef')
    user_sef = make_sef_url(user and user.user_name() or 'secret_user_name')

    if not user or sef != user_sef:
        return exception_response(404)

    return {
        'products': chunk(user.get_all_products(), request),
        'title': "Bazarek: %s" % (user.user_name()),
        'main': True,
        'user': user
    }
Esempio n. 58
0
def page_view(request):
    Session = sqlahelper.get_session()
    try:
        page = Session.query(Page).\
            filter(Page.slug == request.matchdict.get('page')).\
            filter(Page.visible == True).\
            one()
    except SQLAlchemyError:
        Session.rollback()
        raise exception_response(404)
    else:
        return render_to_response(
            'columns:templates/blog/page.jinja', 
            {'page': page}
        )
Esempio n. 59
0
def imageupload(request):
    upload_file = request.POST['file']
    values = {
        'title': upload_file.filename,
        'content': '',
        'tags': set([]),
        'file': upload_file
    }
    upload = Upload()
    try:
        upload = upload.build_from_values(values, request=request)
    except OSError: # pragma: no cover
        raise exception_response(500)
    else:
        return {'filelink': '/'.join([request.registry.settings.get('upload_baseurl'), upload.filepath])}