示例#1
0
文件: api.py 项目: FroopleXP/BitOrb
def api_token_redeem():
    try:
        auth_token = request.form["auth_token"]

        token_code = request.form["token_code"]
    except KeyError as e:
        raise APIMissingField(e.args[0])

    caller = get_user_from_token(auth_token)

    conn = engine.connect()

    query = sql.select([Token]).where(Token.code == token_code).limit(1)
    res = conn.execute(query)
    try:
        token = res.fetchall()[0]
    except IndexError:
        raise APIInvalidField("token_code", 200)

    query1 = sql.update(Token).where(Token.id == token.id).values({
        Token.redeemed: True,
        Token.redeemer: caller.id
    })
    query2 = sql.update(User).where(User.id == caller.id).values({
        User.credits: caller.credits + token.value
    })
    res1 = conn.execute(query1)
    res2 = conn.execute(query2)

    if res1.inserted_primary_key and res2.inserted_primary_key:
        return make_response(jsonify({
            "status": "success",
            "message": "Token successfully redeemed",
            "new_balance": caller.credits + token.value
        }))
示例#2
0
文件: api.py 项目: FroopleXP/BitOrb
def api_user_create():
    try:
        auth_token = request.form["auth_token"]

        user_first_name = request.form["user_first_name"]
        user_last_name = request.form["user_last_name"]
        user_other_names = request.form["user_other_names"] or None

        user_email = request.form["user_email"] or None
        user_username = request.form["user_first_name"]
        user_password = request.form["user_password"] or gen_password(8)

        user_rank = request.form["rank"]

        if "" in (user_first_name, user_last_name, user_username,
                  user_password, user_rank):
            raise KeyError

    except KeyError as e:
        raise APIMissingField(e.args[0])

    caller = get_user_from_token(auth_token)

    if caller.rank != "admin":
        return make_response(
            jsonify({
                "status":
                "failed",
                "message":
                "You do not have a high enough rank to create users."
            }))

    conn = engine.connect()
    query = sql.insert(
        User, {
            User.first_name: user_first_name,
            User.last_name: user_last_name,
            User.other_names: user_other_names,
            User.email: user_email,
            User.username: user_username,
            User.pass_hash: crypt_hash(user_password),
            User.rank: user_rank
        })
    res = conn.execute(query)

    if res.inserted_primary_key:
        return make_response(
            jsonify({
                "status": "success",
                "message": "User created",
                "user_id": res.inserted_primary_key
            }))
    else:
        return make_response(
            jsonify({
                "status": "failed",
                "message": "Unknown error"
            }))
示例#3
0
def get_user_from_id(user_id):
    conn = engine.connect()
    query = sql.select([User]).where((User.id == user_id))
    res = conn.execute(query)

    if res.rowcount == 1:
        return res.fetchone()
    else:
        raise UserNotFound()
示例#4
0
def get_estab_from_id(estab_id):
    conn = engine.connect()
    query = sql.select([Establishment]).where((Establishment.id == estab_id))
    res = conn.execute(query)

    if res.rowcount == 1:
        return res.fetchone()
    else:
        raise EstabNotFound()
示例#5
0
def get_estab_from_id(estab_id):
    conn = engine.connect()
    query = sql.select([Establishment]).where(
        (Establishment.id == estab_id)
    )
    res = conn.execute(query)

    if res.rowcount == 1:
        return res.fetchone()
    else:
        raise EstabNotFound()
示例#6
0
文件: main.py 项目: FroopleXP/BitOrb
def login():
    if request.cookies.get("auth_token"):
        return redirect("/user")
    else:
        query = sql.select(
            (Establishment.id,
             Establishment.full_name)).order_by(Establishment.full_name)
        conn = engine.connect()
        res = conn.execute(query)

        return render_template("login.html", establishments=res.fetchall())
示例#7
0
def get_user_from_id(user_id):
    conn = engine.connect()
    query = sql.select([User]).where(
        (User.id == user_id)
    )
    res = conn.execute(query)

    if res.rowcount == 1:
        return res.fetchone()
    else:
        raise UserNotFound()
示例#8
0
文件: api.py 项目: FroopleXP/BitOrb
def api_user_create():
    try:
        auth_token = request.form["auth_token"]

        user_first_name = request.form["user_first_name"]
        user_last_name = request.form["user_last_name"]
        user_other_names = request.form["user_other_names"] or None

        user_email = request.form["user_email"] or None
        user_username = request.form["user_first_name"]
        user_password = request.form["user_password"] or gen_password(8)

        user_rank = request.form["rank"]

        if "" in (user_first_name, user_last_name, user_username, user_password, user_rank):
            raise KeyError

    except KeyError as e:
        raise APIMissingField(e.args[0])

    caller = get_user_from_token(auth_token)

    if caller.rank != "admin":
        return make_response(jsonify({
            "status": "failed",
            "message": "You do not have a high enough rank to create users."
        }))

    conn = engine.connect()
    query = sql.insert(User, {
        User.first_name: user_first_name,
        User.last_name: user_last_name,
        User.other_names: user_other_names,

        User.email: user_email,
        User.username: user_username,
        User.pass_hash: crypt_hash(user_password),

        User.rank: user_rank
    })
    res = conn.execute(query)

    if res.inserted_primary_key:
        return make_response(jsonify({
            "status": "success",
            "message": "User created",
            "user_id": res.inserted_primary_key
        }))
    else:
        return make_response(jsonify({
            "status": "failed",
            "message": "Unknown error"
        }))
示例#9
0
文件: main.py 项目: FroopleXP/BitOrb
def login():
    if request.cookies.get("auth_token"):
        return redirect("/user")
    else:
        query = sql.select(
            (
                Establishment.id,
                Establishment.full_name
            )
        ).order_by(Establishment.full_name)
        conn = engine.connect()
        res = conn.execute(query)

        return render_template("login.html", establishments=res.fetchall())
示例#10
0
文件: api.py 项目: FroopleXP/BitOrb
def api_user_login():
    print(request.form.to_dict())
    try:
        estab_id = request.form["estab_id"]
        username = request.form["username"]
        password = request.form["password"]

        if estab_id == "":
            raise APIMissingField("estab_id")
        elif username == "":
            raise APIMissingField("username")
        elif password == "":
            raise APIMissingField("password")

    except KeyError as e:
        raise APIMissingField(e.args[0])
    try:
        estab_id = int(estab_id)
    except ValueError:
        raise APIInvalidField("estab_id")

    username = username.lower()
    pass_hash = crypt_hash(password)

    conn = engine.connect()
    query = sql.select([User]).where((User.establishment == estab_id)
                                     & (User.username == username)
                                     & (User.pass_hash == pass_hash))
    res = conn.execute(query)

    if res.rowcount == 1:
        # successful login, make a token
        return make_response(
            jsonify({
                "status": "success",
                "message": "You have successfully logged in.",
                "auth_token": gen_login_token(res.fetchall()[0])
            }), 200)

    else:
        return make_response(
            jsonify({
                "status":
                "failed",
                "message":
                "Username, password and establishment combination was incorrect."
            }), 200)
示例#11
0
文件: api.py 项目: FroopleXP/BitOrb
def api_user_login():
    print(request.form.to_dict())
    try:
        estab_id = request.form["estab_id"]
        username = request.form["username"]
        password = request.form["password"]

        if estab_id == "":
            raise APIMissingField("estab_id")
        elif username == "":
            raise APIMissingField("username")
        elif password == "":
            raise APIMissingField("password")

    except KeyError as e:
        raise APIMissingField(e.args[0])
    try:
        estab_id = int(estab_id)
    except ValueError:
        raise APIInvalidField("estab_id")

    username = username.lower()
    pass_hash = crypt_hash(password)

    conn = engine.connect()
    query = sql.select([User]).where(
        (User.establishment == estab_id) &
        (User.username == username) &
        (User.pass_hash == pass_hash)
    )
    res = conn.execute(query)

    if res.rowcount == 1:
        # successful login, make a token
        return make_response(jsonify({
            "status": "success",
            "message": "You have successfully logged in.",
            "auth_token": gen_login_token(res.fetchall()[0])
        }), 200)

    else:
        return make_response(jsonify({
            "status": "failed",
            "message": "Username, password and establishment combination was incorrect."
        }), 200)
示例#12
0
def get_user_from_token(token):
    if not signer.validate(token):
        raise AuthTokenInvalid()

    split = signer.unsign(token).decode("utf8").split("-")

    username = split[0]
    estab_id = split[1]

    conn = engine.connect()
    query = sql.select([User]).where((User.establishment == estab_id)
                                     & (User.username == username))
    res = conn.execute(query)

    if res.rowcount == 1:
        return res.fetchone()
    else:
        raise AuthTokenInvalid()
示例#13
0
文件: main.py 项目: FroopleXP/BitOrb
def other_user(estab_code_name, username):
    estab_code_name = estab_code_name.upper()
    username = username.lower()

    conn = engine.connect()
    query = sql.select((Establishment, )).where(
        Establishment.code_name == estab_code_name).limit(1)
    res = conn.execute(query)
    if res.rowcount == 0:
        return make_response("Invalid estab_code_name", 404)

    estab_id = res.fetchone()["id"]

    query = sql.select((User, )).where((User.establishment == estab_id)
                                       & (User.username == username)).limit(1)
    res = conn.execute(query)
    if res.rowcount == 0:
        return make_response("User not found", 404)
    else:
        return render_template("user.html", user_id=res.fetchone()["id"])
示例#14
0
def get_user_from_token(token):
    if not signer.validate(token):
        raise AuthTokenInvalid()

    split = signer.unsign(token).decode("utf8").split("-")

    username = split[0]
    estab_id = split[1]

    conn = engine.connect()
    query = sql.select([User]).where(
        (User.establishment == estab_id) &
        (User.username == username)
    )
    res = conn.execute(query)

    if res.rowcount == 1:
        return res.fetchone()
    else:
        raise AuthTokenInvalid()
示例#15
0
文件: main.py 项目: FroopleXP/BitOrb
def other_user(estab_code_name, username):
    estab_code_name = estab_code_name.upper()
    username = username.lower()

    conn = engine.connect()
    query = sql.select((Establishment,)).where(
        Establishment.code_name == estab_code_name
    ).limit(1)
    res = conn.execute(query)
    if res.rowcount == 0:
        return make_response("Invalid estab_code_name", 404)

    estab_id = res.fetchone()["id"]

    query = sql.select((User, )).where(
        (User.establishment == estab_id) &
        (User.username == username)
    ).limit(1)
    res = conn.execute(query)
    if res.rowcount == 0:
        return make_response("User not found", 404)
    else:
        return render_template("user.html", user_id=res.fetchone()["id"])
示例#16
0
文件: api.py 项目: FroopleXP/BitOrb
def api_token_redeem():
    try:
        auth_token = request.form["auth_token"]

        token_code = request.form["token_code"]
    except KeyError as e:
        raise APIMissingField(e.args[0])

    caller = get_user_from_token(auth_token)

    conn = engine.connect()

    query = sql.select([Token]).where(Token.code == token_code).limit(1)
    res = conn.execute(query)
    try:
        token = res.fetchall()[0]
    except IndexError:
        raise APIInvalidField("token_code", 200)

    query1 = sql.update(Token).where(Token.id == token.id).values({
        Token.redeemed:
        True,
        Token.redeemer:
        caller.id
    })
    query2 = sql.update(User).where(User.id == caller.id).values(
        {User.credits: caller.credits + token.value})
    res1 = conn.execute(query1)
    res2 = conn.execute(query2)

    if res1.inserted_primary_key and res2.inserted_primary_key:
        return make_response(
            jsonify({
                "status": "success",
                "message": "Token successfully redeemed",
                "new_balance": caller.credits + token.value
            }))
示例#17
0
文件: api.py 项目: FroopleXP/BitOrb
def api_token_add():
    try:
        auth_token = request.form["auth_token"]

        token_value = request.form["token_value"]
    except KeyError as e:
        raise APIMissingField(e.args[0])

    try:
        token_code = request.form["token_code"]
    except KeyError as e:
        token_code = None

    try:
        token_number = request.form["token_number"]
    except KeyError as e:
        token_number = 1

    caller = get_user_from_token(auth_token)

    token_number = min(100, int(token_number))
    if token_number == 0:
        raise APIInvalidField("token_number")

    if caller.rank != "admin":
        if caller.credits < token_value * token_number:
            raise APIInvalidUsage(
                "Not enough credits")  # TODO: add better error

    tokens = []

    if token_number == 1 and token_code:
        if re.match("[^A-Z0-9]", token_code) or len(token_code) != 10:
            token_code = gen_password(10)
        tokens.append({
            "code": token_code,
            "value": token_value,
            "creator": caller.id,
            "redeemed": False
        })

    else:
        for token in range(token_number):
            tokens.append({
                "code": gen_password(10),
                "value": token_value,
                "creator": caller.id,
                "redeemed": False
            })

    pprint(tokens)

    conn = engine.connect()
    query1 = sql.insert(Token, tokens)
    res = conn.execute(query1)

    if res.inserted_primary_key:
        if caller.rank != "admin":
            query = sql.update(User).where(User.id == caller.id).values(
                {User.credits: caller.credits - token_number * token_code})
            res = conn.execute(query)

        return make_response(
            jsonify({
                "status":
                "success",
                "message":
                "%s codes have been generated with a value of %s credits." %
                (str(token_number), str(token_value)),
                "tokens":
                list({
                    "code": x["code"],
                    "value": x["value"]
                } for x in tokens)
            }))
示例#18
0
文件: api.py 项目: FroopleXP/BitOrb
def api_estab_create():
    try:
        full_name = request.form["full_name"]
        code_name = request.form["code_name"]
    except KeyError as e:
        # do something more useful here
        raise APIMissingField(e.args[0])

    try:
        user = request.form["user"] or ""
        password = request.form["password"] or ""

        if "" in (user, password):
            raise KeyError

        default_user = False
    except KeyError as e:
        user = "******"
        password = gen_password(8)
        default_user = True

    if full_name == "":
        raise APIMissingField("name")

    conn = engine.connect()
    query = sql.Insert(Establishment, {
        Establishment.full_name: full_name,
        Establishment.code_name: code_name
    })
    try:
        res = conn.execute(query)
    except sqlalchemy.exc.IntegrityError as e:
        print(e)
        return make_response(jsonify({
            "status": "failed",
            "message": "Name is in use."
        }), 400)
    estab_id = res.inserted_primary_key[0]

    query = sql.insert(User, {
        User.first_name: "Admin",
        User.last_name: "User",
        User.rank: "admin",

        User.username: user,
        User.pass_hash: crypt_hash(password),
        User.establishment: estab_id
    })
    res = conn.execute(query)

    if default_user:
        return make_response(jsonify({
            "status": "success",
            "message": "Establishment was created! (User does not work yet...)",
            "id": estab_id,
            "username": user,
            "password": password
        }))
    else:
        return make_response(jsonify({
            "status": "success",
            "message": "Establishment was created! (User does not work yet...)",
            "id": estab_id,
            "username": user,
            "password": "******"
        }))
示例#19
0
文件: api.py 项目: FroopleXP/BitOrb
def api_token_add():
    try:
        auth_token = request.form["auth_token"]

        token_value = request.form["token_value"]
    except KeyError as e:
        raise APIMissingField(e.args[0])

    try:
        token_code = request.form["token_code"]
    except KeyError as e:
        token_code = None

    try:
        token_number = request.form["token_number"]
    except KeyError as e:
        token_number = 1

    caller = get_user_from_token(auth_token)

    token_number = min(100, int(token_number))
    if token_number == 0:
        raise APIInvalidField("token_number")

    if caller.rank != "admin":
        if caller.credits < token_value * token_number:
            raise APIInvalidUsage("Not enough credits")  # TODO: add better error

    tokens = []

    if token_number == 1 and token_code:
        if re.match("[^A-Z0-9]", token_code) or len(token_code) != 10:
            token_code = gen_password(10)
        tokens.append({
            "code": token_code,
            "value": token_value,
            "creator": caller.id,
            "redeemed": False
        })

    else:
        for token in range(token_number):
            tokens.append({
                "code": gen_password(10),
                "value": token_value,
                "creator": caller.id,
                "redeemed": False
            })

    pprint(tokens)

    conn = engine.connect()
    query1 = sql.insert(Token, tokens)
    res = conn.execute(query1)

    if res.inserted_primary_key:
        if caller.rank != "admin":
            query = sql.update(User).where(User.id == caller.id).values({
                User.credits: caller.credits - token_number*token_code
            })
            res = conn.execute(query)

        return make_response(jsonify({
            "status": "success",
            "message": "%s codes have been generated with a value of %s credits." % (
                str(token_number),
                str(token_value)
            ),
            "tokens": list({"code": x["code"], "value": x["value"]} for x in tokens)
        }))
示例#20
0
文件: api.py 项目: FroopleXP/BitOrb
def api_estab_create():
    try:
        full_name = request.form["full_name"]
        code_name = request.form["code_name"]
    except KeyError as e:
        # do something more useful here
        raise APIMissingField(e.args[0])

    try:
        user = request.form["user"] or ""
        password = request.form["password"] or ""

        if "" in (user, password):
            raise KeyError

        default_user = False
    except KeyError as e:
        user = "******"
        password = gen_password(8)
        default_user = True

    if full_name == "":
        raise APIMissingField("name")

    conn = engine.connect()
    query = sql.Insert(Establishment, {
        Establishment.full_name: full_name,
        Establishment.code_name: code_name
    })
    try:
        res = conn.execute(query)
    except sqlalchemy.exc.IntegrityError as e:
        print(e)
        return make_response(
            jsonify({
                "status": "failed",
                "message": "Name is in use."
            }), 400)
    estab_id = res.inserted_primary_key[0]

    query = sql.insert(
        User, {
            User.first_name: "Admin",
            User.last_name: "User",
            User.rank: "admin",
            User.username: user,
            User.pass_hash: crypt_hash(password),
            User.establishment: estab_id
        })
    res = conn.execute(query)

    if default_user:
        return make_response(
            jsonify({
                "status": "success",
                "message":
                "Establishment was created! (User does not work yet...)",
                "id": estab_id,
                "username": user,
                "password": password
            }))
    else:
        return make_response(
            jsonify({
                "status": "success",
                "message":
                "Establishment was created! (User does not work yet...)",
                "id": estab_id,
                "username": user,
                "password": "******"
            }))