Ejemplo n.º 1
0
 def __call__(self, value, context):
     super(RestrictedString, self).__call__(value, context)
     if self.ui_name:
         ui_name = self.ui_name
     else:
         ui_name = context
     if self.minlength is not None \
             and len(value) < self.minlength:
         raise OperationFailure(
             code="paramtooshort:%s" % context,
             title="Invalid %s" % ui_name,
             message=(
                 "invalid input: %s must be at least %d characters long" %
                 (ui_name, self.minlength)))
     if self.maxlength is not None \
             and len(value) > self.maxlength:
         raise OperationFailure(
             code="paramtoolong:%s" % context,
             title="Invalid %s" % ui_name,
             message=(
                 "invalid input: %s must be at most %d characters long" %
                 (ui_name, self.maxlength)))
     if self.allowed:
         disallowed = [
             ch for ch in sorted(set(value)) if not self.allowed(ch)
         ]
         if disallowed:
             raise OperationFailure(
                 code="paramcontainsillegalchar:%s" % context,
                 title="Invalid %s" % ui_name,
                 message=(
                     "invalid input: %s may not contain the character%s %s"
                     % (ui_name, "s" if len(disallowed) > 1 else "",
                        ", ".join(repr(ch) for ch in disallowed))))
Ejemplo n.º 2
0
 def requireRole(db, role, user):
     if not user.hasRole(db, role):
         raise OperationFailure(
             code="notallowed",
             title="Not allowed!",
             message="Operation not permitted, user that lacks role '%s'." %
             role)
Ejemplo n.º 3
0
 def __call__(self, value, context):
     super(RestrictedInteger, self).__call__(value, context)
     if self.ui_name:
         ui_name = self.ui_name
     else:
         ui_name = context
     if self.minvalue is not None \
             and value < self.minvalue:
         raise OperationFailure(
             code="valuetoolow:%s" % context,
             title="Invalid %s parameter" % ui_name,
             message=("invalid input: %s must be %d or higher" %
                      (ui_name, self.minvalue)))
     if self.maxvalue is not None \
             and value > self.maxvalue:
         raise OperationFailure(
             code="valuetoohigh:%s" % context,
             title="Invalid %s parameter" % ui_name,
             message=("invalid input: %s must be %d or lower" %
                      (ui_name, self.maxvalue)))
Ejemplo n.º 4
0
def basic():
    from operation.basictypes import (OperationResult, OperationError,
                                      OperationFailure,
                                      OperationFailureMustLogin)

    def convert(value):
        return json.loads(str(value))

    #
    # OperationResult
    #

    # OperationResult has status=ok by default.
    assert convert(OperationResult()) == {"status": "ok"}

    # But status can be overridden.
    assert convert(OperationResult(status="bananas")) == {"status": "bananas"}

    # Other values can be set as well.
    assert convert(OperationResult(foo=10)) == {"status": "ok", "foo": 10}

    # Even to None/null.
    assert convert(OperationResult(foo=None)) == {"status": "ok", "foo": None}

    # And test OperationResult.set().
    result = OperationResult()
    result.set("foo", 10)
    assert convert(result) == {"status": "ok", "foo": 10}
    result.set("foo", [1, 2, 3])
    assert convert(result) == {"status": "ok", "foo": [1, 2, 3]}
    result.set("foo", None)
    assert convert(result) == {"status": "ok", "foo": None}

    #
    # OperationError
    #

    assert convert(OperationError("wrong!")) == {
        "status": "error",
        "error": "wrong!"
    }

    #
    # OperationFailure
    #

    assert (convert(OperationFailure("the code", "the title",
                                     "the message")) == {
                                         "status": "failure",
                                         "code": "the code",
                                         "title": "the title",
                                         "message": "the message"
                                     })

    # Check HTML escaping.
    assert (convert(OperationFailure("<code>", "<title>", "<message>")) == {
        "status": "failure",
        "code": "<code>",
        "title": "&lt;title&gt;",
        "message": "&lt;message&gt;"
    })

    # Check HTML escaping with is_html=True (title still escaped, but not the
    # message.)
    assert (convert(OperationFailure("<code>", "<title>", "<message>",
                                     True)) == {
                                         "status": "failure",
                                         "code": "<code>",
                                         "title": "&lt;title&gt;",
                                         "message": "<message>"
                                     })

    print "basic: ok"
Ejemplo n.º 5
0
    def __call__(self, req, db, user):
        from operation.typechecker import TypeCheckerContext

        if user.isAnonymous() and not self.__accept_anonymous_user:
            return OperationFailureMustLogin()

        if req.method == "POST": data = req.read()
        else: data = req.getParameter("data")

        if not data: raise OperationError("no input")

        try:
            value = json_decode(data)
        except ValueError as error:
            raise OperationError("invalid input: %s" % str(error))

        try:
            self.__checker(value, TypeCheckerContext(req, db, user))
            return self.process(db, user, **value)
        except OperationError as error:
            return error
        except OperationFailure as failure:
            return failure
        except dbutils.NoSuchUser as error:
            return OperationFailure(
                code="nosuchuser",
                title="Who is '%s'?" % error.name,
                message="There is no user in Critic's database named that.")
        except dbutils.NoSuchReview as error:
            return OperationFailure(
                code="nosuchreview",
                title="Invalid review ID",
                message="The review ID r/%d is not valid." % error.id)
        except dbutils.TransactionRollbackError:
            return OperationFailure(
                code="transactionrollback",
                title="Transaction rolled back",
                message=
                "Your database transaction rolled back, probably due to a deadlock.  Please try again."
            )
        except extensions.extension.ExtensionError as error:
            return OperationFailure(code="invalidextension",
                                    title="Invalid extension",
                                    message=error.message)
        except:
            # Decode value again since the type checkers might have modified it.
            value = json_decode(data)

            error_message = ("User: %s\nReferrer: %s\nData: %s\n\n%s" %
                             (user.name, req.getReferrer(),
                              json_encode(self.sanitize(value),
                                          indent=2), traceback.format_exc()))

            db.rollback()

            import mailutils
            import configuration

            if not user.hasRole(db, "developer"):
                mailutils.sendExceptionMessage(db, "wsgi[%s]" % req.path,
                                               error_message)

            if configuration.debug.IS_DEVELOPMENT or user.hasRole(
                    db, "developer"):
                return OperationError(error_message)
            else:
                return OperationError(
                    "An unexpected error occurred.  " +
                    "A message has been sent to the system administrator(s) " +
                    "with details about the problem.")