Пример #1
0
def team_register():
    if request.method == "GET":
        return redirect(url_for('team_dashboard'))
    else:
        team_name = request.form["team_name"].strip()
        team_elig = "team_eligibility" in request.form
        affiliation = request.form["affiliation"].strip()

        try:
            if (Team.get(Team.name == team_name)):
                flash("The team name has been used.")
                return redirect(url_for('team_dashboard'))
        except Team.DoesNotExist:
            pass

        if len(team_name) > 50 or not team_name:
            flash("wrong team name format!")
            return redirect(url_for('team_dashboard'))
        if not affiliation or len(affiliation) > 100:
            affiliation = "No affiliation"
        team_leader = User.get(User.id == g.user.id)
        team = Team.create(name=team_name, eligible=team_elig, affiliation=affiliation, team_leader=team_leader)
        TeamMember.create(team=team,member=team_leader,member_confirmed=False)
        if not app.debug:
            UserAccess.create(user=g.user, ip=misc.get_ip(), time=datetime.now())
        session["team_id"] = team.id
        app.logger.info(g.user.username+" register a team.")
        flash("The request has send to admin.")
        return redirect(url_for('team_dashboard'))
Пример #2
0
def add_team():
    form = TeamForm()
    if form.validate_on_submit():
        team = Team()
        team.sport_id = form.add_sport.data.id
        db.session.add(team)
        form.populate_obj(team)
        db.session.commit()
        flash("Added team")
        return redirect(url_for("index"))
    return render_template("errors.html", form = form)
Пример #3
0
def team_modify():
    if request.method == "POST":
        team_name = request.form["team_name"].strip()
        team_elig = "team_eligibility" in request.form
        affiliation = request.form["affiliation"].strip()
        name_changed = (team_name!=g.team.name)
        affi_changed = (affiliation!=g.team.affiliation)
        elig_changed = (team_elig!=g.team.eligible)
        if not name_changed and not affi_changed and not elig_changed:
            flash("nothing changed!")
            return redirect(url_for('team_dashboard'))
        if name_changed:
            try:
                if (Team.get(Team.name == team_name)):
                    flash("The team name has been used.")
                    return redirect(url_for('team_dashboard'))
            except Team.DoesNotExist:
                pass

            if len(team_name) > 50 or not team_name:
                flash("wrong team name format!")
                return redirect(url_for('team_dashboard'))

        if affi_changed:
            if not affiliation or len(affiliation) > 100:
                affiliation = "No affiliation"

        g.team.name = team_name
        g.team.affiliation = affiliation
        g.team.eligible = team_elig
        g.team.save()
        app.logger.info(g.user.username+" modify team.")
        flash("change successfully.")
        return redirect(url_for('team_dashboard'))
Пример #4
0
def admin_dashboard():
    teams = Team.select()
    solves = ChallengeSolve.select(ChallengeSolve, Challenge).join(Challenge)
    adjustments = ScoreAdjustment.select()
    scoredata = utils.scoreboard.get_all_scores(teams, solves, adjustments)
    lastsolvedata = utils.scoreboard.get_last_solves(teams, solves)
    tickets = list(TroubleTicket.select().where(TroubleTicket.active == True))
    return render_template("admin/dashboard.html", teams=teams, scoredata=scoredata, lastsolvedata=lastsolvedata, tickets=tickets)
Пример #5
0
def admin_score_adjust(tid):
    value = int(request.form["value"])
    reason = request.form["reason"]

    team = Team.get(Team.id == tid)

    ScoreAdjustment.create(team=team, value=value, reason=reason)
    flash("Score adjusted.")

    return redirect(url_for(".admin_show_team", tid=tid))
Пример #6
0
def oauth2_step2():

    code = request.args.get('code')
    url = 'https://slack.com/api/oauth.access?client_id=%s&client_secret=%s&code=%s&redirect_uri=%s' % (
        CLIENT_ID, CLIENT_SECRET, code, REDIRECT_URI)

    r = requests.get(url)
    response = json.loads(r.text)

    s = session()

    team = Team(name=response['team_name'],
                token=response['access_token'],
                id=response['team_id'],
                bot_id=response['bot']['bot_user_id'],
                bot_token=response['bot']['bot_access_token'])
    s.add(team)

    sc = SlackClient(response['access_token'])
    """
    user_im_ids = {}
    
    im_list = sc.api_call('im.list')
    return str(im_list)

    
    for im in im_list['ims']:
        pass
        #user_im_ids[im['user']] = im['id']

    """

    user_list = sc.api_call("users.list")['members']

    for user_object in user_list:

        if user_object['deleted'] or not user_object['is_bot']:
            continue

        user_id = user_object['id']

        user_profile = user_object['profile']

        #im_id = user_im_ids[user_id]
        #user = User(id=user_id, team=team, im_id=im_id)

        user = User(id=user_id, team=team)
        s.add(user)

    s.commit()

    os.system("nohup python bot/rtmbot.py %s &" %
              response['bot']['bot_access_token'])

    return jsonify(r.json())
Пример #7
0
def user_regiter():
    body = request.get_json(force=True)
    try:
        user = User.create(email=body['email'],
                           password=body['password'],
                           name=body['name'],
                           token=b64encode(
                               body['email'].encode('utf-8')).decode('utf-8'),
                           team=Team.get_random_team())
    except IntegrityError:
        return error(404, "User not found")
    return jsonify({'token': user.token})
Пример #8
0
def register():
    if not config.registration:
        if "admin" in session and session["admin"]:
            pass
        else:
            return "Registration is currently disabled. Email [email protected] to create an account."

    if request.method == "GET":
        return render_template("register.html")
    elif request.method == "POST":
        error, message = captcha.verify_captcha()
        if error:
            flash(message)
            return render_template("register.html")

        team_name = request.form["team_name"].strip()
        team_email = request.form["team_email"].strip()
        team_elig = "team_eligibility" in request.form
        affiliation = request.form["affiliation"].strip()

        if len(team_name) > 50 or not team_name:
            flash("You must have a team name!")
            return render_template("register.html")

        if not (team_email and "." in team_email and "@" in team_email):
            flash("You must have a valid team email!")
            return render_template("register.html")

        if not affiliation or len(affiliation) > 100:
            affiliation = "No affiliation"

        if not email.is_valid_email(team_email):
            flash("You're lying")
            return render_template("register.html")

        team_key = misc.generate_team_key()
        confirmation_key = misc.generate_confirmation_key()

        team = Team.create(name=team_name,
                           email=team_email,
                           eligible=team_elig,
                           affiliation=affiliation,
                           key=team_key,
                           email_confirmation_key=confirmation_key)
        TeamAccess.create(team=team, ip=misc.get_ip(), time=datetime.now())

        email.send_confirmation_email(team_email, confirmation_key, team_key)

        session["team_id"] = team.id
        flash("Team created.")
        return redirect(url_for('dashboard'))
Пример #9
0
def scoreboard_variables():
    var = dict(config=config)
    var["user_teamed"] = False     #user_teamed用户属于某个队伍
    var["user_requested"] = False   #user_requested用户申请加入某个队伍
    var["team_requested"] = False   #team_requested用户申请创建某个队伍
    if "user_id" in session:
        var["logged_in"] = True
        var["user"] = g.user
        try:
            if (TeamMember.get(TeamMember.member == g.user.id).member_confirmed):
                var["user_teamed"] = True
        except:
            var["user_teamed"] = False
        try:
            if (not TeamMember.get(TeamMember.member == g.user.id).member_confirmed):
                var["user_requested"] = True
        except:
            var["user_requested"] = False
        try:
            if (not Team.get(Team.team_leader == g.user.id).team_confirmed):
                var["team_requested"] = True
        except:
            var["team_requested"] = False
    else:
        var["logged_in"] = False
        var["notifications"] = []

    if "team_id" in session:
        g.team = Team.get(Team.id == session["team_id"])
        var["team"] = g.team
        if (g.user.id == g.team.team_leader.id):
            var["user_leader"] = True        #用户是队长
        else:
            var["user_leader"] = False
        var["notifications"] = Notification.select().where(Notification.team == g.team)
    else:
        var["notifications"] = []
    return var
Пример #10
0
def teamconfirm():
    if utils.misc.get_ip() in config.confirm_ip:
        team_name = request.form["team_name"].strip()
        team_key = request.form["team_key"].strip()
        try:
            team = Team.get(Team.name == team_name)
        except Team.DoesNotExist:
            return "invalid", 403
        if team.key == team_key:
            return "ok", 200
        else:
            return "invalid", 403
    else:
        return "unauthorized", 401
Пример #11
0
def teamconfirm():
    if utils.misc.get_ip() in config.confirm_ip:
        team_name = request.form["team_name"].strip()
        team_key = request.form["team_key"].strip()
        try:
            team = Team.get(Team.name == team_name)
        except Team.DoesNotExist:
            return "invalid", 403
        if team.key == team_key:
            return "ok", 200
        else:
            return "invalid", 403
    else:
        return "unauthorized", 401
Пример #12
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    elif request.method == "POST":
        team_key = request.form["team_key"]

        try:
            team = Team.get(Team.key == team_key)
            TeamAccess.create(team=team, ip=misc.get_ip(), time=datetime.now())
            session["team_id"] = team.id
            flash("Login successful.")
            return redirect(url_for('dashboard'))
        except Team.DoesNotExist:
            flash("Couldn't find your team. Check your team key.", "error")
            return render_template("login.html")
Пример #13
0
def login():
    if request.method == "GET":
        return render_template("login.html")
    elif request.method == "POST":
        team_key = request.form["team_key"]

        try:
            team = Team.get(Team.key == team_key)
            TeamAccess.create(team=team, ip=misc.get_ip(), time=datetime.now())
            session["team_id"] = team.id
            flash("Login successful.")
            return redirect(url_for('dashboard'))
        except Team.DoesNotExist:
            flash("Couldn't find your team. Check your team key.", "error")
            return render_template("login.html")
Пример #14
0
def team_join():
    if request.method == "POST":
        team_name = request.form["team_name"].strip()
        try:
            team=Team.get(Team.name == team_name)
            if not team.team_confirmed:
                flash("The team has not be agreed by admin.Please wait,or join another team!")
                return redirect(url_for('team_dashboard'))
            else:
                TeamMember.create(team=team.id, member=g.user.id)
                app.logger.info(g.user.username+" want to join "+team_name)
                flash("The request has sent to leader!")
                return redirect(url_for('team_dashboard'))
        except Team.DoesNotExist:
            flash("team name do not exist!")
            return redirect(url_for('team_dashboard'))
Пример #15
0
def register():
    if not config.registration:
        if "admin" in session and session["admin"]:
            pass
        else:
            return "Registration is currently disabled. Email [email protected] to create an account."

    if request.method == "GET":
        return render_template("register.html")
    elif request.method == "POST":
        error, message = captcha.verify_captcha()
        if error:
            flash(message)
            return render_template("register.html")

        team_name = request.form["team_name"].strip()
        team_email = request.form["team_email"].strip()
        team_elig = "team_eligibility" in request.form
        affiliation = request.form["affiliation"].strip()

        if len(team_name) > 50 or not team_name:
            flash("You must have a team name!")
            return render_template("register.html")

        if not (team_email and "." in team_email and "@" in team_email):
            flash("You must have a valid team email!")
            return render_template("register.html")

        if not affiliation or len(affiliation) > 100:
            affiliation = "No affiliation"

        if not email.is_valid_email(team_email):
            flash("You're lying")
            return render_template("register.html")

        team_key = misc.generate_team_key()
        confirmation_key = misc.generate_confirmation_key()

        team = Team.create(name=team_name, email=team_email, eligible=team_elig, affiliation=affiliation, key=team_key,
                           email_confirmation_key=confirmation_key)
        TeamAccess.create(team=team, ip=misc.get_ip(), time=datetime.now())

        email.send_confirmation_email(team_email, confirmation_key, team_key)

        session["team_id"] = team.id
        flash("Team created.")
        return redirect(url_for('dashboard'))
Пример #16
0
def calculate_scores():
    solves = ChallengeSolve.select(ChallengeSolve, Challenge).join(Challenge)
    adjustments = ScoreAdjustment.select()
    teams = Team.select()

    team_solves = {team.id: [] for team in teams}
    team_mapping = {team.id: team for team in teams}
    scores = {team.id: 0 for team in teams}
    for solve in solves:
        scores[solve.team_id] += solve.challenge.points
        team_solves[solve.team_id].append(solve)
    for adjustment in adjustments:
        scores[adjustment.team_id] += adjustment.value

    most_recent_solve = {tid: max([i.time for i in team_solves[tid]]) for tid in team_solves if team_solves[tid]}
    scores = {i: j for i, j in scores.items() if i in most_recent_solve}
    # eligible, teamid, teamname, affiliation, score
    return [(team_mapping[i[0]].eligible, i[0], team_mapping[i[0]].name, team_mapping[i[0]].affiliation, i[1]) for idx, i in enumerate(sorted(scores.items(), key=lambda k: (-k[1], most_recent_solve[k[0]])))]
Пример #17
0
def team_search(name_search, limit=3, **kwargs):
    """Search database for a team by team name.

    Args:
        session (Session): Database session object.
        name_search (str): Team name to search for.
        threshold (int, optional): Levenshtein ratio cutoff.  Defaults to 
            80.

    Returns:
        Team object from database that matches the name.

    Raises:
        SearchError: If no match above 'threshold' is found.
    """

    ## Query database or use provided team list
    session = None
    team_list = None
    if "team_list" in kwargs:
        team_list = kwargs['team_list']
    elif "session" in kwargs:
        session = kwargs['session']
        team_list = Team.from_db(session)
    else:
        raise TypeError('Must provided either session=' +
                        'or team_list= parameters')
    
    ## Look for matches for the team
    choices = [team.name for team in team_list]
    matches = process.extract(name_search, choices, limit=limit)

    ## Get corresponding Team object for the results
    search_results = []
    for match in matches:
        for team in team_list:
            if team.name == match[0]:
                search_results.append((team, match[1]))

    ## Sort results
    search_results.sort(key=lambda x: x[1], reverse=True)
    return search_results
Пример #18
0
def dashboard():

    ad_matches = db.ad_matches()    #./dashboard

    #---------------OPERATIONS--------------------------------

    if request.method == 'POST':

        if request.form.get('operation') == 'schedule_match':

            team1 = request.form.get('team1_id')
            team2 = request.form.get('team2_id')
            date  = request.form.get('date')

            match = Match(team1_id=team1, team2_id=team2, date=date)

            db.addMatch(match)   

            return redirect(url_for('dashboard'))  

        elif request.form.get('operation') == 'delete_match':

            match_id = request.form.get('match_id')

            match = Match(match_id=match_id)

            db.deleteMatch(match)

            return redirect(url_for('dashboard'))

        elif request.form.get('operation') == 'add_team':

            name = request.form.get('team_name')
            captain = request.form.get('captain_name')

            team = Team(name=name, captain=captain)

            db.addTeam(team)

            return redirect(url_for('dashboard'))

        elif request.form.get('operation') == 'delete_team':

            id = request.form.get('team_id')

            team = Team(id=id)

            db.deleteTeam(team)

            return redirect(url_for('dashboard'))

        
        elif request.form.get('operation') == 'add_player':

            name = request.form.get('player_name')
            team_id = request.form.get('team_id')

            player = Player(name=name, team_id=team_id)

            db.addPlayer(player)

            return redirect(url_for('dashboard'))

        elif request.form.get('operation') == 'delete_player':

            id = request.form.get('player_id')
            team_id = request.form.get('team_id')

            player = Player(id=id, team_id=team_id)

            db.deletePlayer(player)

            return redirect(url_for('dashboard'))


    return render_template("./admin/dashboard.html",title="Dash Board", matches=ad_matches)
Пример #19
0
def make_info_available():
    if "user_id" in session:
        g.user = User.get(User.id == session["user_id"])
    if "team_id" in session:
        g.team = Team.get(Team.id == session["team_id"])
        g.team_restricts = g.team.restricts.split(",")
Пример #20
0
def make_info_available():
    if "team_id" in session:
        g.team = Team.get(Team.id == session["team_id"])
        g.team_restricts = g.team.restricts.split(",")
Пример #21
0
def admin_toggle_eligibility_lock(tid):
    team = Team.get(Team.id == tid)
    team.eligibility_locked = not team.eligibility_locked
    team.save()
    flash("Eligibility lock set to {}".format(team.eligibility_locked))
    return redirect(url_for(".admin_show_team", tid=tid))
Пример #22
0
def admin_show_team(tid):
    team = Team.get(Team.id == tid)
    return render_template("admin/team.html", team=team)