Beispiel #1
0
def run():
    """ Allows the user to run for an officer position. """
    vote = vote_requirements()
    if not isinstance(vote, dict):
        return vote

    form = forms.RunForm()

    signups = cube.get_signups()
    params = {
        "name": cube.get_name(),
        "years": cube.count_years(signups),
        "meetings": cube.count_meetings(signups, datetime.min, datetime.max),
        "annual_meetings": cube.count_meetings(signups),
        "year": cube.get_year(),
    }

    if form.validate_on_submit():
        cube.store_candidate(
            cube.add_dict({"description": form.description.data}, params))
        return alert(
            "<strong>Congrats!</strong> Your application has been registered.")

    return flask.render_template(flask.request.path + cube.FILE,
                                 **vote,
                                 **params,
                                 title="run",
                                 length=forms.LENGTH,
                                 form=form)
Beispiel #2
0
def GLOBALS() -> dict:
    """ Returns all the global variables passed to every template. """
    user = cube.load_file("users").get(flask.session.get("account", None), {})
    vars = {
        "vote_active": cube.load_file("vote")["vote_active"],
        "user": user,
        "btnform": forms.FlaskForm(),
        "searchForm": forms.SearchForm(),
    }
    return cube.add_dict(GLOBAL, vars)
Beispiel #3
0
def stats() -> dict:
    """ Parses a user's .csv / .txt file and returns statistics. """
    form, file = forms.StatsForm(), forms.UploadForm()
    rtn = {"form": form, "file": file}

    if form.validate_on_submit():
        times = statistics.parse_text(form.times.data)
    elif file.validate_on_submit():
        times = statistics.parse(file.file.data)
    else:
        times = None

    if times:
        descr, mean, best = statistics.process(times)
        return cube.add_dict({"descr": descr, "mean": mean, "best": best}, rtn)

    return rtn
Beispiel #4
0
def profile() -> dict:
    """ Allows the user to login as well as register a new account. """
    loginForm = forms.LoginForm()
    codeForm = forms.TFAForm()
    signupForm = forms.SignupForm()
    mailForm = forms.MailForm()
    httpForm = forms.HTTPForm()
    ionForm, wcaForm = forms.APIForm(prefix="ion"), forms.APIForm(prefix="wca")
    rtn = {
        "loginForm": loginForm,
        "codeForm": codeForm,
        "signupForm": signupForm,
        "mailForm": mailForm,
        "httpForm": httpForm,
        "ionForm": ionForm,
        "wcaForm": wcaForm
    }

    users = cube.load_file("users")

    if "account" in flask.session:
        tabs = [["overview", "API"], ["email", "refresh", "develop"], ["edit"]]
        scopes = {"default": 0, "privileged": 1, "admin": 2}
        tab = flask.request.args.get('tab', 'overview')
        scope = scopes[flask.session["scope"]]

        i = None
        for j, group in enumerate(tabs):
            if tab in group:
                i = j
        if i is None:
            return alert("Invalid tab!", "info", "self")
        if i > scope:
            return alert(
                "User does not have the valid scope. This incident will be logged.",
                "danger", "self")

        rtn = cube.add_dict(
            {
                "tabs": tabs,
                "scopes": scopes,
                "clubmailpassword":
                cube.load_file("secrets")["clubmailpassword"],
                "emails": cube.load_file("emails")["emails"],
            }, rtn)
    else:
        scope = 0

    if scope >= 0:
        if "confirm" in flask.request.form and signupForm.validate_on_submit():
            username, password = signupForm.username.data, signupForm.password.data
            if username in cube.load_file("users"):
                return alert("Username is taken.", "info", "meta")
            if password != signupForm.confirm.data:
                return alert("Passwords do not match.", "info", "meta")

            cube.register(username, password)
            return alert("Account registered!", "success", "self")

        elif "login" in flask.request.form and loginForm.validate_on_submit():
            username, password = loginForm.username.data, loginForm.password.data
            if not cube.check(username, password):
                return alert("Username or password is incorrect.", "info",
                             "self")

            # Save login to cookies if 2fa is not enabled, otherwise don't
            if "2fa" not in users[username] and "yubi" not in users[username]:
                flask.session["account"] = username
                flask.session["scope"] = users[username]["scope"]
            else:
                if "2fa" in users[username]:
                    flask.session["2fa"] = True
                flask.session["username"] = username

            # load U2F challenge if it exists
            if "yubi" in users[username]:
                flask.session["yubi"] = websafe_decode(users[username]["yubi"])

            return flask.redirect(flask.url_for("profile"))

        elif "yubi_check" in flask.session or (
                "login_2fa" in flask.request.form
                and codeForm.validate_on_submit()):
            username = flask.session["username"]
            if "yubi_check" not in flask.session and not cube.check_2fa(
                    username, str(codeForm.code.data)):
                return alert("2FA code is incorrect.", "info", "self")

            if "yubi_check" in flask.session:
                del flask.session["yubi_check"]

            # actually login
            flask.session["account"] = username
            flask.session["scope"] = users[username]["scope"]
            return flask.redirect(flask.url_for("profile"))

        elif "cancel_2fa" in flask.request.form and "2fa" in flask.session:
            del flask.session["2fa"]

        elif "cancel_yubi" in flask.request.form and "yubi" in flask.session:
            del flask.session["yubi"]

        elif ionForm.validate_on_submit():
            rtn = cube.add_dict(
                {"data": cube.api_call("ion", ionForm.call.data)}, rtn)

        elif wcaForm.validate_on_submit():
            rtn = cube.add_dict(
                {"data": cube.api_call("wca", wcaForm.call.data)}, rtn)

    if scope >= 1:
        if mailForm.validate_on_submit():
            recipients = mailForm.recipients.data.split(
                ", ") if mailForm.recipients.data != "" else cube.load_file(
                    "emails")["emails"]
            # add footer with unsubscribe information
            body = mailForm.email.data.replace("\n", "") + \
f"""

--
If you're tired of seeing these emails, unsubscribe [here]({cube.TJ}).
"""
            body = cube.markdown2.markdown(body)
            cube.send_email(recipients, mailForm.subject.data, body)
            if mailForm.log.data:
                cube.save_email(mailForm.subject.data, mailForm.email.data)
            return alert("Mail sent.", "success", "meta")

        elif httpForm.validate_on_submit():
            flask.abort(int(httpForm.http.data))

    if scope >= 2:
        pass

    if flask.request.method == "POST":

        if "logout" in flask.request.form:
            del flask.session["account"]
            if "2fa" in flask.session:
                del flask.session["2fa"]
            if "yubi" in flask.session:
                del flask.session["yubi"]

        if "delete" in flask.request.form:
            del users[flask.session["account"]]
            del flask.session["account"]
            cube.dump_file(users, "users")
            return alert("Account deleted!", "success", "self")

        if "clear" in flask.request.form:
            # Save CSRF token
            csrf = flask.session["csrf_token"]
            flask.session.clear()
            flask.session["csrf_token"] = csrf

        if "fb" in flask.request.form:
            cube.get_pfps(cube.CONFIG["officers"])
            alert("Updated the profile pictures!")

        if "comps" in flask.request.form:
            cube.get_comps()
            alert("Updated the competitions!")

        if "records" in flask.request.form:
            cube.update_records()
            alert("Updated the records!")

        if "history" in flask.request.form:
            cube.save_club_history()
            cube.graph_capacity()
            cube.graph_blocks("by_x")
            cube.graph_blocks("by_y")
            alert("Updated the club history!")

        if "heatmap" in flask.request.form:
            cube.graph_vists()
            alert("Updated the heatmap!")

    return rtn
Beispiel #5
0
def profile() -> dict:
    """ Allows the user to login as well as register a new account. """
    loginForm = forms.LoginForm()
    signupForm = forms.SignupForm()
    mailForm = forms.MailForm()
    httpForm = forms.HTTPForm()
    ionForm, wcaForm = forms.APIForm(prefix="ion"), forms.APIForm(prefix="wca")
    rtn = {
        "loginForm": loginForm,
        "signupForm": signupForm,
        "mailForm": mailForm,
        "httpForm": httpForm,
        "ionForm": ionForm,
        "wcaForm": wcaForm
    }

    users = cube.load_file("users")

    if "account" in flask.session:
        tabs = [["overview", "API"], ["email", "refresh", "develop"], ["edit"]]
        scopes = {"default": 0, "privileged": 1, "admin": 2}
        tab = flask.request.args.get('tab', 'overview')
        scope = scopes[flask.session["scope"]]

        i = None
        for j, group in enumerate(tabs):
            if tab in group:
                i = j
        if i is None:
            return alert("Invalid tab!", "info", "self")
        if i > scope:
            return alert(
                "User does not have the valid scope. This incident will be logged.",
                "danger", "self")

        rtn = cube.add_dict(
            {
                "tabs": tabs,
                "scopes": scopes,
                "clubmailpassword":
                cube.load_file("secrets")["clubmailpassword"],
                "emails": cube.load_file("emails")["emails"],
            }, rtn)
    else:
        scope = 0

    if scope >= 0:
        if "confirm" in flask.request.form and signupForm.validate_on_submit():
            username, password = signupForm.username.data, signupForm.password.data
            if username in cube.load_file("users"):
                return alert("Username is taken.", "info", "meta")
            if password != signupForm.confirm.data:
                return alert("Passwords do not match.", "info", "meta")

            cube.register(username, password)
            return alert("Account registered!", "success", "self")

        elif "login" in flask.request.form and loginForm.validate_on_submit():
            username, password = loginForm.username.data, loginForm.password.data
            if not cube.check(username, password):
                return alert("Username or password is incorrect.", "info",
                             "self")

            # Save login to cookies
            flask.session["account"] = username
            flask.session["scope"] = users[username]["scope"]
            return flask.redirect(flask.url_for("profile"))

        elif ionForm.validate_on_submit():
            rtn = cube.add_dict(
                {"data": cube.api_call("ion", ionForm.call.data)}, rtn)

        elif wcaForm.validate_on_submit():
            rtn = cube.add_dict(
                {"data": cube.api_call("wca", wcaForm.call.data)}, rtn)

    if scope >= 1:
        if mailForm.validate_on_submit():
            recipients = mailForm.recipients.data.split(
                ", ") if mailForm.recipients.data != "" else cube.load_file(
                    "emails")["emails"]
            body = cube.markdown2.markdown(mailForm.email.data).replace(
                "\n", "")
            cube.send_email(recipients, mailForm.subject.data, body)
            if mailForm.log.data:
                cube.save_email(mailForm.subject.data, mailForm.email.data)
            return alert("Mail sent.", "success", "meta")

        elif httpForm.validate_on_submit():
            flask.abort(int(httpForm.http.data))

    if scope >= 2:
        pass

    if flask.request.method == "POST":

        if "logout" in flask.request.form:
            del flask.session["account"]

        if "delete" in flask.request.form:
            del users[flask.session["account"]]
            del flask.session["account"]
            cube.dump_file(users, "users")
            return alert("Account deleted!", "success", "self")

        if "clear" in flask.request.form:
            # Save CSRF token
            csrf = flask.session["csrf_token"]
            flask.session.clear()
            flask.session["csrf_token"] = csrf

        if "fb" in flask.request.form:
            cube.get_pfps(cube.CONFIG["officers"])

        if "comps" in flask.request.form:
            cube.get_comps()

        if "records" in flask.request.form:
            cube.update_records()

    return rtn