main.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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', active_button="home")
  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['user'] = user # :KLUDGE:maethor:120528: Stoquer toute la ligne de la table users dans la session, c'est un peu crade…
  42. #session['user']['id'] = user['id']
  43. #session['user']['name'] = user['name']
  44. #session['user']['email'] = user['email']
  45. #session['user']['organization'] = user['organization']
  46. #if user['is_admin'] == 1:
  47. # session['user']['is_admin'] = True
  48. def disconnect_user():
  49. session.pop('user', 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/<userid>/<key>')
  80. def login_key(userid, key):
  81. user = query_db('select * from users where id = ? and key = ?', [userid, key], one=True)
  82. if user is None or key == "invalid":
  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 (invalid)
  87. flash(u"Veuillez mettre à jour votre mot de passe", 'info')
  88. return redirect(url_for('user_password'), userid=user['userid'])
  89. #---------------
  90. # User settings
  91. @app.route('/user/<userid>')
  92. def show_user(userid):
  93. if int(userid) != session.get('user').get('id'):
  94. abort(401)
  95. return render_template('show_user.html')
  96. @app.route('/user/settings/<userid>', methods=['GET', 'POST'])
  97. def user_settings(userid):
  98. if int(userid) != session.get('user').get('id'):
  99. abort(401)
  100. if request.method == 'POST':
  101. g.db.execute('update users set email = ?, name = ?, organization = ? where id = ?',
  102. [request.form['email'], request.form['name'], request.form['organization'], session['user']['id']])
  103. g.db.commit()
  104. disconnect_user() # :TODO:maethor:120528: Maybe useless, but this is simple way to refresh session :D
  105. flash(u'Votre profil a été mis à jour !', 'success')
  106. return redirect(url_for('login'))
  107. return render_template('user_settings.html')
  108. @app.route('/user/password/<userid>', methods=['GET', 'POST'])
  109. def user_password(userid):
  110. if int(userid) != session.get('user').get('id'):
  111. abort(401)
  112. if request.method == 'POST':
  113. if request.form['password'] == request.form['password2']:
  114. # :TODO:maethor:120528: Chiffrer le mot de passe !
  115. g.db.execute('update users set password = ? where id = ?', [request.form['password'], session['user']['id']])
  116. g.db.commit()
  117. flash(u'Votre mot de passe a été mis à jour.', 'success')
  118. else:
  119. flash(u'Les mots de passe sont différents.', 'error')
  120. return render_template('user_settings.html')
  121. #------------
  122. # User admin
  123. @app.route('/users/admin/list')
  124. def admin_users():
  125. if not session.get('user').get('is_admin'):
  126. abort(401)
  127. users = query_db('select * from users order by id desc')
  128. return render_template('admin_users.html', users=users)
  129. @app.route('/users/admin/add', methods=['GET', 'POST'])
  130. def add_user():
  131. if not session.get('user').get('is_admin'):
  132. abort(401)
  133. if request.method == 'POST':
  134. if request.form['email']:
  135. # :TODO:maethor:120528: Check fields
  136. password = "toto" # :TODO:maethor:120528: Generate password
  137. admin = 0
  138. if 'admin' in request.form.keys():
  139. admin = 1
  140. g.db.execute('insert into users (email, name, organization, password, is_admin) values (?, ?, ?, ?, ?)',
  141. [request.form['email'], request.form['username'], request.form['organization'], password, admin])
  142. g.db.commit()
  143. # :TODO:maethor:120528: Send mail
  144. flash(u'Le nouvel utilisateur a été créé avec succès', 'success')
  145. return redirect(url_for('home'))
  146. else:
  147. flash(u"Vous devez spécifier une adresse email.", 'error')
  148. return render_template('add_user.html')
  149. #-------------
  150. # Roles admin
  151. @app.route('/roles')
  152. def show_roles():
  153. if not session.get('user').get('is_admin'):
  154. abort(401)
  155. roles = query_db('select * from roles')
  156. return render_template('show_roles.html', roles=roles)
  157. @app.route('/roles/admin/add', methods=['POST'])
  158. def add_role():
  159. if not session.get('user').get('is_admin'):
  160. abort(401)
  161. if request.method == 'POST':
  162. if request.form['name']:
  163. g.db.execute('insert into roles (name) values (?)', [request.form['name']])
  164. g.db.commit()
  165. else:
  166. flash(u"Vous devez spécifier un nom.", "error")
  167. return redirect(url_for('show_roles'))
  168. @app.route('/roles/admin/delete/<idrole>')
  169. def del_role(idrole):
  170. if not session.get('user').get('is_admin'):
  171. abort(401)
  172. role = query_db('select * from roles where id = ?', [idrole], one=True)
  173. if role is None:
  174. abort(404)
  175. if role['system']:
  176. abort(401)
  177. g.db.execute('delete from roles where id = ?', [idrole])
  178. g.db.commit()
  179. return redirect(url_for('show_roles'))
  180. #------------
  181. # Votes list
  182. @app.route('/votes/<votes>')
  183. def show_votes(votes):
  184. today = date.today()
  185. active_button = votes
  186. basequery = 'select *, roles.name as rolename from votes join roles on roles.id=votes.id_role where is_open=1'
  187. if votes == 'all':
  188. votes = query_db(basequery + ' order by id desc')
  189. elif votes == 'archive':
  190. votes = query_db(basequery + ' and date_end < (?) order by id desc', [today])
  191. elif votes == 'current':
  192. votes = query_db(basequery + ' and date_end >= (?) order by id desc', [today])
  193. else:
  194. abort(404)
  195. return render_template('show_votes.html', votes=votes, active_button=active_button)
  196. #------
  197. # Vote
  198. def can_see_vote(idvote, iduser=-1):
  199. user = query_db('select * from users where id=?', [iduser], one=True)
  200. vote = query_db('select * from votes where id=?', [idvote], one=True)
  201. if user is None and not vote.is_public:
  202. return False
  203. return True # :TODO:maethor:20120529: Check others things
  204. def can_vote(idvote, iduser=-1):
  205. if not can_see_vote(idvote, iduser):
  206. return False
  207. return True # :TODO:maethor:20120529: Check others things
  208. @app.route('/vote/<idvote>')
  209. def show_vote(idvote):
  210. vote = query_db('select *, roles.name as rolename from votes join roles on roles.id=votes.id_role where votes.id=?', [idvote], one=True)
  211. if vote is None:
  212. abort(404)
  213. if can_see_vote(idvote, session.get('user').get('id')):
  214. choices = query_db('select * from choices where id_vote=?', [idvote])
  215. attachments = query_db('select * from attachments where id_vote=?', [idvote])
  216. return render_template('vote.html', vote=vote, attachments=attachments, choices=choices, can_vote=can_vote(idvote, session.get('user').get('id')))
  217. flash('Vous n\'avez pas le droit de voir ce vote, désolé.')
  218. return(url_for('home'))
  219. #-------------
  220. # Votes admin
  221. @app.route('/votes/admin/list')
  222. def admin_votes():
  223. if not session.get('user').get('is_admin'):
  224. abort(401)
  225. votes = query_db('select *, roles.name as rolename from votes join roles on roles.id=votes.id_role order by id desc')
  226. return render_template('admin_votes.html', votes=votes)
  227. @app.route('/votes/admin/add', methods=['GET', 'POST'])
  228. def add_vote():
  229. if not session.get('user').get('is_admin'):
  230. abort(401)
  231. if request.method == 'POST':
  232. if request.form['title']:
  233. date_begin = date.today()
  234. date_end = date.today() + timedelta(days=int(request.form['days']))
  235. transparent = 0
  236. public = 0
  237. multiplechoice = 0
  238. if 'transparent' in request.form.keys():
  239. transparent = 1
  240. if 'public' in request.form.keys():
  241. public = 1
  242. if 'multiplechoice' in request.form.keys():
  243. multiplechoice = 1
  244. role = query_db('select id from roles where name = ?', [request.form['role']], one=True)
  245. if role is None:
  246. role[id] = 1
  247. g.db.execute('insert into votes (title, description, category, date_begin, date_end, is_transparent, is_public, is_multiplechoice, id_role, id_author) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
  248. [request.form['title'], request.form['description'], request.form['category'], date_begin, date_end, transparent, public, multiplechoice, role['id'], session['user']['id']])
  249. g.db.commit()
  250. vote = query_db('select * from votes where title = ? and date_begin = ? order by id desc',
  251. [request.form['title'], date_begin], one=True) # :DEBUG:maethor:20120528: Bug possible car le titre n'est pas unique
  252. if vote is None:
  253. flash(u'Une erreur est survenue !', 'error')
  254. return redirect(url_for('home'))
  255. else:
  256. flash(u"Le vote a été créé", 'info')
  257. return redirect(url_for('edit_vote', voteid=vote['id']))
  258. else:
  259. flash(u'Vous devez spécifier un titre.', 'error')
  260. groups = query_db('select * from roles')
  261. return render_template('new_vote.html', groups=groups)
  262. @app.route('/votes/admin/edit/<voteid>', methods=['GET', 'POST'])
  263. def edit_vote(voteid):
  264. if not session.get('user').get('is_admin'):
  265. abort(401)
  266. vote = query_db('select * from votes where id = ?', [voteid], one=True)
  267. if vote is None:
  268. abort(404)
  269. if request.method == 'POST':
  270. if request.form['title']:
  271. # :TODO:maethor:120529: Calculer date_begin pour pouvoir y ajouter duration et obtenir date_end
  272. transparent = 0
  273. public = 0
  274. if 'transparent' in request.form.keys():
  275. transparent = 1
  276. if 'public' in request.form.keys():
  277. public = 1
  278. isopen = 0
  279. if request.form['status'] == 'Ouvert': # :TODO:maethor:20120529: Check if there is at least 2 choices before
  280. isopen = 1
  281. g.db.execute('update votes set title = ?, description = ?, category = ?, is_transparent = ?, is_public = ?, is_open = ? where id = ?',
  282. [request.form['title'], request.form['description'], request.form['category'], transparent, public, isopen, voteid])
  283. g.db.commit()
  284. vote = query_db('select * from votes where id = ?', [voteid], one=True)
  285. flash(u"Le vote a bien été mis à jour.", "success")
  286. else:
  287. flash(u'Vous devez spécifier un titre.', 'error')
  288. # :TODO:maethor:20120529: Calculer la durée du vote (différence date_end - date_begin)
  289. vote['duration'] = 15
  290. group = query_db('select name from roles where id = ?', [vote['id_role']], one=True)
  291. choices = query_db('select * from choices where id_vote = ?', [voteid])
  292. return render_template('edit_vote.html', vote=vote, group=group, choices=choices)
  293. @app.route('/votes/admin/addchoice/<voteid>', methods=['POST'])
  294. def add_choice(voteid):
  295. if not session.get('user').get('is_admin'):
  296. abort(401)
  297. vote = query_db('select * from votes where id = ?', [voteid], one=True)
  298. if vote is None:
  299. abort(404)
  300. g.db.execute('insert into choices (name, id_vote) values (?, ?)', [request.form['title'], voteid])
  301. g.db.commit()
  302. return redirect(url_for('edit_vote', voteid=voteid))
  303. @app.route('/votes/admin/editchoice/<voteid>/<choiceid>', methods=['POST', 'DELETE'])
  304. def edit_choice(voteid, choiceid):
  305. if not session.get('user').get('is_admin'):
  306. abort(401)
  307. choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
  308. if choice is None:
  309. abort(404)
  310. if request.method == 'POST':
  311. g.db.execute('update choices set name=? where id = ? and id_vote = ?', [request.form['title'], choiceid, voteid])
  312. g.db.commit()
  313. elif request.method == 'DELETE': # :COMMENT:maethor:20120528: I can't find how to use it from template
  314. g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
  315. g.db.commt()
  316. return redirect(url_for('edit_vote', voteid=voteid))
  317. @app.route('/votes/admin/deletechoice/<voteid>/<choiceid>')
  318. def delete_choice(voteid, choiceid):
  319. if not session.get('user').get('is_admin'):
  320. abort(401)
  321. choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
  322. if choice is None:
  323. abort(404)
  324. g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
  325. g.db.commit()
  326. return redirect(url_for('edit_vote', voteid=voteid))
  327. #------
  328. # Main
  329. if __name__ == '__main__':
  330. app.run()