""" Authentication module """ from flask import render_template, request, flash, Blueprint, redirect, url_for from app.models import User, Ballot, Question, Option, Vote, Code from app import db BLUEPRINT = Blueprint( 'vote', __name__, template_folder='templates' ) @BLUEPRINT.route('/') def index(): """View list of votes""" ballots = Ballot.query.all() return render_template( 'vote/index.j2', ballots=ballots, ) @BLUEPRINT.route('/', methods=["GET", "POST"]) def view(ballot_id): """Vote and view results of ballot""" ballot = Ballot.query.get(ballot_id) if request.method == 'POST': security_code = request.form['security_code'] code = Code.query.order_by(Code.expire_date.desc()).first() user_id = None for user in User.query.all(): if security_code == code.get_digest(user.id): user_id = user.id if user_id is not None: for question_id, option_id in request.form.items(): if question_id == 'security_code': continue question = Question.query.get(question_id) if question.has_voten(user_id): flash('Je hebt al gestemd.', 'warning') return redirect(url_for('vote.view', ballot_id=ballot.id)) option = question.options.filter(Option.id == option_id).first() vote = Vote() vote.option_id = option.id vote.user_id = user_id db.session.add(vote) db.session.commit() flash('Succesvol gestemd.', 'success') else: flash('Fout in veiligheids code.', 'warning') return render_template( 'vote/view.j2', ballot=ballot, )