示例#1
0
def team_create():
    mock = config_setting("TESTING")
    customNames = config_setting("CUSTOM_PLAYER_NAMES")
    if not g.user:
        return redirect('/login')
    form = TeamForm()
    # We wish to query this every time, since we can now upload photos.
    if not mock:
        form.logo.choices = logos.get_logo_choices()
    if request.method == 'POST':
        num_teams = g.user.teams.count()
        max_teams = config_setting('USER_MAX_TEAMS')
        if max_teams >= 0 and num_teams >= max_teams and not (util.is_admin(
                g.user) or util.is_super_admin(g.user)):
            flash('You already have the maximum number of teams ({}) stored'.
                  format(num_teams))

        elif form.validate():
            data = form.data
            auths = form.get_auth_list()
            pref_names = form.get_pref_list()
            name = data['name'].strip()
            tag = data['tag'].strip()
            flag = data['country_flag']
            logo = data['logo']

            # Update the logo. Passing validation we have the filename in the
            # list now.
            if not mock and (util.is_admin(g.user) or util.is_super_admin(
                    g.user)) and form.upload_logo.data:
                filename = secure_filename(form.upload_logo.data.filename)
                index_of_dot = filename.index('.')
                newLogoDetail = filename[:index_of_dot]
                # Reinit our logos.
                logos.add_new_logo(newLogoDetail)
                app.logger.info("Added new logo id {}".format(newLogoDetail))
                data['logo'] = newLogoDetail

            team = Team.create(
                g.user, name, tag, flag, logo, auths, data['public_team']
                and (util.is_admin(g.user) or util.is_super_admin(g.user)),
                pref_names)

            db.session.commit()
            app.logger.info('User {} created team {}'.format(
                g.user.id, team.id))

            return redirect('/teams/{}'.format(team.user_id))

        else:
            flash_errors(form)

    return render_template('team_create.html',
                           user=g.user,
                           form=form,
                           edit=False,
                           is_admin=(util.is_admin(g.user)
                                     or util.is_super_admin(g.user)),
                           MAXPLAYER=Team.MAXPLAYERS,
                           customNames=customNames)
示例#2
0
def server_edit(serverid):
    server = GameServer.query.get_or_404(serverid)
    is_owner = (g.user and (util.is_server_owner(g.user, server)))
    is_sadmin = (g.user and util.is_super_admin(g.user))
    app.logger.info("Owner: {} Sadmin: {}".format(is_owner, is_sadmin))
    if not is_owner:
        if not is_sadmin:
            raise BadRequestError('You do not have access to this server.')

    # Attempt encryption/decryption
    rconDecrypt = util.decrypt(dbKey, server.rcon_password)
    form = ServerForm(request.form,
                      display_name=server.display_name,
                      ip_string=server.ip_string,
                      port=server.port,
                      rcon_password=server.rcon_password
                      if rconDecrypt is None else rconDecrypt,
                      public_server=server.public_server)

    if request.method == 'POST':
        if form.validate():
            mock = app.config['TESTING']
            data = form.data
            if not mock:
                encRcon = util.encrypt(dbKey, str(data['rcon_password']))
            else:
                encRcon = data['rcon_password']
            server.display_name = data['display_name']
            server.ip_string = data['ip_string']
            server.port = data['port']
            server.rcon_password = encRcon
            server.public_server = (data['public_server']
                                    and util.is_admin(g.user))

            if mock or util.check_server_connection(server, dbKey):
                db.session.commit()
                return redirect('/myservers')
            else:
                db.session.remove()
                flash('Failed to connect to server')

        else:
            flash_errors(form)

    return render_template('server_create.html',
                           user=g.user,
                           form=form,
                           edit=True,
                           is_admin=util.is_admin(g.user),
                           is_sadmin=util.is_super_admin(g.user))
示例#3
0
def match_rcon(matchid):
    match = Match.query.get_or_404(matchid)

    command = request.values.get('command')
    server = GameServer.query.get_or_404(match.server_id)
    owns_server = util.is_server_owner(g.user, server)
    is_sadmin = util.is_super_admin(g.user)
    # Check to see if user owns server.
    if not owns_server or not is_sadmin:
        raise BadRequestError('You are not the server owner.')

    if command:
        try:
            rcon_response = server.send_rcon_command(
                command, raise_errors=True)
            if rcon_response:
                rcon_response = Markup(rcon_response.replace('\n', '<br>'))
            else:
                rcon_response = 'No output'
            flash(rcon_response)
            # Store the command.
            match_audit.create(g.user.id, matchid, datetime.now(), command)
            db.session.commit()
        except util.RconError as e:
            print(e)
            flash('Failed to send command: ' + str(e))

    return redirect('/match/{}'.format(matchid))
示例#4
0
def all_teams():
    all_public_teams = Team.query.filter_by(public_team=True)
    page = util.as_int(request.values.get('page'), on_fail=1)
    json_data = util.as_int(request.values.get('json'), on_fail=0)

    if json_data:
        teams_dict = {}
        for team in all_public_teams:
            team_dict = {}
            team_dict['name'] = team.name
            team_dict['tag'] = team.tag
            team_dict['flag'] = team.flag
            team_dict['logo'] = team.logo
            team_dict['players'] = filter(lambda x: bool(x), team.auths)
            team_dict['players_pref_names'] = filter(lambda x: bool(x),
                                                     team.preferred_names)
            teams_dict[team.id] = team_dict
        return jsonify(teams_dict)

    else:
        # Render teams page
        teams = all_public_teams.paginate(page, 20)
        editable = g.user is not None and util.is_super_admin(g.user)
        return render_template('teams.html',
                               user=g.user,
                               teams=teams,
                               my_teams=editable,
                               page=page,
                               owner=None)
示例#5
0
def teams_user(userid):
    user = User.query.get_or_404(userid)
    page = util.as_int(request.values.get('page'), on_fail=1)
    json_data = util.as_int(request.values.get('json'), on_fail=0)

    if json_data:
        teams_dict = {}
        for team in user.teams:
            team_dict = {}
            team_dict['name'] = team.name
            team_dict['tag'] = team.tag
            team_dict['flag'] = team.flag
            team_dict['logo'] = team.logo
            team_dict['players'] = filter(lambda x: bool(x), team.auths)
            team_dict['players_pref_names'] = filter(lambda x: bool(x),
                                                     team.preferred_names)
            teams_dict[team.id] = team_dict
        return jsonify(teams_dict)

    else:
        # Render teams page
        my_teams = (g.user is not None
                    and ((userid == g.user.id) or util.is_super_admin(g.user)))
        teams = user.teams.paginate(page, 20)
        return render_template('teams.html',
                               user=g.user,
                               teams=teams,
                               my_teams=my_teams,
                               page=page,
                               owner=user)
示例#6
0
 def can_edit(self, user):
     if not user:
         return False
     if self.user_id == user.id:
         return True
     if util.is_super_admin(user):
         return True
     return False
示例#7
0
def myservers():
    if not g.user:
        return redirect('/login')

    servers = GameServer.query.filter_by(
        user_id=g.user.id).order_by(-GameServer.id).limit(50)
    if util.is_super_admin(g.user):
        servers = GameServer.query.order_by(-GameServer.id)

    return render_template('servers.html', user=g.user, servers=servers)
示例#8
0
def super_admintools_check(user, match):
    if user is None:
        raise BadRequestError('You do not have access to this page')

    if not util.is_super_admin(user):
        raise BadRequestError('You do not have access to this page')

    if match.finished():
        raise BadRequestError('Match already finished')

    if match.cancelled:
        raise BadRequestError('Match is cancelled')
示例#9
0
def match(matchid):
    match = Match.query.get_or_404(matchid)
    # Begin Private/Public Match Implementation

    vetoes = Veto.query.filter_by(match_id=matchid)
    if match.server_id:
        server = GameServer.query.get_or_404(match.server_id)
    else:
        server = None
    team1 = Team.query.get_or_404(match.team1_id)
    team2 = Team.query.get_or_404(match.team2_id)
    check_private_or_public(g.user, match, team1, team2)

    map_stat_list = match.map_stats.all()
    completed = match.winner
    try:
        if server is not None and (completed is None and match.cancelled == 0):
            password = server.receive_rcon_value('sv_password')
            connect_string = str("steam://connect/") + str(server.ip_string) + str(":") + \
                str(server.port) + str("/") + str(password)
            gotv_port = server.receive_rcon_value('tv_port')
            gotv_string = str("steam://connect/") + str(server.ip_string) + str(":") + \
                str(gotv_port)
        else:
            connect_string = None
            gotv_string = None
    except util.RconError as e:
        connect_string = None
        gotv_string = None
        app.logger.info('Attempted to connect to server {}, but it is offline'
                        .format(server.ip_string))

    is_match_owner = False
    is_server_op = False
    has_admin_access = False
    has_super_admin_access = False
    if g.user:
        is_match_owner = (g.user.id == match.user_id)
        has_admin_access = (config_setting(
            'ADMINS_ACCESS_ALL_MATCHES') and util.is_admin(g.user))
        has_super_admin_access = util.is_super_admin(g.user)
        is_server_op = util.is_server_owner(g.user, server)
    return render_template(
        'match.html', user=g.user, admin_access=has_admin_access,
        match=match, team1=team1, team2=team2,
        map_stat_list=map_stat_list, completed=completed, connect_string=connect_string,
        gotv_string=gotv_string, super_admin_access=has_super_admin_access, vetoes=vetoes,
        server_owner=is_server_op, match_owner=is_match_owner)
示例#10
0
def server_delete(serverid):
    server = GameServer.query.get_or_404(serverid)
    is_owner = g.user and (g.user.id == server.user_id)
    is_sadmin = g.user and util.is_super_admin(g.user)
    if not is_owner:
        if not is_sadmin:
            raise BadRequestError('You do not have access to this server.')

    if server.in_use:
        raise BadRequestError('Cannot delete server when in use.')

    matches = g.user.matches.filter_by(server_id=serverid)
    for m in matches:
        m.server_id = None

    GameServer.query.filter_by(id=serverid).delete()
    db.session.commit()
    return redirect('myservers')
示例#11
0
def server_create():
    if not g.user:
        return redirect('/login')

    form = ServerForm(request.form)
    if request.method == 'POST':
        num_servers = g.user.servers.count()
        max_servers = config_setting('USER_MAX_SERVERS')
        if max_servers >= 0 and num_servers >= max_servers and not (
                util.is_admin(g.user) or util.is_super_admin(g.user)):
            flash('You already have the maximum number of servers ({}) stored'.
                  format(num_servers))

        elif form.validate():
            mock = config_setting('TESTING')
            data = form.data
            if not mock:
                encRcon = util.encrypt(dbKey, str(data['rcon_password']))
            else:
                encRcon = data['rcon_password']

            server = GameServer.create(
                g.user, data['display_name'], data['ip_string'], data['port'],
                encRcon, data['public_server'] and util.is_admin(g.user))

            if mock or util.check_server_connection(server, dbKey):
                db.session.commit()
                app.logger.info('User {} created server {}'.format(
                    g.user.id, server.id))
                return redirect('/myservers')
            else:
                db.session.remove()
                flash('Failed to connect to server')

        else:
            flash_errors(form)

    return render_template('server_create.html',
                           user=g.user,
                           form=form,
                           edit=False,
                           is_admin=util.is_admin(g.user))
示例#12
0
def check_private_or_public(user, match, team1, team2):
    if match.is_private_match():
        if not user:
            raise BadRequestError("Please login before viewing this match.")
        # Get team lists, and check if logged in user is part of match.
        if (user.id == match.user_id) or (config_setting(
                'ADMINS_ACCESS_ALL_MATCHES') and util.is_admin(user)) or util.is_super_admin(user):
            isPlayer = False
            playerstats_steam = [r.steam_id for r in PlayerStats.query.filter(
                PlayerStats.match_id == match.id)]
            playerList = list(
                set(team1.auths + team2.auths + playerstats_steam))
            app.logger.info("Our list: {}".format(playerList))
            if (config_setting('ADMINS_ACCESS_ALL_MATCHES') and util.is_admin(user)) or util.is_super_admin(user):
                isPlayer = True
            else:
                for player in playerList:
                    if user.steam_id == player:
                        isPlayer = True
                        break
            if not isPlayer:
                raise BadRequestError(
                    "You cannot view this match as you were not a part of it!")
示例#13
0
def season_create():
    if not g.user:
        return redirect('/login')

    form = SeasonForm(request.form)

    if request.method == 'POST':
        num_seasons = g.user.seasons.count()
        max_seasons = config_setting('USER_MAX_SEASONS')
        if max_seasons >= 0 and num_seasons >= max_seasons and not (util.is_admin(g.user) or util.is_super_admin(g.user)):
            flash('You already have the maximum number of seasons ({}) created'.format(
                num_seasons))

        elif form.validate():
            season = Season.create(
                g.user, form.data['season_title'],
                form.data['start_date'], form.data['end_date'])

            db.session.commit()
            app.logger.info('User {} created season {}'
                            .format(g.user.id, season.id))

            return redirect('/myseasons')

        else:
            get5.flash_errors(form)

    return render_template(
        'season_create.html', form=form, user=g.user)
示例#14
0
def match_create():
    if not g.user:
        return redirect('/login')

    form = MatchForm(request.form)
    form.add_teams(g.user)
    form.add_servers(g.user)
    form.add_seasons()

    if request.method == 'POST':
        num_matches = g.user.matches.count()
        max_matches = config_setting('USER_MAX_MATCHES')
        season_id = None

        if max_matches >= 0 and num_matches >= max_matches and not (util.is_admin(g.user) or util.is_super_admin(g.user)):
            flash('You already have the maximum number of matches ({}) created'.format(
                num_matches))

        elif form.validate():
            mock = config_setting('TESTING')

            server = GameServer.query.get_or_404(form.data['server_id'])

            match_on_server = g.user.matches.filter_by(
                server_id=server.id, end_time=None, cancelled=False).first()

            server_available = False
            json_reply = None

            if g.user.id != server.user_id and not server.public_server:
                server_available = False
                message = 'This is not your server!'
            elif match_on_server is not None:
                server_available = False
                message = 'Match {} is already using this server'.format(
                    match_on_server.id)
            elif mock:
                server_available = True
                message = 'Success'
            else:
                json_reply, message = util.check_server_avaliability(
                    server, dbKey)
                server_available = (json_reply is not None)

            if server_available:
                skip_veto = 'preset' in form.data['series_type']
                try:
                    max_maps = int(form.data['series_type'][2])
                except ValueError:
                    max_maps = 1

                if form.data['season_selection'] != 0:
                    season_id = form.data['season_selection']

                # Series Score Feature.
                team1_series_score = form.data[
                    'team1_series_score'] if not None else 0
                team2_series_score = form.data[
                    'team2_series_score'] if not None else 0
                # End Series Score Feature.

                # Spectator Feature
                specList = []
                if form.data['spectator_string']:
                    for auth in form.data['spectator_string'].split():
                        suc, new_auth = steamid.auth_to_steam64(auth)
                        if suc:
                            specList.append(new_auth)
                if not specList:
                    specList = None
                # End Spectator Feature

                match = Match.create(
                    g.user, form.data['team1_id'], form.data['team2_id'],
                    form.data['team1_string'], form.data['team2_string'],
                    max_maps, skip_veto,
                    form.data['match_title'], form.data['veto_mappool'],
                    season_id, form.data['side_type'],
                    form.data['veto_first'], form.data['server_id'],
                    team1_series_score, team2_series_score, specList,
                    form.data['private_match'], form.data['enforce_teams'])

                # Save plugin version data if we have it
                if json_reply and 'plugin_version' in json_reply:
                    match.plugin_version = json_reply['plugin_version']
                else:
                    match.plugin_version = 'unknown'

                server.in_use = True

                db.session.commit()
                app.logger.info('User {} created match {}, assigned to server {}'
                                .format(g.user.id, match.id, server.id))

                if mock or match.send_to_server():
                    return redirect('/mymatches')
                else:
                    flash('Failed to load match configs on server')
            else:
                flash(message)

        else:
            get5.flash_errors(form)

    return render_template(
        'match_create.html', form=form, user=g.user, teams=g.user.teams,
        match_text_option=config_setting('CREATE_MATCH_TITLE_TEXT'))