Ejemplo n.º 1
0
Archivo: util.py Proyecto: DINKIN/tg2
def validation_errors_response(*args, **kwargs):
    """Returns a :class:`.Response` object with validation errors.

    The response will be created with a *412 Precondition Failed*
    status code and errors are reported in JSON format as response body.

    Typical usage is as ``error_handler`` for JSON based api::

        @expose('json')
        @validate({'display_name': validators.NotEmpty(),
                   'group_name': validators.NotEmpty()},
                  error_handler=validation_errors_response)
        def post(self, **params):
            group = Group(**params)
            return dict(group=group)

    """
    req = request._current_obj()
    errors = dict(((str(key), str(error)) for key, error in req.validation.errors.items()))
    values = req.validation['values']
    try:
        return Response(status=412, json_body={'errors': errors,
                                               'values': values})
    except TypeError:
        # values cannot be encoded to JSON, this might happen after
        # validation passed and validators converted them to complex objects.
        # In this case use request params, instead of controller params.
        return Response(status=412, json_body={'errors': errors,
                                               'values': req.args_params})
Ejemplo n.º 2
0
def validation_errors_response(*args, **kwargs):
    """Returns a :class:`.Response` object with validation errors.

    The response will be created with a *412 Precondition Failed*
    status code and errors are reported in JSON format as response body.

    Typical usage is as ``error_handler`` for JSON based api::

        @expose('json')
        @validate({'display_name': validators.NotEmpty(),
                   'group_name': validators.NotEmpty()},
                  error_handler=validation_errors_response)
        def post(self, **params):
            group = Group(**params)
            return dict(group=group)

    """
    req = request._current_obj()
    errors = dict(((str(key), str(error)) for key, error in req.validation.errors.items()))
    values = req.validation['values']
    try:
        return Response(status=412, json_body={'errors': errors,
                                               'values': values})
    except TypeError:
        # values cannot be encoded to JSON, this might happen after
        # validation passed and validators converted them to complex objects.
        # In this case use request params, instead of controller params.
        return Response(status=412, json_body={'errors': errors,
                                               'values': req.args_params})
Ejemplo n.º 3
0
def auth_force_logout():
    """Forces user logout if authentication is enabled."""
    req = request._current_obj()
    resp = response._current_obj()

    api = req.environ.get('repoze.who.api')
    if api:
        resp.headers.extend(api.forget())
Ejemplo n.º 4
0
Archivo: util.py Proyecto: DINKIN/tg2
def auth_force_logout():
    """Forces user logout if authentication is enabled."""
    req = request._current_obj()
    resp = response._current_obj()

    api = req.environ.get('repoze.who.api')
    if api:
        resp.headers.extend(api.forget())
Ejemplo n.º 5
0
Archivo: utils.py Proyecto: todun/ksweb
def ksweb_error_handler(*args, **kw):  # pragma: nocover
    from tg import flash, redirect
    from tg._compat import unicode_text
    from tg.request_local import request
    from tg.i18n import lazy_ugettext as l_
    _request = request._current_obj()
    errors = dict((unicode_text(key), unicode_text(error))
                  for key, error in _request.validation.errors.items())
    flash(l_('Errors: %s' % errors), 'error')
    redirect('/start')
Ejemplo n.º 6
0
    def pop_payload(self):
        """Fetch current flash message, status and related information.

        Fetching flash message deletes the associated cookie.
        """
        # First try fetching it from the request
        req = request._current_obj()
        payload = req.environ.get('webflash.payload', {})
        if not payload:
            payload = req.cookies.get(self.cookie_name, {})

        if payload:
            payload = json.loads(url_unquote(payload))
            if 'webflash.deleted_cookie' not in req.environ:
                response.delete_cookie(self.cookie_name)
                req.environ['webflash.delete_cookie'] = True
        return payload or {}
Ejemplo n.º 7
0
Archivo: flash.py Proyecto: moreati/tg2
    def pop_payload(self):
        """Fetch current flash message, status and related information.

        Fetching flash message deletes the associated cookie.
        """
        # First try fetching it from the request
        req = request._current_obj()
        payload = req.environ.get("webflash.payload", {})
        if not payload:
            payload = req.cookies.get(self.cookie_name, {})

        if payload:
            payload = json.loads(url_unquote(payload))
            if "webflash.deleted_cookie" not in req.environ:
                response.delete_cookie(self.cookie_name)
                req.environ["webflash.delete_cookie"] = True
        return payload or {}
Ejemplo n.º 8
0
def auth_force_login(user_name):
    """Forces user login if authentication is enabled.

    As TurboGears identifies users by ``user_name`` the passed parameter should
    be anything your application declares being the ``user_name`` field in models.

    """
    req = request._current_obj()
    resp = response._current_obj()

    api = req.environ.get("repoze.who.api")
    if api:
        authentication_plugins = req.environ["repoze.who.plugins"]
        try:
            identifier = authentication_plugins["main_identifier"]
        except KeyError:
            raise TGConfigError('No repoze.who plugin registered as "main_identifier"')

        resp.headers.extend(api.remember({"repoze.who.userid": user_name, "identifier": identifier}))
Ejemplo n.º 9
0
def auth_force_login(user_name):
    """Forces user login if authentication is enabled.

    As TurboGears identifies users by ``user_name`` the passed parameter should
    be anything your application declares being the ``user_name`` field in models.

    """
    req = request._current_obj()
    resp = response._current_obj()

    api = req.environ.get('repoze.who.api')
    if api:
        authentication_plugins = req.environ['repoze.who.plugins']
        try:
            identifier = authentication_plugins['main_identifier']
        except KeyError:
            raise TGConfigError('No repoze.who plugin registered as "main_identifier"')

        resp.headers.extend(api.remember({
            'repoze.who.userid': user_name,
            'identifier': identifier
        }))