Example #1
0
File: auth.py Project: ed588/nselec
def signup():
    if request.method == "POST":
        error = None
        token = request.form['token']
        ts = TimestampSigner(current_app.secret_key)
        try:
            username = ts.unsign(token, 60*5).decode("utf-8") # 2 minutes
        except SignatureExpired:
            error = "Token has expired"
        except BadSignature:
            error = "Invalid token"
        else:
            db = get_db()
            users = db.table("users")
            if users.contains(Query().username == username):
                error = "That user already exists"
            else:
                users.insert({"username":username,"role":0,"password":generate_password_hash(request.form['password'])})
        if error is None:
            session.clear()
            flash("Successfully created user! You can now login.", "success")
            return redirect(url_for("auth.login"))
        else:
            flash(error, "error")
    return render_template("auth/signup.html")
Example #2
0
def results(el_id):
    db = get_db()
    el = db.get(doc_id=el_id)
    if el is None:
        abort(404)
    tt = time_type(el['times']['start'], el['times']['end'])
    if tt == "present":
        return redirect(url_for("vote.election", el_id=el_id))
    elif tt != "past":
        abort(404)
    if el['type'] == "yesno":
        results = process_votes_yesno(el['votes'])
        voters = process_voters(el['voters'])
        return render_template("results/yesno.html",
                               processed_results=results,
                               results=el['votes'],
                               voters=voters,
                               el=el)
    elif el['type'] == "ranked":
        winner, results = process_votes_ranked(list(el['votes']), el)
        voters = process_voters(el['voters'])
        return render_template("results/ranked.html",
                               winner=winner,
                               processed_results=results,
                               results=el['votes'],
                               voters=voters,
                               el=el)
    else:
        return render_template(
            "base.html", content="Oops, that election type is not supported")
Example #3
0
def check_vote(el_id, nation, code, vote):
    if nation is None or code is None or vote is None:
        return False, "the nation, verification code, or vote was not specified"
    voters = get_allowed_voters()
    if nation not in voters:
        return False, "that nation is not allowed to vote"
    if not verify_code(nation, code):
        return False, "the verification code was invalid or has expired"
    db = get_db()
    el = db.get(doc_id=el_id)
    if el is None:
        return False, "that election does not exist"
    if nation in el['voters']:
        return False, "you have already voted on this election"
    if el['type'] == "yesno":
        if vote not in ['for','against']:
            return False, "invalid vote (must be for or against)"
    elif el['type'] == "ranked":
        opts = vote.split(":")
        for o in opts:
            if not o.isdigit():
                return False, "invalid option string, please contact your administrator. (some non-digits) (debug: {})".format(vote)
        seq = all(val == idx for idx, val in enumerate(sorted((int(o) for o in opts))))
        if not seq:
            return False, "invalid option string, please contact your administrator. (non-consecutive options) (debug: {})".format(vote)

    return True, "ok"
Example #4
0
def edit_election(el_id):
    db = get_db()
    el = db.get(doc_id=el_id)
    if el is None:
        abort(404)
    tt = time_type(el["times"]["start"], el["times"]["end"])
    if tt != "future":
        abort(404)
    if request.method == "POST":
        if el["type"] == "ranked":
            succ, data = get_data_ranked()
            if succ:
                db.remove(doc_ids=[el_id])
                db.insert(data)
                flash("Election updated successfully!", "success")
                return redirect(url_for("admin.elections"))
            else:
                flash(data, "error")
        elif el["type"] == "yesno":
            succ, data = get_data_yesno()
            if succ:
                db.remove(doc_ids=[el_id])
                db.insert(data)
                flash("Election updated successfully!", "success")
                return redirect(url_for("admin.elections"))
            else:
                flash(data, "error")
    else:
        if el["type"] == "ranked":
            return render_template("admin/edit_ranked.html", el=el)
        elif el["type"] == "yesno":
            return render_template("admin/edit_yesno.html", el=el)
Example #5
0
def register_vote(el_id, nation, vote):
    db = get_db()
    el = db.get(doc_id=el_id)
    if el['type'] == "yesno":
        register_vote_yesno(el_id, nation, vote)
    elif el['type'] == "ranked":
        register_vote_ranked(el_id, nation, vote)
Example #6
0
File: auth.py Project: ed588/nselec
def set_password(username, password):
    pwh = generate_password_hash(password)
    del password # i have no idea if that will do anything but we can try i guess
    usertab = get_db().table("users")
    u = usertab.get(Query().username == username)
    if u == None:
        return False
    else:
        usertab.update({"password":pwh}, Query().username == username)
Example #7
0
def archive():
    db = get_db()
    Election = Query()
    els = sorted(
        db.search(Election.times.end < datetime.now()),
        key=lambda n: n["times"]["end"],
        reverse=True,
    )
    return render_template("archive/archive.html", els=els)
Example #8
0
def elections():
    db = get_db()
    els = db.all()
    categories = {"past": [], "present": [], "future": []}
    for el in els:
        tt = time_type(el["times"]["start"], el["times"]["end"])
        categories[tt].append(el)

    return render_template("admin/elections.html", **categories)
Example #9
0
def delete_user(username):
    db = get_db()
    user = db.table("users").get(Query().username == username)
    if user is None:
        abort(404)
    if request.method == "POST":
        db.table("users").remove(Query().username == username)
        flash("User removed successfully", "success")
        return redirect(url_for("admin.users"))
    return render_template("admin/delete_user.html", username=username)
Example #10
0
File: auth.py Project: ed588/nselec
 def wrapped(**kwargs):
     db = get_db()
     # we know the user exists, because login_required should check that for us
     User = Query()
     u = db.table("users").get(User.username == session['user'])
     if u['role'] >= role:
         return view(**kwargs)
     else:
         flash("You do not have permissions to do that.", "error")
         return redirect(url_for("admin.index"))
Example #11
0
def new_ranked():
    if request.method == "POST":
        succ, data = get_data_ranked()
        if succ:
            db = get_db()
            db.insert(data)
            flash("Successfully added election!", "success")
            return redirect(url_for("admin.elections"))
        else:
            flash(data, "error")
    return render_template("admin/new_ranked.html")
Example #12
0
File: auth.py Project: ed588/nselec
def check_user():
    if "user" not in session:
        # not even logged in
        return False, "You need to be logged in"
    db = get_db()
    User = Query()
    if not db.table("users").contains(User.username == session['user']):
        # that user doesn't exist!
        # it shouldn't be possible for somebody to tamper with the session, this
        # is mainly to log people out if the user gets deleted.
        return False, "The user you are logged in as does not exist (any more)"
    return True, "seems ok to me"
Example #13
0
def delete_election(el_id):
    db = get_db()
    el = db.get(doc_id=el_id)
    if el is None:
        abort(404)
    tt = time_type(el["times"]["start"], el["times"]["end"])
    if tt != "future":
        abort(404)
    if request.method == "POST":
        db.remove(doc_ids=[el_id])
        flash("Election removed successfully", "success")
        return redirect(url_for("admin.elections"))
    return render_template("admin/delete_election.html", el=el)
Example #14
0
File: cli.py Project: ed588/nselec
 def new_admin(username):
     """Creates a new administrator user. Useful if you've forgotten the password, or
     if you've just installed this (if so, do initialise first)"""
     password = getpass("Password for the new user: "******"users")
     data = {
         "username": username,
         "password": generate_password_hash(password),
         "role": 1,
     }
     usertab.insert(data)
     click.echo("User {} created and given admin permissions successfully.")
Example #15
0
File: auth.py Project: ed588/nselec
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        db = get_db()
        usertab = db.table("users")
        User = Query()
        entry = usertab.get(User.username == username)
        if entry == None or not check_password_hash(entry.get('password', None), password):
            flash("Invalid username or password!", "error")
        else:
            # valid login, hooray!
            session.clear()
            session['user'] = username
            flash("Login successful!", "success")
            return redirect(url_for('admin.index'))
    return render_template("auth/login.html")
Example #16
0
def election_list():
    db = get_db()
    elections = db.all()
    # we need to sort these into "past", "present" and "future"
    categories = {'past': [], 'present': [], 'future': []}
    for el in elections:
        tt = time_type(el['times']['start'], el['times']['end'])
        categories[tt].append(el)

    threshold = dt.datetime.now() - dt.timedelta(days=7 * 2)  # 2 weeks ago
    print(threshold)
    for e in categories['past']:
        print(e['times']['end'], e['times']['end'] < threshold)
    categories['past'] = [
        e for e in categories['past'] if e['times']['end'] > threshold
    ]

    return render_template("election_list/election_list.html", **categories)
Example #17
0
def election(el_id):
    db = get_db()
    el = db.get(doc_id=el_id)
    if el is None:
        abort(404)
    else:
        tt = time_type(el['times']['start'], el['times']['end'])
        if tt == "past":
            return redirect(url_for("results.results", el_id=el_id))
        elif tt == "present":
            voters = get_allowed_voters()
            if el['type'] == "yesno":
                return render_template("vote/yesno.html", el=el, el_id=el_id, voters=voters)
            elif el['type'] == "ranked":
                return render_template("vote/ranked.html", el=el, el_id=el_id, voters=voters)
            else:
                return render_template("base.html", content="Oops, that election type is not supported")
        else:
            abort(404)
Example #18
0
def edit_user(username):
    db = get_db()
    usertab = db.table("users")
    user = usertab.get(Query().username == username)
    if user is None:
        abort(404)
    if request.method == "POST":
        err = None
        pw = request.form["password"]
        role = request.form['role']
        if not (0 <= int(role) <= 1):
            err = "Role must be an integer between 0 and 1"
        else:
            if pw != "":
                set_password(username, pw)
            usertab.update({"role": int(role)}, Query().username == username)
        if err is None:
            flash("User updated successfully!", "success")
            return redirect(url_for("admin.users"))
        else:
            flash(err, "error")
    return render_template("admin/edit_user.html", user=user)
Example #19
0
def users():
    db = get_db()
    users = db.table("users").all()
    return render_template("admin/users.html", users=users)
Example #20
0
def register_vote_ranked(el_id, nation, vote):
    db = get_db()
    db.update(list_append("voters", nation), doc_ids=[el_id])
    db.update(list_append("votes", vote), doc_ids=[el_id])
Example #21
0
def register_vote_yesno(el_id, nation, vote):
    db = get_db()
    db.update(list_append("voters", nation), doc_ids=[el_id])
    db.update(inc_result(vote), doc_ids=[el_id])
Example #22
0
File: auth.py Project: ed588/nselec
def get_user(username):
    # utility function for other stuff to use
    db = get_db()
    usertab = db.table("users")
    u = usertab.get(Query().username == username)
    return u