main.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from flask import Flask, request, session, g, redirect, url_for, abort, \
  4. render_template, flash
  5. import sqlite3
  6. from datetime import date, timedelta
  7. from contextlib import closing
  8. import locale
  9. locale.setlocale(locale.LC_ALL, '')
  10. DATABASE = '/tmp/cavote.db'
  11. SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
  12. DEBUG = True
  13. app = Flask(__name__)
  14. app.config.from_object(__name__)
  15. def connect_db():
  16. return sqlite3.connect(app.config['DATABASE'])
  17. @app.before_request
  18. def before_request():
  19. g.db = connect_db()
  20. @app.teardown_request
  21. def teardown_request(exception):
  22. g.db.close()
  23. @app.route('/')
  24. def home():
  25. return render_template('index.html')
  26. def query_db(query, args=(), one=False):
  27. cur = g.db.execute(query, args)
  28. rv = [dict((cur.description[idx][0], value)
  29. for idx, value in enumerate(row)) for row in cur.fetchall()]
  30. return (rv[0] if rv else None) if one else rv
  31. def init_db():
  32. with closing(connect_db()) as db:
  33. with app.open_resource('schema.sql') as f:
  34. db.cursor().executescript(f.read())
  35. db.commit()
  36. #----------------
  37. # Login / Logout
  38. def valid_login(username, password):
  39. return query_db('select * from users where email = ? and password = ?', [username, password], one=True)
  40. def connect_user(user):
  41. session['userid'] = user['id']
  42. session['username'] = user['name']
  43. session['email'] = user['email']
  44. session['organization'] = user['organization']
  45. if user['is_admin'] == 1:
  46. session['is_admin'] = True
  47. def disconnect_user():
  48. session.pop('username', None)
  49. session.pop('is_admin', None)
  50. @app.route('/login', methods=['GET', 'POST'])
  51. def login():
  52. if request.method == 'POST':
  53. user = valid_login(request.form['username'], request.form['password'])
  54. if user is None:
  55. flash('Invalid username/password', 'error')
  56. else:
  57. connect_user(user)
  58. flash('You were logged in', 'success')
  59. return redirect(url_for('home'))
  60. return render_template('login.html')
  61. @app.route('/logout')
  62. def logout():
  63. disconnect_user()
  64. flash('You were logged out', 'info')
  65. return redirect(url_for('home'))
  66. #-----------------
  67. # Change password
  68. @app.route('/password/lost', methods=['GET', 'POST'])
  69. def password_lost():
  70. info = None
  71. if request.method == 'POST':
  72. user = query_db('select * from users where email = ?', [request.form['email']], one=True)
  73. if user is None:
  74. flash('Cet utilisateur n\'existe pas !', 'error')
  75. else:
  76. # :TODO:maethor:120528: Générer la clé, la mettre dans la base de données et envoyer le mail
  77. flash(u"Un mail a été envoyé à " + user['email'], 'info')
  78. return render_template('password_lost.html')
  79. @app.route('/login/<username>/<key>')
  80. def login_key(username, key):
  81. user = query_db('select * from users where email = ? and key = ?', [username, key], one=True)
  82. if user is None:
  83. abort(404)
  84. else:
  85. connect_user(user)
  86. # :TODO:maethor:120528: Remplacer la clé pour qu'elle ne puisse plus être utilisée
  87. return redirect(url_for('home'))
  88. #---------------
  89. # User settings
  90. @app.route('/user/settings/<username>')
  91. def show_user(username):
  92. if username != session.get('username'):
  93. abort(401)
  94. return render_template('user_settings.html')
  95. #------------
  96. # User admin
  97. #------------
  98. # Votes list
  99. @app.route('/votes/<votes>')
  100. def show_votes(votes):
  101. today = date.today()
  102. if votes == 'all':
  103. votes = query_db('select title, description, date_begin, date_end from votes order by id desc')
  104. elif votes == 'archive':
  105. votes = query_db('select title, description, date_begin, date_end from votes where date_end < (?) order by id desc', [today])
  106. elif votes == 'current':
  107. votes = query_db('select title, description, date_begin, date_end from votes where date_end >= (?) order by id desc', [today])
  108. else:
  109. abort(404)
  110. return render_template('show_votes.html', votes=votes)
  111. #-------------
  112. # Votes admin
  113. @app.route('/votes/admin/new')
  114. def new_vote():
  115. if not session.get('is_admin'):
  116. abort(401)
  117. return render_template('new_vote.html')
  118. @app.route('/votes/admin/add', methods=['POST'])
  119. def add_vote():
  120. if not session.get('is_admin'):
  121. abort(401)
  122. date_begin = date.today()
  123. date_end = date.today() + timedelta(days=int(request.form['days']))
  124. transparent = 0
  125. public = 0
  126. multiplechoice = 0
  127. if 'transparent' in request.form.keys():
  128. transparent = 1
  129. if 'public' in request.form.keys():
  130. public = 1
  131. if 'multiplechoice' in request.form.keys():
  132. multiplechoice = 1
  133. g.db.execute('insert into votes (title, description, date_begin, date_end, is_transparent, is_public, is_multiplechoice) values (?, ?, ?, ?, ?, ?, ?)',
  134. [request.form['title'], request.form['description'], date_begin, date_end, transparent, public, multiplechoice])
  135. g.db.commit()
  136. flash('New entry was successfully posted', 'info')
  137. return redirect(url_for('home'))
  138. #------
  139. # Main
  140. if __name__ == '__main__':
  141. app.run()