Exemplo n.º 1
0
def login():
    add_json_header(response)

    username = request.params.get("username")
    password = request.params.get("password")

    user = PYLOAD.checkAuth(username, password, request.environ.get('REMOTE_ADDR', None))

    if not user:
        return dumps(False)

    s = set_session(request, user)

    # get the session id by dirty way, documentations seems wrong
    try:
        sid = s._headers["cookie_out"].split("=")[1].split(";")[0]
    # reuse old session id
    except:
        sid = request.get_header(session.options['key'])

    result = BaseEncoder().default(user)
    result["session"] = sid

    # Return full user information if needed
    if request.params.get('user', None):
        return dumps(result)

    return dumps(sid)
Exemplo n.º 2
0
def login():
    add_header(response)

    username = request.params.get("username")
    password = request.params.get("password")

    user = PYLOAD.checkAuth(username, password,
                            request.environ.get('REMOTE_ADDR', None))

    if not user:
        return dumps(False)

    s = set_session(request, user)

    # get the session id by dirty way, documentations seems wrong
    try:
        sid = s._headers["cookie_out"].split("=")[1].split(";")[0]
    # reuse old session id
    except:
        sid = request.get_header(session.options['key'])

    result = BaseEncoder().default(user)
    result["session"] = sid

    # Return full user information if needed
    if request.params.get('user', None):
        return dumps(result)

    return dumps(sid)
Exemplo n.º 3
0
def call_api(func, args=""):
    add_header(response)

    s = request.environ.get("beaker.session")
    # Accepts standard http auth
    auth = parse_auth(request.get_header("Authorization", ""))
    if "session" in request.POST or "session" in request.GET:
        # removes "' so it works on json strings
        s = s.get_by_id(remove_chars(request.params.get("session"), "'\""))
    elif auth:
        user = PYLOAD.checkAuth(auth[0], auth[1], request.environ.get("REMOTE_ADDR", None))
        # if auth is correct create a pseudo session
        if user:
            s = {"uid": user.uid}

    api = get_user_api(s)
    if not api:
        return HTTPError(401, dumps("Unauthorized"), **response.headers)

    if not PYLOAD.isAuthorized(func, api.user):
        return HTTPError(403, dumps("Forbidden"), **response.headers)

    if not hasattr(PYLOAD.EXTERNAL, func) or func.startswith("_"):
        print "Invalid API call", func
        return HTTPError(404, dumps("Not Found"), **response.headers)

    # TODO: possible encoding
    # TODO Better error codes on invalid input

    args = [loads(unquote(arg)) for arg in args.split("/")[1:]]
    kwargs = {}

    # accepts body as json dict
    if request.json:
        kwargs = request.json

    # convert arguments from json to obj separately
    for x, y in chain(request.GET.iteritems(), request.POST.iteritems()):
        if not x or not y or x == "session":
            continue
        kwargs[x] = loads(unquote(y))

    try:
        result = getattr(api, func)(*args, **kwargs)
        # null is invalid json response
        if result is None:
            result = True
        return dumps(result)

    except ExceptionObject, e:
        return HTTPError(400, dumps(e), **response.headers)
Exemplo n.º 4
0
def call_api(func, args=""):
    add_header(response)

    s = request.environ.get('beaker.session')
    # Accepts standard http auth
    auth = parse_auth(request.get_header('Authorization', ''))
    if 'session' in request.POST or 'session' in request.GET:
        # removes "' so it works on json strings
        s = s.get_by_id(remove_chars(request.params.get('session'), "'\""))
    elif auth:
        user = PYLOAD.checkAuth(auth[0], auth[1],
                                request.environ.get('REMOTE_ADDR', None))
        # if auth is correct create a pseudo session
        if user: s = {'uid': user.uid}

    api = get_user_api(s)
    if not api:
        return HTTPError(401, dumps("Unauthorized"), **response.headers)

    if not PYLOAD.isAuthorized(func, api.user):
        return HTTPError(403, dumps("Forbidden"), **response.headers)

    if not hasattr(PYLOAD.EXTERNAL, func) or func.startswith("_"):
        print "Invalid API call", func
        return HTTPError(404, dumps("Not Found"), **response.headers)

    # TODO: possible encoding
    # TODO Better error codes on invalid input

    args = [loads(unquote(arg)) for arg in args.split("/")[1:]]
    kwargs = {}

    # accepts body as json dict
    if request.json:
        kwargs = request.json

    # convert arguments from json to obj separately
    for x, y in chain(request.GET.iteritems(), request.POST.iteritems()):
        if not x or not y or x == "session": continue
        kwargs[x] = loads(unquote(y))

    try:
        result = getattr(api, func)(*args, **kwargs)
        # null is invalid json response
        if result is None: result = True
        return dumps(result)

    except ExceptionObject, e:
        return HTTPError(400, dumps(e), **response.headers)
Exemplo n.º 5
0
def logout():
    add_header(response)

    s = request.environ.get('beaker.session')
    s.delete()

    return dumps(True)
Exemplo n.º 6
0
def logout():
    add_header(response)

    s = request.environ.get('beaker.session')
    s.delete()

    return dumps(True)
Exemplo n.º 7
0
def login():
    add_header(response)

    username = request.params.get("username")
    password = request.params.get("password")

    user = PYLOAD.checkAuth(username, password, request.environ.get('REMOTE_ADDR', None))

    if not user:
        return dumps(False)

    s = set_session(request, user)

    # get the session id by dirty way, documentations seems wrong
    try:
        sid = s._headers["cookie_out"].split("=")[1].split(";")[0]
        return dumps(sid)
    except:
        print "Could not get session"
        return dumps(True)
Exemplo n.º 8
0
def json_response(obj):
    accept = 'gzip' in request.headers.get('Accept-Encoding', '')
    result = dumps(obj)
    # don't compress small string
    if gzip and accept and len(result) > 500:
        response.headers['Vary'] = 'Accept-Encoding'
        response.headers['Content-Encoding'] = 'gzip'
        zbuf = StringIO()
        zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
        zfile.write(result)
        zfile.close()
        return zbuf.getvalue()

    return result
Exemplo n.º 9
0
def json_response(obj):
    accept = 'gzip' in request.headers.get('Accept-Encoding', '')
    result = dumps(obj)
    # don't compress small string
    if gzip and accept and len(result) > 500:
        response.headers['Vary'] = 'Accept-Encoding'
        response.headers['Content-Encoding'] = 'gzip'
        zbuf = StringIO()
        zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf)
        zfile.write(result)
        zfile.close()
        return zbuf.getvalue()

    return result
Exemplo n.º 10
0
 def send(self, req, obj):
     return send_message(req, dumps(obj))
Exemplo n.º 11
0
        if not x or not y or x == "session": continue
        kwargs[x] = loads(unquote(y))

    try:
        result = getattr(api, func)(*args, **kwargs)
        # null is invalid json response
        if result is None: result = True
        return dumps(result)

    except ExceptionObject, e:
        return HTTPError(400, dumps(e), **response.headers)
    except Exception, e:
        print_exc()
        return HTTPError(
            500, dumps({
                "error": e.message,
                "traceback": format_exc()
            }), **response.headers)


@route("/api/login")
@route("/api/login", method="POST")
def login():
    add_header(response)

    username = request.params.get("username")
    password = request.params.get("password")

    user = PYLOAD.checkAuth(username, password,
                            request.environ.get('REMOTE_ADDR', None))

    if not user:
Exemplo n.º 12
0
def error(code, msg):
    return HTTPError(code, dumps(msg), **dict(response.headers))
Exemplo n.º 13
0
    # convert arguments from json to obj separately
    for x, y in chain(request.GET.iteritems(), request.POST.iteritems()):
        if not x or not y or x == "session": continue
        kwargs[x] = loads(unquote(y))

    try:
        result = getattr(api, func)(*args, **kwargs)
        # null is invalid json response
        if result is None: result = True
        return dumps(result)

    except ExceptionObject, e:
        return HTTPError(400, dumps(e), **response.headers)
    except Exception, e:
        print_exc()
        return HTTPError(500, dumps({"error": e.message, "traceback": format_exc()}), **response.headers)


@route("/api/login")
@route("/api/login", method="POST")
def login():
    add_header(response)

    username = request.params.get("username")
    password = request.params.get("password")

    user = PYLOAD.checkAuth(username, password, request.environ.get('REMOTE_ADDR', None))

    if not user:
        return dumps(False)
Exemplo n.º 14
0
 def send_result(self, req, code, result):
     return send_message(req, dumps([code, result]))
Exemplo n.º 15
0
 def send_result(self, req, code, result):
     return send_message(req, dumps([code, result]))
Exemplo n.º 16
0
def error(code, msg):
    return HTTPError(code, dumps(msg), **dict(response.headers))
Exemplo n.º 17
0
 def send(self, req, obj):
     return send_message(req, dumps(obj))
Exemplo n.º 18
0
    for x, y in request.params.iteritems():
        try:
            if not x or not y or x == "session": continue
            kwargs[x] = loads(unquote(y))
        except Exception, e:
            # Unsupported input
            msg = "Invalid Input %s, %s : %s" % (x, y, e.message)
            print_exc()
            print msg
            return error(415, msg)

    try:
        result = getattr(api, func)(*args, **kwargs)
        # null is invalid json response
        if result is None: result = True
        return dumps(result)

    except ExceptionObject, e:
        return error(400, e.message)
    except Exception, e:
        print_exc()
        return error(500, {"error": e.message, "traceback": format_exc()})


@route("/api/login")
@route("/api/login", method="POST")
def login():
    add_json_header(response)

    username = request.params.get("username")
    password = request.params.get("password")