コード例 #1
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def user_contest_game(user_id, contest_id, game_id):
    game = query_db("""select games.date, games.contest_id
                          from games, users, contests
                          where (users.id=contests.user_id and
                                 games.contest_id=contests.id and
                                 users.id=? and
                                 contests.id=? and
                                 games.id=?)""",
                    (user_id, contest_id, game_id), one=True)
    if not game:
        return json_response(404, 'No such game')
    if request.method == 'DELETE':
        check_session_auth(user_id)
        g.db.execute("""delete from games where id=?""", (game_id,))
        g.db.execute("""delete from scores where game_id=?""", (game_id,))
        g.db.commit()
        return json_response()
    else:
        scores = query_db("""select player_id, score
                                from scores
                                where game_id=?""",
                          (game_id,))
        ordered = sorted(scores, key=lambda x: x["score"], reverse=True)
        ranking = map(lambda x: int(x["player_id"]), ordered)
        game["ranking"] = ranking
        return json_response(data={"game": game})
コード例 #2
0
ファイル: contests.py プロジェクト: josephturnerjr/brackcity
class ManyPlayersRanked(Contest):
    _SCHEMA = dict(Contest._SCHEMA)
    _SCHEMA.update({"ranking": [1]})
    GAME_SCHEMA = json.dumps(_SCHEMA)

    def get_game_schema(self):
        print ManyPlayersRanked.GAME_SCHEMA
        return ManyPlayersRanked.GAME_SCHEMA

    def create_game(self, **kwargs):
        cur = g.db.cursor()
        try:
            ranking = kwargs["ranking"]
        except ValueError:
            raise GameValidationError("Rankings must be a list of player ids in decreasing order of score")
        except KeyError, e:
            raise GameValidationError("Required argument %s not found" % e.message)
        if not isinstance(ranking, list):
            raise GameValidationError("Rankings must be a list of player ids in decreasing order of score")
        if len(ranking) < 2:
            raise GameValidationError("Games for this contest type must have two or more players")
        players = query_db("""select id
                               from players
                               where id in (%s) and
                               contest_id = ?""" % (",".join('?' * len(ranking)),),
                           ranking + [self.contest_id])
        if len(players) != len(ranking):
            raise GameValidationError('Rankings must be for contest players')
        scores_json = json.dumps({"ranking": ranking})
        game_id = Contest.create_game(self, cur, scores_json, **kwargs)
        return game_id
コード例 #3
0
ファイル: contests.py プロジェクト: josephturnerjr/brackcity
class PingPong(Contest):
    _SCHEMA = dict(Contest._SCHEMA)
    _SCHEMA.update({"players": [1, 2], "games_played": 3, "game_scores": [[11, 9], [19, 21], [11, 2]]})
    GAME_SCHEMA = json.dumps(_SCHEMA)

    def get_game_schema(self):
        return self.GAME_SCHEMA

    def create_game(self, **kwargs):
        cur = g.db.cursor()
        try:
            players = kwargs["players"]
            scores = kwargs["game_scores"]
        except ValueError:
            raise GameValidationError("Game must be a valid JSON object")
        except KeyError, e:
            raise GameValidationError("Required argument %s not found" % e.message)
        if len(players) != 2:
            raise GameValidationError("This context is for singles ping pong, there must be 2 players")
        if not reduce(lambda x, y: x and y, map(lambda x: len(x) == 2, scores)):
            raise GameValidationError("Game scores must be lists of length 2")
        cplayers = query_db("""select id
                               from players
                               where id in (?,?) and
                               contest_id = ?""",  (players[0], players[1], self.contest_id))
        if len(cplayers) != 2:
            raise GameValidationError('Rankings must be for contest players')
        scores_json = json.dumps({"players": players, "scores": scores})
        game_id = Contest.create_game(self, cur, scores_json, **kwargs)
        return game_id
コード例 #4
0
ファイル: auth.py プロジェクト: josephturnerjr/brackcity
def check_auth(username, password):
    q = query_db('select user_id, is_admin from sessions where session_id=?',
                 (username,),
                 one=True)
    if q:
        g.auth_user_id = q["user_id"]
        g.is_user_admin = q["is_admin"]
        return True
    else:
        return False
コード例 #5
0
ファイル: auth.py プロジェクト: josephturnerjr/brackcity
def check_auth(username, password):
    q = query_db('select user_id, is_admin from sessions where session_id=?',
                 (username, ),
                 one=True)
    if q:
        g.auth_user_id = q["user_id"]
        g.is_user_admin = q["is_admin"]
        return True
    else:
        return False
コード例 #6
0
ファイル: contests.py プロジェクト: josephturnerjr/brackcity
def load_contest(user_id, contest_id):
    contest = query_db("""select contests.name, contests.id, contests.user_id,
                                 contests.type
                                          from users, contests
                                          where (users.id=contests.user_id and
                                                 users.id=? and
                                                 contests.id=?)""",
                       (user_id, contest_id), one=True)
    if contest:
        return CONTEST_FACTORIES[contest["type"]](user_id, contest["name"],
                                                  contest["type"], contest_id)
    return None
コード例 #7
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def user_contests(user_id):
    valid = '{"name": "contest name (string)", "type": "contest type (string)"}'
    user = query_db('select id from users where id=?',
                    (user_id,), one=True)
    if not user:
        return json_response(404, 'No such user')
    if request.method == 'POST':
        check_session_auth(user_id)
        try:
            data = get_request_data(valid)
        except (NoDataError, BadDataError, SchemaError), e:
            return json_response(400, e.message)
        name = data['name']
        c_type = data['type']
        try:
            contest = create_contest(user_id, name, c_type)
        except ContestError, e:
            return json_response(400, e.message)
コード例 #8
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def user_contest_games(user_id, contest_id):
    contest = query_db("""select contests.name, contests.id,
                                 contests.user_id, contests.type
                                          from users, contests
                                          where (users.id=contests.user_id and
                                                 users.id=? and
                                                 contests.id=?)""",
                       (user_id, contest_id), one=True)
    contest = load_contest(user_id, contest_id)
    if not contest:
        return json_response(404, 'No such contest')
    if request.method == 'POST':
        check_session_auth(user_id)
        try:
            print contest.get_game_schema()
            data = get_request_data(contest.get_game_schema())
            game_id = contest.create_game(**data)
            return json_response(data={"id": game_id})
        except (NoDataError, BadDataError, SchemaError, GameValidationError), e:
            return json_response(400, e.message)
コード例 #9
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def user_contest(user_id, contest_id):
    contest = query_db("""select contests.name, contests.id, contests.user_id
                                 from users, contests
                                          where (users.id=contests.user_id and
                                                 users.id=? and
                                                 contests.id=?)""",
                    (user_id, contest_id), one=True)
    if not contest:
        return json_response(404, 'No such contest')
    if request.method == 'PUT':
        check_session_auth(user_id)
        try:
            name = str(request.form['name'])
            g.db.execute("""update contests set user_id=?, name=?
                                            where id=?""",
                         (user_id, name, contest_id))
            g.db.commit()
            return json_response()
        except KeyError, e:
            return json_response(400,
                                 "Required argument %s not found" % e.message)
コード例 #10
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def user_contest_player(user_id, contest_id, player_id):
    player = query_db("""select players.name, players.id, players.user_id
                          from users, contests, players
                          where (users.id=contests.user_id and
                                 players.contest_id=contests.id and
                                 users.id=? and
                                 contests.id=? and
                                 players.id=?)""",
                    (user_id, contest_id, player_id), one=True)
    if not player:
        return json_response(404, 'No such player')
    if request.method == 'PUT':
        check_session_auth(user_id)
        try:
            name = str(request.form['name'])
            player_user_id = None  # int(request.form['player_id'])
            g.db.execute("""update players set name=?, user_id=?
                                            where id=?""",
                         (name, player_user_id, player_id))
            g.db.commit()
            return json_response()
        except KeyError, e:
            return json_response(400,
                                 "Required argument %s not found" % e.message)
コード例 #11
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def user_contest_players(user_id, contest_id):
    contest = query_db("""select contests.name, contests.id, contests.user_id
                                          from users, contests
                                          where (users.id=contests.user_id and
                                                 users.id=? and
                                                 contests.id=?)""",
                       (user_id, contest_id), one=True)
    if not contest:
        return json_response(404, 'No such contest')
    if request.method == 'POST':
        check_session_auth(user_id)
        try:
            name = request.form['name']
            player_user_id = None  # int(request.form['player_id'])
            cur = g.db.cursor()
            cur.execute("""insert into players (contest_id, name, user_id)
                                        values (?, ?, ?)""",
                         (contest["id"], name, player_user_id))
            g.db.commit()
            player_id = cur.lastrowid
            return json_response(data={"id": player_id})
        except KeyError, e:
            return json_response(400,
                                 "Required argument %s not found" % e.message)
コード例 #12
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def contest(contest_id):
    contest = query_db('select name, id, user_id from contests where id=?',
                 (contest_id,), one=True)
    if not contest:
        return json_response(404, "No such contest")
    return json_response(data={"contest": contest})
コード例 #13
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def contests():
    contests = query_db('select id, user_id, name from contests')
    return json_response(data={"contests": contests})
コード例 #14
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def user(user_id):
    user = query_db('select id, name, username from users where id=?',
                    (user_id,), one=True)
    if not user:
        return json_response(404, "No such user")
    return json_response(data={"user": user})
コード例 #15
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
def users():
    users = query_db('select id, username from users')
    return json_response(data={"users": users})
コード例 #16
0
ファイル: api_views.py プロジェクト: josephturnerjr/brackcity
    except ValueError:
        # Error loading json
        raise BadDataError("'data' argument must be valid JSON")


@app.route('/login', methods=['POST'])
def login():
    valid = '{"username": "******", "password": "******"}'
    try:
        data = get_request_data(valid)
    except (NoDataError, BadDataError, SchemaError), e:
        return json_response(400, e.message)
    username = data['username']
    password = data['password']
    q = query_db('select id, name, pw_hash from users where username=?',
                 (username,),
                 one=True)
    if q:
        if check_pw(password, q['pw_hash']):
            is_admin = False
            admin_q = query_db('select id from admins where user_id=?',
                         (q["id"],),
                         one=True)
            is_admin = bool(admin_q)
            session_token = uuid.uuid4().hex
            g.db.execute("""insert into sessions (user_id, session_id,
                                                  creation_date, is_admin)
                                          values (?, ?, ?, ?)""",
                         (q["id"], session_token,
                          datetime.datetime.today(), is_admin))
            g.db.commit()