Beispiel #1
0
def call_api(func, args=""):
    response.headers.replace("Content-type", "application/json")
    response.headers.append("Cache-Control", "no-cache, must-revalidate")

    s = request.environ.get('beaker.session')
    if 'session' in request.POST:
        s = s.get_by_id(request.POST['session'])

    if not s or not s.get("authenticated", False):
        return HTTPError(403, json.dumps("Forbidden"))

    if not PYLOAD.isAuthorized(func, {"role": s['role'], "permission": s['perms']}):
        return HTTPError(401, json.dumps("Unauthorized"))

    args = args.split("/")[1:]
    kwargs = {}

    for x, y in chain(request.GET.iteritems(), request.POST.iteritems()):
        if x == "session":
            continue
        kwargs[x] = unquote(y)

    try:
        return callApi(func, *args, **kwargs)
    except Exception, e:
        traceback.print_exc()
        return HTTPError(500, json.dumps({"error": e.message, "traceback": traceback.format_exc()}))
Beispiel #2
0
def call_api(func, args=""):
    response.headers.replace("Content-type", "application/json")
    response.headers.append("Cache-Control", "no-cache, must-revalidate")

    s = request.environ.get('beaker.session')
    if 'session' in request.POST:
        s = s.get_by_id(request.POST['session'])

    if not s or not s.get("authenticated", False):
        return HTTPError(403, json.dumps("Forbidden"))

    if not PYLOAD.isAuthorized(func, {
            "role": s["role"],
            "permission": s["perms"]
    }):
        return HTTPError(401, json.dumps("Unauthorized"))

    args = args.split("/")[1:]
    kwargs = {}

    for x, y in chain(request.GET.iteritems(), request.POST.iteritems()):
        if x == "session": continue
        kwargs[x] = unquote(y)

    try:
        return callApi(func, *args, **kwargs)
    except Exception, e:
        print_exc()
        return HTTPError(
            500, json.dumps({
                "error": e.message,
                "traceback": format_exc()
            }))
Beispiel #3
0
def callApi(func, *args, **kwargs):
    if not hasattr(PYLOAD.EXTERNAL, func) or func.startswith("_"):
        print "Invalid API call", func
        return HTTPError(404, json.dumps("Not Found"))

    result = getattr(PYLOAD, func)(*[literal_eval(x) for x in args],
                                   **dict((x, literal_eval(y)) for x, y in kwargs.iteritems()))

    # null is invalid json  response
    return json.dumps(result or True, cls=TBaseEncoder)
Beispiel #4
0
def callApi(func, *args, **kwargs):
    if not hasattr(PYLOAD.EXTERNAL, func) or func.startswith("_"):
        print "Invalid API call", func
        return HTTPError(404, json.dumps("Not Found"))

    result = getattr(PYLOAD, func)(*[literal_eval(x) for x in args],
                                   **dict((x, literal_eval(y)) for x, y in kwargs.iteritems()))

    # null is invalid json  response
    return json.dumps(result or True, cls=TBaseEncoder)
Beispiel #5
0
def dumps(*args, **kwargs):
    if 'compact' in kwargs and kwargs['compact']:
        kwargs['cls'] = BaseEncoderCompact
        del kwargs['compact']
    else:
        kwargs['cls'] = BaseEncoder

    kwargs['separators'] = separators
    return json.dumps(*args, **kwargs)
Beispiel #6
0
 def saveAccounts(self):
     """save all account information"""
     data = []
     for plugin, accounts in self.accounts.iteritems():
         data.extend(
             [(acc.loginname, 1 if acc.activated else 0, 1 if acc.shared else 0, acc.password,
               json.dumps(acc.options), acc.aid) for acc in
              accounts])
     self.core.db.saveAccounts(data)
Beispiel #7
0
 def saveAccounts(self):
     """save all account information"""
     data = []
     for plugin, accounts in self.accounts.iteritems():
         data.extend([(acc.loginname, 1 if acc.activated else 0,
                       1 if acc.shared else 0, acc.password,
                       json.dumps(acc.options), acc.aid)
                      for acc in accounts])
     self.core.db.saveAccounts(data)
Beispiel #8
0
def dumps(*args, **kwargs):
    if 'compact' in kwargs and kwargs['compact']:
        kwargs['cls'] = BaseEncoderCompact
        del kwargs['compact']
    else:
        kwargs['cls'] = BaseEncoder

    kwargs['separators'] = separators
    return json.dumps(*args, **kwargs)
Beispiel #9
0
def login():
    response.headers.replace("Content-type", "application/json")
    response.headers.append("Cache-Control", "no-cache, must-revalidate")

    user = request.forms.get("username")
    password = request.forms.get("password")

    info = PYLOAD.checkAuth(user, password)

    if not info:
        return json.dumps(False)

    s = set_session(request, info)

    # get the session id by dirty way, documentations seems wrong
    try:
        sid = s._headers['cookie_out'].split("=")[1].split(";")[0]
        return json.dumps(sid)
    except Exception:
        return json.dumps(True)
Beispiel #10
0
    def saveAccounts(self):
        """save all account information"""
        # TODO: multi user
        # TODO: activated

        data = []
        for name, plugin in self.accounts.iteritems():
            data.extend([(name, acc.loginname, 1 if acc.activated else 0,
                          acc.password, json.dumps(acc.options))
                         for acc in plugin.itervalues()])
        self.core.db.saveAccounts(data)
Beispiel #11
0
def login():
    response.headers.replace("Content-type", "application/json")
    response.headers.append("Cache-Control", "no-cache, must-revalidate")

    user = request.forms.get("username")
    password = request.forms.get("password")

    info = PYLOAD.checkAuth(user, password)

    if not info:
        return json.dumps(False)

    s = set_session(request, info)

    # get the session id by dirty way, documentations seems wrong
    try:
        sid = s._headers["cookie_out"].split("=")[1].split(";")[0]
        return json.dumps(sid)
    except Exception:
        return json.dumps(True)
Beispiel #12
0
    def saveAccounts(self):
        """save all account information"""
        # TODO: multi user
        # TODO: activated

        data = []
        for name, plugin in self.accounts.iteritems():
            data.extend(
                [(name, acc.loginname, 1 if acc.activated else 0, acc.password, json.dumps(acc.options)) for acc in
                 plugin.itervalues()])
        self.core.db.saveAccounts(data)
Beispiel #13
0
 def saveValues(self, user, section):
     if section in self.parser and user is None:
         self.save()
     elif (user, section) in self.values:
         self.db.saveConfig(section, json.dumps(self.values[user, section]),
                            user)
Beispiel #14
0
 def saveValues(self, user, section):
     if section in self.parser and user is None:
         self.save()
     elif (user, section) in self.values:
         self.db.saveConfig(section, json.dumps(self.values[user, section]), user)