app.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Authentication module
  3. """
  4. from flask import render_template, request, flash, Blueprint, redirect, url_for
  5. from app.models import User, Ballot, Question, Option, Vote, Code
  6. from app import db
  7. BLUEPRINT = Blueprint(
  8. 'vote',
  9. __name__,
  10. template_folder='templates'
  11. )
  12. @BLUEPRINT.route('/')
  13. def index():
  14. """View list of votes"""
  15. ballots = Ballot.query.all()
  16. return render_template(
  17. 'vote/index.j2',
  18. ballots=ballots,
  19. )
  20. @BLUEPRINT.route('/<int:ballot_id>', methods=["GET", "POST"])
  21. def view(ballot_id):
  22. """Vote and view results of ballot"""
  23. ballot = Ballot.query.get(ballot_id)
  24. if request.method == 'POST':
  25. security_code = request.form['security_code']
  26. code = Code.query.order_by(Code.expire_date.desc()).first()
  27. user_id = None
  28. for user in User.query.all():
  29. if security_code == code.get_digest(user.id):
  30. user_id = user.id
  31. if user_id is not None:
  32. for question_id, option_id in request.form.items():
  33. if question_id == 'security_code':
  34. continue
  35. question = Question.query.get(question_id)
  36. if question.has_voten(user_id):
  37. flash('Je hebt al gestemd.', 'warning')
  38. return redirect(url_for('vote.view', ballot_id=ballot.id))
  39. option = question.options.filter(Option.id == option_id).first()
  40. vote = Vote()
  41. vote.option_id = option.id
  42. vote.user_id = user_id
  43. db.session.add(vote)
  44. db.session.commit()
  45. flash('Succesvol gestemd.', 'success')
  46. else:
  47. flash('Fout in veiligheids code.', 'warning')
  48. return render_template(
  49. 'vote/view.j2',
  50. ballot=ballot,
  51. )