Beispiel #1
0
def profile(accountid):
    account = db.session.query(Account).get(accountid)
    if account is None:
        flask.abort(404, "Account not found!")

    max_restriction_level = 0
    if perm_manager.get_permission('view_notes_low').can():
        max_restriction_level = 100
    if perm_manager.get_permission('view_notes_med').can():
        max_restriction_level = 200
    if perm_manager.get_permission('view_notes_high').can():
        max_restriction_level = 500

    criterion = (AccountNote.accountID == accountid)

    if not perm_manager.get_permission("view_notes_all").can():
        criterion = criterion & (AccountNote.restriction_level <
                                 max_restriction_level)

    notes = db.session.query(AccountNote).filter(criterion).all()

    return render_template('account/profile.html',
                           account=account,
                           notes=notes,
                           note_renderer=render_note_text)
Beispiel #2
0
def delete_event_id(event_id):
    # if they are council they can delete everything
    event = db.session.query(CalendarEvent).get(event_id)
    if perm_manager.get_permission('calendar_event_delete_other').can():
        logger.info(
            "%s with id %d is deleting event Title[%s] by Account[%s, %d]",
            current_user.username, current_user.id, event.eventTitle,
            event.creator.username, event.creator.id)
        db.session.delete(event)
        db.session.commit()
        return make_response("Event with id[" + str(event_id) + "] deleted",
                             200)

    elif event.creator.id == current_user.id:
        logger.info("%s with id %d is deleting how own event Title[%s]",
                    current_user.username, current_user.id, event.eventTitle)
        db.session.delete(event)
        db.session.commit()
        return make_response("You successfully deleted your own event", 200)
    else:
        logger.error("%s tried to delete event %d not owned by him",
                     current_user.username, event.eventID)
        return make_response(
            "You are not allowed to delete other peoples events, and this does not seem to be your event!",
            403)
Beispiel #3
0
def accounts_download_csv() -> Response:
    def iter_accs(data):
        for account in data:
            for ci, char in enumerate(account.characters):
                if ci > 0:
                    yield ", " + char.eve_name
                else:
                    yield char.eve_name
            yield '\n'

    permission = perm_manager.get_permission('include_in_accountlist')
    include_check = (Account.disabled == False)
    role_check = None
    for role_need in permission.needs:
        if role_need.method != 'role':
            continue
        if role_check is None:
            role_check = (Role.name == role_need.value)
        else:
            role_check = role_check | (Role.name == role_need.value)

    include_check = (include_check & role_check)

    # noinspection PyPep8
    accs = db.session.query(Account).options(joinedload('characters')).join(
        Account.roles).filter(include_check).order_by(Account.username).all()

    response = Response(iter_accs(accs), mimetype='text/csv')
    response.headers[
        'Content-Disposition'] = 'attachment; filename=accounts.csv'
    return response
def history_since():
    laststamp = int(request.args.get('last'))
    logger.info("last=%s", str(laststamp))
    since = datetime.utcfromtimestamp(laststamp / 1000.0)
    logger.info("Looking for %s", str(since))
    tnow = datetime.utcnow()

    if not perm_comp_unlimited.can():
        if perm_manager.get_permission('comphistory_view_240').can():
            max_time = timedelta(minutes=240)
            if tnow - since > max_time:
                since = tnow - max_time
        else:
            max_time = timedelta(minutes=30)
            if tnow - since > max_time:
                since = tnow - max_time

    new_history_entries = db.session.query(HistoryEntry).filter(
        HistoryEntry.time > since).all()

    # do access tracking here
    if get_access_duration(current_user.id, timedelta(hours=6),
                           datetime.utcnow()) > timedelta(days=4):
        logger.error(
            f"User {current_user.username}"
            f" is requesting fits since over 4days, without a break of at least 6h"
        )

    return jsonify(make_history_json(new_history_entries))
Beispiel #5
0
def profile_by_name(username):
    account = db.session.query(Account).filter(
        Account.username == username).first()
    if account is None:
        flask.abort(404, "Account not found!")
    notes = None
    if perm_manager.get_permission('view_notes').can():
        notes = db.session.query(AccountNote).filter(
            AccountNote.accountID == account.id).all()
    return render_template('account/profile.html',
                           account=account,
                           notes=notes)
Beispiel #6
0
def get_index():
    # noinspection PyPep8
    accounts: Sequence[Account] = db.session.query(Account).filter(
        Account.disabled == False).all()

    event_query = db.session.query(CalendarEvent).filter(
        CalendarEvent.eventTime > datetime.utcnow())
    if not perm_manager.get_permission('calendar_event_see_all').can():
        event_query = event_query \
            .filter((CalendarEvent.eventCreatorID == current_user.id)
                    | (CalendarEvent.backseats.any(Account.id == current_user.id))
                    | (CalendarEvent.organizers.any(Account.id == current_user.id)))

    event_query.order_by(CalendarEvent.eventTime.asc())
    events = event_query.all()

    categories = db.session.query(CalendarEventCategory).all()

    return render_template('calendar/settings.html',
                           accounts=accounts,
                           events=events,
                           categories=categories)
            access_duration_track[user_id] = (first_access, access_now)
            return access_now - first_access
    else:
        access_duration_track[user_id] = (access_now, access_now)
        return timedelta(minutes=0)


perm_manager.define_permission('notification_send')
perm_manager.define_permission('comphistory_view')
perm_manager.define_permission('comphistory_unlimited')
perm_manager.define_permission('trainee')
perm_manager.define_permission('fits_approve')
perm_manager.define_permission('fits_view')
perm_manager.define_permission('comphistory_view_240')

perm_notify_send = perm_manager.get_permission('notification_send')
perm_comp_view = perm_manager.get_permission('comphistory_view')
perm_comp_unlimited = perm_manager.get_permission('comphistory_unlimited')
perm_trainee = perm_manager.get_permission('trainee')
perm_approve = perm_manager.get_permission('fits_approve')
perm_fits_view = perm_manager.get_permission('fits_view')


@bp.route("/player/<int:player_id>/notification", methods=["POST"])
@login_required
@perm_notify_send.require(http_exception=401)
def send_notification(player_id):
    waitlist_id = int(request.form['waitlistID'])
    send_notifiaction_to_player(player_id, waitlist_id,
                                "The FC is looking for you")
    return make_response("Notification send", 200,
Beispiel #8
0
from flask_login import login_required
from gevent import Greenlet
from sqlalchemy import and_, or_, func

from waitlist import db
from waitlist.blueprints.settings import add_menu_entry
from waitlist.permissions import perm_manager
from waitlist.storage.database import InvType, Character, Shipfit, HistoryEntry, HistoryFits, Account

bp = Blueprint('settings_overview', __name__)
logger = logging.getLogger(__name__)


perm_manager.define_permission('settings_access')

perm_access = perm_manager.get_permission('settings_access')


class StatCache(object):
    def __init__(self) -> None:
        self.__data: Dict[str, Any] = {}

    def has_cache_item(self, key: str) -> bool:
        if key not in self.__data:
            return False

        if self.__data[key]['datetime'] < datetime.utcnow():
            return False
        return True

    def get_cache_item(self, key: str) -> Any:
Beispiel #9
0
def fleet_status_set(gid: int) -> Response:
    action = request.form['action']
    group = db.session.query(WaitlistGroup).get(gid)
    if action == "status":
        text = request.form['status']
        xup = request.form.get('xup', 'off')
        influence = request.form.get('influence')
        influence = False if influence is None else True
        xup_text = "closed"
        if xup == 'off':
            xup = False
        else:
            xup = True
            xup_text = "open"

        if xup != group.enabled:
            group.enabled = xup
            logger.info("XUP was set to %s by %s", xup, current_user.username)

        if influence != group.influence:
            group.influence = influence
            logger.info("Influence setting of grp %s was changed to %s by %s",
                        group.groupID, influence, current_user.username)

        if perm_custom_status.can():
            group.status = text
            logger.info("Status was set to %s by %s", group.status,
                        current_user.username)
            flash("Status was set to " + text + ", xup is " + xup_text,
                  "success")

        else:
            if text == "Running" or text == "Down" or text == "Forming":
                group.status = text
                logger.info("Status was set to %s by %s", group.status,
                            current_user.username)
                flash("Status was set to " + text + ", xup is " + xup_text,
                      "success")
            else:
                logger.info(
                    "%s tried to set the status to %s and did not have the rights",
                    current_user.username, group.status)
                flash(
                    "You do not have the rights to change the status to " +
                    text, "danger")
                flash("XUP is now " + xup_text, "success")
    elif action == "fc":
        group.fcs.append(current_user)

        with open("set_history.log", "a+") as f:
            f.write('{} - {} sets them self as FC\n'.format(
                datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                current_user.username))

        flash("You added your self to FCs " + current_user.get_eve_name(),
              "success")
    elif action == "manager":
        group.manager.append(current_user)

        with open("set_history.log", "a+") as f:
            f.write('{} - {} sets them self as Fleet Manager\n'.format(
                datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                current_user.username))

        flash("You added your self to manager " + current_user.get_eve_name(),
              "success")
    elif action == "manager-remove":
        account_id = int(request.form['accountID'])
        account = db.session.query(Account).get(account_id)

        with open("set_history.log", "a+") as f:
            f.write('{} - {} is removed as Fleet Manager by {}\n'.format(
                datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                account.username, current_user.username))

        try:
            group.manager.remove(account)
        except ValueError:
            pass
    elif action == "fc-remove":
        account_id = int(request.form['accountID'])
        account = db.session.query(Account).get(account_id)

        with open("set_history.log", "a+") as f:
            f.write('{} - {} is removed as FC by {}\n'.format(
                datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                account.username, current_user.username))

        try:
            group.fcs.remove(account)
        except ValueError:
            pass
    elif action == "add-backseat":
        group.backseats.append(current_user)

        with open("set_history.log", "a+") as f:
            f.write('{} - {} sets them self as Backseat\n'.format(
                datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                current_user.username))

        flash("You added your self as Backseat " + current_user.get_eve_name(),
              "success")
    elif action == "remove-backseat":
        account_id = int(request.form['accountID'])
        account = db.session.query(Account).get(account_id)
        with open("set_history.log", "a+") as f:
            f.write('{} - {} is removed as Backseat by {}\n'.format(
                datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
                account.username, current_user.username))

        try:
            group.backseats.remove(account)
        except ValueError:
            pass

    elif action == "check-in":
        # check if in a fleet
        if member_info.is_member_in_fleet(current_user.get_eve_id()):
            postfix = "was found in fleet"
        else:
            postfix = "was not found in fleet"

        with open("set_history.log", "a+") as f:
            f.write(
                f'{datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")}'
                f' - {current_user.username} checked in for activity, {postfix}\n'
            )
        flash(
            f"Your activity report has been submitted {current_user.username}",
            "success")

    elif action == "change_display_name":
        # if we have no permissions to set a custom name, we are done
        if not perm_manager.get_permission('fleet_custom_display_name').can():
            flash(
                f"{current_user.username} has no permissions to set a custom display name for a waitlist!",
                "danger")
            return redirect(url_for(".fleet"), code=303)

        # TODO: this should be configurable and also set the dropdown options
        unrestricted_display_names = ["Headquarter", "Assault", "Vanguard"]
        display_name = request.form.get("display_name", None)

        # if we are not given a valid new custom name we are done
        if display_name is None:
            flash(f"No valid new display name given (given was None)",
                  "danger")
            return redirect(url_for(".fleet"), code=303)

        # it is not a unresticted name and we do not have the power to set abitrary names, then we are done
        if not ((display_name in unrestricted_display_names) or perm_manager.
                get_permission('fleet_custom_display_name_all').can()):
            flash(
                f"You gave no unrestricted display name and do not have the power to set abitrary names!",
                "danger")
            return redirect(url_for(".fleet"), code=303)

        # we checked that we are allowed to do this, let do it and logg it
        group.displayName = display_name
        logging.info(
            f"{current_user.username} set the displayName of group with id={group.groupID} to {display_name}"
        )

    db.session.commit()

    event = StatusChangedSSE(group)
    send_server_sent_event(event)

    return redirect(url_for(".fleet"), code=303)
Beispiel #10
0
        for type_id in rest_typeids:
            invtype = db.session.query(InvType).get(type_id)
            check.check_rest_types.append(invtype)
        for group_id in rest_invgroupids:
            check.check_rest_groups.append(
                db.session.query(InvGroup).get(group_id))
        for mgroup_id in rest_mgroupids:
            check.check_rest_market_groups.append(
                db.session.query(MarketGroup).get(mgroup_id))

    db.session.commit()
    return redirect(
        url_for('.collection_edit',
                collection_id=check.collection.checkCollectionID))


@bp.route('/check/delete', methods=['POST'])
@login_required
@perm_manager.require('ship_assignment_edit')
def check_delete():
    check_id = int(request.form['check_id'])
    check = db.session.query(ShipCheck).get(check_id)
    db.session.delete(check)
    db.session.commit()
    return redirect(request.referrer)


add_menu_entry('ship_assignment.ship_assignments',
               lazy_gettext('Ship Classification'),
               perm_manager.get_permission('ship_assignment_edit').can)
Beispiel #11
0
    acc.disabled = status
    db.session.commit()
    return "OK"


@bp.route("/api/account/<int:acc_id>", methods=["DELETE"])
@login_required
@perm_manager.require('admin')
def api_account_delete(acc_id: int) -> Response:
    db.session.query(Account).filter(Account.id == acc_id).delete()
    db.session.commit()
    return flask.jsonify(status="OK")


add_menu_entry('accounts.accounts', lazy_gettext('Accounts'),
               perm_manager.get_permission('accounts_edit').can)
add_menu_entry('accounts.account_self', lazy_gettext('Own Settings'),
               lambda: True)


@login_required
@perm_manager.require('settings_access')
def alt_verification_handler(code: str) -> None:
    # this throws exception and exists this function
    if current_user.type != 'account':
        flask.abort(403, "You are not on an account.")

    auth = authorize(code)

    access_token = auth['access_token']
    refresh_token = auth['refresh_token']
Beispiel #12
0
from waitlist.blueprints.settings import add_menu_entry
from waitlist.permissions import perm_manager

perm_manager.define_permission('calendar_event_add')

add_menu_entry('calendar_settings.get_index', 'Events',
               perm_manager.get_permission('calendar_event_add').can)
Beispiel #13
0
from waitlist.data.sse import FitAddedSSE, EntryAddedSSE, EntryRemovedSSE,\
    FitRemovedSSE, GongSSE, Subscription, add_subscription,\
    remove_subscription,\
    InviteMissedSSE, StatusChangedSSE, ReloadPageSSE
from flask.wrappers import Response

from waitlist.permissions import perm_manager
from waitlist.base import db
from time import sleep

bp = Blueprint('api_sse', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('fits_view')

perm_fits_view = perm_manager.get_permission('fits_view')


def event_gen(sub: Subscription):
    if not isinstance(sub, Subscription):
        raise TypeError("Not a Subscription Object")
    add_subscription(sub)
    try:
        while True:
            event = sub.get()
            logger.debug("Event " + sub.encode(event))
            yield sub.encode(event)
    finally:
        remove_subscription(sub)

Beispiel #14
0
@bp.route("/add_role", methods=['POST'])
@login_required
@perm_manager.require(StaticPermissions.ADMIN)
def add_role() -> Response:
    role_name: str = request.form['role_name']
    role_display_name: str = request.form['role_display_name']

    PermissionManager.add_role(role_name, role_display_name)
    send_role_created(add_role, current_user.id, role_name, role_display_name)

    return redirect(url_for('.view_permissions'), code=303)


add_menu_entry(
    'settings_permissions.view_permissions', lazy_gettext('Permissions'),
    lambda: perm_manager.get_permission(StaticPermissions.ADMIN).can())


@bp.route("/remove_role", methods=['POST'])
@login_required
@perm_manager.require(StaticPermissions.ADMIN)
def remove_role() -> Response:
    role_id: int = int(request.form['role_id'])
    role: Role = PermissionManager.get_role(role_id)
    if role is None:
        flash(
            gettext('Role with id=%(role_id)d was not found, failed to delete',
                    role_id=role_id), "warning")
    else:
        role_display_name: str = role.displayName
        role_name: str = role.name
Beispiel #15
0
from waitlist.blueprints.settings import add_menu_entry
from waitlist.permissions import perm_manager
from waitlist.storage.database import Ban, Whitelist, Character
from waitlist.utility.eve_id_utils import get_character_by_name
from waitlist.utility.utils import get_info_from_ban

bp = Blueprint('bans', __name__)
logger = logging.getLogger(__name__)


perm_manager.define_permission('bans_edit')
perm_manager.define_permission('bans_edit_multiple')
perm_manager.define_permission('bans_custom_name')
perm_manager.define_permission('bans_custom_reason')

perm_custom_name = perm_manager.get_permission('bans_custom_name')
perm_custom_reason = perm_manager.get_permission('bans_custom_reason')


@bp.route("/", methods=["GET"])
@login_required
@perm_manager.require('bans_edit')
def bans():
    db_bans = db.session.query(Ban).order_by(asc(Ban.name)).all()
    return render_template("settings/bans.html", bans=db_bans)


@bp.route("/bans_change", methods=["POST"])
@login_required
@perm_manager.require('bans_edit_multiple')
def bans_change():
from waitlist.permissions import perm_manager
from waitlist.storage.database import Ticket
from waitlist.base import db
import flask
from datetime import datetime, timedelta
from sqlalchemy.sql.expression import desc
from flask_babel import gettext, lazy_gettext

logger = logging.getLogger(__name__)

feedback = Blueprint('feedback', __name__)

perm_manager.define_permission('feedback_view')
perm_manager.define_permission('feedback_edit')

perm_view = perm_manager.get_permission('feedback_view')
perm_edit = perm_manager.get_permission('feedback_edit')


@feedback.route("/", methods=["GET"])
@login_required
def index() -> Response:
    # get old feedback and input data back
    char_id = current_user.get_eve_id()
    tickets = db.session.query(Ticket).filter(
        Ticket.characterID == char_id).all()
    return render_template("feedback/index.html", tickets=tickets)


@feedback.route("/", methods=["POST"])
@login_required
Beispiel #17
0
from waitlist.permissions import perm_manager
from waitlist.utility.settings import sget_resident_mail,\
    sget_tbadge_mail, sset_tbadge_mail, sset_resident_mail, sset_resident_topic,\
    sset_tbadge_topic, sset_other_mail, sset_other_topic, sget_tbadge_topic,\
    sget_other_mail, sget_resident_topic, sget_other_topic
from flask.globals import request
from flask.helpers import flash, url_for
from werkzeug.utils import redirect
from waitlist.base import app
from flask_babel import gettext, lazy_gettext

bp = Blueprint('settings_mail', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('welcome_mail_edit')
perm_edit = perm_manager.get_permission('welcome_mail_edit')


@app.context_processor
def inject_data():
    return dict()


@bp.route("/")
@login_required
@perm_edit.require()
def index():
    mails = {
        'resident': [sget_resident_mail(),
                     sget_resident_topic()],
        'tbadge': [sget_tbadge_mail(), sget_tbadge_topic()],
Beispiel #18
0
from waitlist.permissions import perm_manager
from waitlist.storage.database import Ban, Whitelist, Character, CharacterTypes
from waitlist.utility.eve_id_utils import get_character_by_name, get_char_corp_all_name_by_id_and_type
from waitlist.utility.utils import get_info_from_ban
from flask_babel import lazy_gettext, gettext
from waitlist.utility.outgate.exceptions import ApiException

bp = Blueprint('bans', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('bans_edit')
perm_manager.define_permission('bans_edit_multiple')
perm_manager.define_permission('bans_custom_name')
perm_manager.define_permission('bans_custom_reason')

perm_custom_name = perm_manager.get_permission('bans_custom_name')
perm_custom_reason = perm_manager.get_permission('bans_custom_reason')


@bp.route("/", methods=["GET"])
@login_required
@perm_manager.require('bans_edit')
def bans():
    db_bans = db.session.query(Ban).all()

    return render_template("settings/bans.html", bans=db_bans)


@bp.route("/bans_change", methods=["POST"])
@login_required
@perm_manager.require('bans_edit_multiple')
Beispiel #19
0
def account_edit():
    acc_id = int(request.form['account_id'])
    acc_name = request.form['account_name']

    note = request.form['change_note'].strip()

    acc_roles = request.form.getlist('account_roles')

    char_name = request.form['default_char_name']
    char_name = char_name.strip()
    if char_name == "":
        char_name = None

    acc = db.session.query(Account).filter(Account.id == acc_id).first()
    if acc is None:
        return flask.abort(400)

    if acc.username != acc_name:
        old_name: str = acc.username
        acc.username = acc_name
        send_account_name_change(account_edit, current_user.id, acc.id,
                                 old_name, acc_name, note)

    # if there are roles, add new ones, remove the ones that aren't there
    if len(acc_roles) > 0:
        roles_new = {}
        for r in acc_roles:
            roles_new[r] = True

        # db_roles = session.query(Role).filter(or_(Role.name == name for name in acc_roles)).all()
        roles_to_remove = []
        for role in acc.roles:
            if role.name in roles_new:
                del roles_new[
                    role.name]  # remove because it is already in the db
            else:
                # remove the roles because it not submitted anymore
                # only remove admin if current user is an admin
                if role.name == StaticRoles.ADMIN and not perm_manager.get_permission(
                        StaticPermissions.ADMIN).can():
                    continue
                roles_to_remove.append(role)  # mark for removal

        for role in roles_to_remove:
            acc.roles.remove(role)

        # if it is not an admin remove admin role from new roles
        if not perm_manager.get_permission('admin').can():
            if 'admin' in roles_new:
                del roles_new['admin']

        # add remaining roles
        if len(roles_new) > 0:
            new_db_roles = db.session.query(Role).filter(
                or_(Role.name == name for name in roles_new))
            for role in new_db_roles:
                acc.roles.append(role)
        if len(roles_new) > 0 or len(roles_to_remove) > 0:
            send_roles_changed(account_edit, acc.id, current_user.id,
                               [x for x in roles_new],
                               [x.name for x in roles_to_remove], note)
    else:
        # make sure all roles are removed
        roles_to_remove = []
        for role in acc.roles:
            # only remove admin if current user is an admin
            if role.name == StaticRoles.ADMIN and not perm_manager.get_permission(
                    StaticPermissions.ADMIN).can():
                continue
            roles_to_remove.append(role)

        if len(roles_to_remove) > 0:
            for role in roles_to_remove:
                acc.roles.remove(role)
            db.session.flush()
            send_roles_changed(account_edit, acc.id, current_user.id, [],
                               [x.name for x in roles_to_remove], note)

    if char_name is not None:
        try:
            char_info = outgate.character.get_info_by_name(char_name)
            if char_info is None:
                flash(
                    gettext(
                        "Character with name %(char_name)s could not be found!",
                        char_name=char_name), 'danger')
            else:
                char_id = char_info.id
                # find out if there is a character like that in the database
                # or create it
                character = get_character_by_id(char_id)

                # check if character is linked to this account
                link = db.session.query(linked_chars) \
                    .filter((linked_chars.c.id == acc_id) & (linked_chars.c.char_id == char_id)).first()
                if link is None:
                    acc.characters.append(character)
                    send_alt_link_added(account_edit, current_user.id, acc.id,
                                        character.id)

                db.session.flush()
                acc.current_char = char_id
        except ApiException as e:
            flash(
                gettext("Could not execute action, ApiException %(ex)s", ex=e),
                'danger')

    db.session.commit()
    return redirect(url_for('.accounts'), code=303)
Beispiel #20
0
    send_server_sent_event, FitAddedSSE, FitRemovedSSE, EntryRemovedSSE
import flask
from sqlalchemy.sql.expression import desc
from waitlist.utility.history_utils import create_history_object
from waitlist.blueprints.api import fittings as fit_api

bp_waitlist = Blueprint('fittings', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('fleet_management')
perm_manager.define_permission('fits_approve')
perm_manager.define_permission('developer_tools')
perm_manager.define_permission('comphistory_view')
perm_manager.define_permission('comphistory_unlimited')

perm_fleet_manage = perm_manager.get_permission('fleet_management')

perm_dev = perm_manager.get_permission('developer_tools')

perm_comp_view = perm_manager.get_permission('comphistory_view')
perm_comp_unlimited = perm_manager.get_permission('comphistory_unlimited')


@bp_waitlist.route("/move_to_waitlist", methods=["POST"])
@login_required
@perm_fleet_manage.require(http_exception=401)
def move_to_waitlists():
    """
    Move a whole entry to a the corresponding waitlists
    """
Beispiel #21
0
from flask import Response, request, make_response, jsonify
from flask_login import login_required

from waitlist.base import db
from waitlist.blueprints.swagger_api.characters import bp_v1
from waitlist.blueprints.swagger_api.models import errors
from waitlist.permissions import perm_manager
from waitlist.storage.database import Character

perm_manager.define_permission('change_character_data')
perm_change_character_data = perm_manager.get_permission(
    'change_character_data')


@login_required
@perm_change_character_data.require()
@bp_v1.route('/<int:character_id>/', methods=['PUT'])
def character_put_v1(character_id: int) -> Response:
    """
    file: character_put_v1.yml
    """
    owner_hash = request.form.get('owner_hash')
    character: Character = db.session.query(Character).get(character_id)
    if character is None:
        resp: Response = jsonify(
            errors.error_404(
                f'Character with id={character_id} does not exist.'))
        resp.status_code = 404
        return resp

    character.owner_hash = owner_hash
Beispiel #22
0
from os import path

from werkzeug.utils import secure_filename, redirect

from waitlist.blueprints.settings import add_menu_entry
from waitlist import app
from waitlist.permissions import perm_manager
from waitlist.utility import sde

bp = Blueprint('sde', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('static_data_import')
perm_manager.define_permission('developer_tools')

perm_access = perm_manager.get_permission('static_data_import')
perm_developer = perm_manager.get_permission('developer_tools')


@bp.route("/sde/update/typeids", methods=["POST"])
@login_required
@perm_access.require(http_exception=401)
def update_type_ids():
    f = request.files['file']
    if f and (f.filename.rsplit('.', 1)[1] == "bz2"
              or f.filename.rsplit('.', 1)[1] == "yaml"):
        filename = secure_filename(f.filename)
        dest_name = path.join(app.config['UPLOAD_FOLDER'], filename)
        if path.isfile(dest_name):
            os.remove(dest_name)
        f.save(dest_name)
Beispiel #23
0
from waitlist import db
from waitlist.storage.database import WaitlistGroup, Account, IncursionLayout, Station, SolarSystem, Constellation, \
    WaitlistEntry
from waitlist.utility.eve_id_utils import get_constellation, get_system, get_station
from waitlist.utility.fleet import member_info

bp = Blueprint('fleetoptions', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('fleet_management')
perm_manager.define_permission('fleet_custom_status')
perm_manager.define_permission('fleet_location_edit')
perm_manager.define_permission('fleet_custom_display_name')
perm_manager.define_permission('fleet_custom_display_name_all')

perm_management = perm_manager.get_permission('fleet_management')
perm_custom_status = perm_manager.get_permission('fleet_custom_status')
perm_fleetlocation_edit = perm_manager.get_permission('fleet_location_edit')


@bp.route('/')
@login_required
@perm_management.require(http_exception=401)
def fleet() -> Response:
    groups = db.session.query(WaitlistGroup).all()
    return render_template("settings/fleet.html",
                           user=current_user,
                           groups=groups,
                           scramble=config.scramble_names)

Beispiel #24
0
from waitlist.blueprints.settings import add_menu_entry
from waitlist.permissions import perm_manager
from waitlist.storage.database import TeamspeakDatum
from waitlist.ts3.connection import change_connection
from waitlist.utility.settings import sget_active_ts_id, sset_active_ts_id
from waitlist.utility.config import disable_teamspeak
from flask_babel import gettext, lazy_gettext

bp = Blueprint('teamspeak', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('teamspeak_change')
perm_manager.define_permission('teamspeak_view')
perm_manager.define_permission('teamspeak_edit')

perm_change_server = perm_manager.get_permission('teamspeak_change')\
    .union(perm_manager.get_permission('teamspeak_edit'))
perm_view_server = perm_change_server
perm_edit_server = perm_manager.get_permission('teamspeak_edit')


@bp.route("/ts", methods=["GET"])
@login_required
@perm_view_server.require()
def teamspeak():
    active_ts_setting_id = sget_active_ts_id()
    active_ts_setting = None
    if active_ts_setting_id is not None:
        active_ts_setting = db.session.query(TeamspeakDatum).get(
            active_ts_setting_id)

    all_ts_settings = db.session.query(TeamspeakDatum).all()
from waitlist.utility.outgate.character.info import get_character_fleet_id
from waitlist.utility.swagger import esi_scopes
from waitlist.utility.swagger.eve.fleet import EveFleetEndpoint
from waitlist.utility.swagger.eve.fleet.models import FleetMember
from waitlist.utility.swagger.eve import ESIResponse
from waitlist.utility.swagger.eve.fleet.responses import EveFleet
from waitlist.signal import send_added_first_fleet
from flask_babel import gettext

bp = Blueprint('fleet', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('fleet_management')
perm_manager.define_permission('developer_tools')

fleets_manage = perm_manager.get_permission('fleet_management')
perm_dev = perm_manager.get_permission('developer_tools')


@login_required
@fleets_manage.require(http_exception=401)
def handle_new_fleet_token(tokens):
    add_token(tokens)
    return redirect(url_for('fleet.take_over_fleet'))


'''
register sso handler
'''
add_sso_handler('get_fleet_token', handle_new_fleet_token)
'''
Beispiel #26
0
from typing import Iterable, Sequence

from waitlist.permissions import perm_manager
from waitlist.storage.database import AccountNote, RoleChangeEntry
from waitlist import db
from waitlist.storage.database import Role, Account
from sqlalchemy.sql.expression import or_
from waitlist.signal.signals import roles_changed_sig, roles_added_sig

perm_manager.define_permission('trainee')

perm_trainee = perm_manager.get_permission('trainee')


# noinspection PyUnusedLocal
@roles_changed_sig.connect
def on_roles_changed(sender, to_id: int, by_id: int, added_roles: Sequence[str],
                     removed_roles: Sequence[str], note: str) -> None:
    if len(added_roles) <= 0 and len(removed_roles) <= 0 and note == "":
        return
    history_entry = AccountNote(accountID=to_id, byAccountID=by_id, note=note)
    if len(added_roles) > 0:
        db_roles = db.session.query(Role).filter(or_(Role.name == name for name in added_roles)).all()
        for role in db_roles:
            # get role from db
            role_change = RoleChangeEntry(added=True, role=role)
            history_entry.role_changes.append(role_change)
        
    if len(removed_roles) > 0:
        db_roles = db.session.query(Role).filter(or_(Role.name == name for name in removed_roles)).all()
        for role in db_roles:
def get_permission():
    return perm_manager.get_permission('change_fleet_motd')
Beispiel #28
0
from flask.globals import request
from flask.helpers import flash, url_for
from werkzeug.utils import redirect
from waitlist.permissions import perm_manager

bp = Blueprint('settings_inserts', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('inserts_edit')


@bp.route("/")
@login_required
@perm_manager.require('inserts_edit')
def index() -> Response:
    data = {'header': sget_insert('header')}
    return render_template("settings/inserts.html", inserts=data)


@bp.route("/change/<string:type_>", methods=["POST"])
@login_required
@perm_manager.require('inserts_edit')
def change(type_) -> Response:
    if type_ == "header":
        content = request.form.get('content')
        sset_insert('header', content)
        flash("Header Insert Saved")
    return redirect(url_for('settings_inserts.index'))

add_menu_entry('settings_inserts.index', 'Page Inserts', perm_manager.get_permission('inserts_edit').can)
Beispiel #29
0
from werkzeug.utils import redirect
from flask.globals import request, session, _app_ctx_stack
from flask_seasurf import randrange
import hashlib

from waitlist.permissions import perm_manager
from waitlist.utility.config import crest_return_url, crest_client_id
import flask
from urllib.parse import urlencode

bp = Blueprint('fc_sso', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('fleet_management')

perm_fleet_manage = perm_manager.get_permission('fleet_management')

sso_handler = {}


def add_sso_handler(key: str, handler):
    sso_handler[key] = handler


def remove_handler(key: str):
    sso_handler.pop(key, None)


@bp.route("/login")
@login_required
@perm_fleet_manage.require(http_exception=401)
Beispiel #30
0
from waitlist.permissions import perm_manager
from flask_babel import gettext, lazy_gettext

bp = Blueprint('settings_inserts', __name__)
logger = logging.getLogger(__name__)

perm_manager.define_permission('inserts_edit')


@bp.route("/")
@login_required
@perm_manager.require('inserts_edit')
def index() -> Response:
    data = {'header': sget_insert('header')}
    return render_template("settings/inserts.html", inserts=data)


@bp.route("/change/<string:type_>", methods=["POST"])
@login_required
@perm_manager.require('inserts_edit')
def change(type_) -> Response:
    if type_ == "header":
        content = request.form.get('content')
        sset_insert('header', content)
        flash(gettext("Header Insert Saved"), 'success')
    return redirect(url_for('settings_inserts.index'))


add_menu_entry('settings_inserts.index', lazy_gettext('Page Inserts'),
               perm_manager.get_permission('inserts_edit').can)