Administration des users et des votes
[cavote.git] / main.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from flask import Flask, request, session, g, redirect, url_for, abort, \
5 render_template, flash
6 import sqlite3
7 from datetime import date, timedelta
8 from contextlib import closing
9 import locale
10 locale.setlocale(locale.LC_ALL, '')
11
12 DATABASE = '/tmp/cavote.db'
13 SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
14 DEBUG = True
15
16 app = Flask(__name__)
17 app.config.from_object(__name__)
18
19 def connect_db():
20 return sqlite3.connect(app.config['DATABASE'])
21
22 @app.before_request
23 def before_request():
24 g.db = connect_db()
25
26 @app.teardown_request
27 def teardown_request(exception):
28 g.db.close()
29
30 @app.route('/')
31 def home():
32 return render_template('index.html', active_button="home")
33
34 def query_db(query, args=(), one=False):
35 cur = g.db.execute(query, args)
36 rv = [dict((cur.description[idx][0], value)
37 for idx, value in enumerate(row)) for row in cur.fetchall()]
38 return (rv[0] if rv else None) if one else rv
39
40 def init_db():
41 with closing(connect_db()) as db:
42 with app.open_resource('schema.sql') as f:
43 db.cursor().executescript(f.read())
44 db.commit()
45
46 #----------------
47 # Login / Logout
48
49 def valid_login(username, password):
50 return query_db('select * from users where email = ? and password = ?', [username, password], one=True)
51
52 def connect_user(user):
53 session['user'] = user # :KLUDGE:maethor:120528: Stoquer toute la ligne de la table users dans la session, c'est un peu crade…
54 #session['user']['id'] = user['id']
55 #session['user']['name'] = user['name']
56 #session['user']['email'] = user['email']
57 #session['user']['organization'] = user['organization']
58 #if user['is_admin'] == 1:
59 # session['user']['is_admin'] = True
60
61 def disconnect_user():
62 session.pop('user', None)
63
64 @app.route('/login', methods=['GET', 'POST'])
65 def login():
66 if request.method == 'POST':
67 user = valid_login(request.form['username'], request.form['password'])
68 if user is None:
69 flash('Invalid username/password', 'error')
70 else:
71 connect_user(user)
72 flash('You were logged in', 'success')
73 return redirect(url_for('home'))
74 return render_template('login.html')
75
76 @app.route('/logout')
77 def logout():
78 disconnect_user()
79 flash('You were logged out', 'info')
80 return redirect(url_for('home'))
81
82 #-----------------
83 # Change password
84
85 @app.route('/password/lost', methods=['GET', 'POST'])
86 def password_lost():
87 info = None
88 if request.method == 'POST':
89 user = query_db('select * from users where email = ?', [request.form['email']], one=True)
90 if user is None:
91 flash('Cet utilisateur n\'existe pas !', 'error')
92 else:
93 # :TODO:maethor:120528: Générer la clé, la mettre dans la base de données et envoyer le mail
94 flash(u"Un mail a été envoyé à " + user['email'], 'info')
95 return render_template('password_lost.html')
96
97 @app.route('/login/<userid>/<key>')
98 def login_key(userid, key):
99 user = query_db('select * from users where id = ? and key = ?', [userid, key], one=True)
100 if user is None or key == "invalid":
101 abort(404)
102 else:
103 connect_user(user)
104 # :TODO:maethor:120528: Remplacer la clé pour qu'elle ne puisse plus être utilisée (invalid)
105 flash(u"Veuillez mettre à jour votre mot de passe", 'info')
106 return redirect(url_for('user_password'), userid=user['userid'])
107
108 #---------------
109 # User settings
110
111 @app.route('/user/<userid>')
112 def show_user(userid):
113 if int(userid) != session.get('user').get('id'):
114 abort(401)
115 return render_template('show_user.html')
116
117 @app.route('/user/settings/<userid>', methods=['GET', 'POST'])
118 def user_settings(userid):
119 if int(userid) != session.get('user').get('id'):
120 abort(401)
121 if request.method == 'POST':
122 g.db.execute('update users set email = ?, name = ?, organization = ? where id = ?',
123 [request.form['email'], request.form['name'], request.form['organization'], session['user']['id']])
124 g.db.commit()
125 disconnect_user() # :TODO:maethor:120528: Maybe useless, but this is simple way to refresh session :D
126 flash(u'Votre profil a été mis à jour !', 'success')
127 return redirect(url_for('login'))
128 return render_template('user_settings.html')
129
130 @app.route('/user/password/<userid>', methods=['GET', 'POST'])
131 def user_password(userid):
132 if int(userid) != session.get('user').get('id'):
133 abort(401)
134 if request.method == 'POST':
135 if request.form['password'] == request.form['password2']:
136 # :TODO:maethor:120528: Chiffrer le mot de passe !
137 g.db.execute('update users set password = ? where id = ?', [request.form['password'], session['user']['id']])
138 g.db.commit()
139 flash(u'Votre mot de passe a été mis à jour.', 'success')
140 else:
141 flash(u'Les mots de passe sont différents.', 'error')
142 return render_template('user_settings.html')
143
144 #------------
145 # User admin
146
147 @app.route('/users/admin/list')
148 def admin_users():
149 if not session.get('user').get('is_admin'):
150 abort(401)
151 users = query_db('select * from users order by id desc')
152 return render_template('admin_users.html', users=users)
153
154 @app.route('/users/admin/add', methods=['GET', 'POST'])
155 def add_user():
156 if not session.get('user').get('is_admin'):
157 abort(401)
158 if request.method == 'POST':
159 if request.form['email']:
160 # :TODO:maethor:120528: Check fields
161 password = "toto" # :TODO:maethor:120528: Generate password
162 admin = 0
163 if 'admin' in request.form.keys():
164 admin = 1
165 g.db.execute('insert into users (email, name, organization, password, is_admin) values (?, ?, ?, ?, ?)',
166 [request.form['email'], request.form['username'], request.form['organization'], password, admin])
167 g.db.commit()
168 # :TODO:maethor:120528: Send mail
169 flash(u'Le nouvel utilisateur a été créé avec succès', 'success')
170 return redirect(url_for('home'))
171 else:
172 flash(u"Vous devez spécifier une adresse email.", 'error')
173 return render_template('add_user.html')
174
175 #-------------
176 # Roles admin
177
178 @app.route('/roles')
179 def show_roles():
180 if not session.get('user').get('is_admin'):
181 abort(401)
182 roles = query_db('select * from roles')
183 return render_template('show_roles.html', roles=roles)
184
185 @app.route('/roles/admin/add', methods=['POST'])
186 def add_role():
187 if not session.get('user').get('is_admin'):
188 abort(401)
189 if request.method == 'POST':
190 if request.form['name']:
191 g.db.execute('insert into roles (name) values (?)', [request.form['name']])
192 g.db.commit()
193 else:
194 flash(u"Vous devez spécifier un nom.", "error")
195 return redirect(url_for('show_roles'))
196
197 @app.route('/roles/admin/delete/<idrole>')
198 def del_role(idrole):
199 if not session.get('user').get('is_admin'):
200 abort(401)
201 role = query_db('select * from roles where id = ?', [idrole], one=True)
202 if role is None:
203 abort(404)
204 if role['system']:
205 abort(401)
206 g.db.execute('delete from roles where id = ?', [idrole])
207 g.db.commit()
208 return redirect(url_for('show_roles'))
209
210 #------------
211 # Votes list
212
213 @app.route('/votes/<votes>')
214 def show_votes(votes):
215 today = date.today()
216 active_button = votes
217 basequery = 'select *, roles.name as rolename from votes join roles on roles.id=votes.id_role where open=1'
218 if votes == 'all':
219 votes = query_db(basequery + ' order by id desc')
220 elif votes == 'archive':
221 votes = query_db(basequery + ' and date_end < (?) order by id desc', [today])
222 elif votes == 'current':
223 votes = query_db(basequery + ' and date_end >= (?) order by id desc', [today])
224 else:
225 abort(404)
226 return render_template('show_votes.html', votes=votes, active_button=active_button)
227
228 #------
229 # Vote
230
231 def can_see_vote(idvote, iduser=-1):
232 user = query_db('select * from users where id=?', [iduser], one=True)
233 vote = query_db('select * from votes where id=?', [idvote], one=True)
234 if user is None and not vote.is_public:
235 return False
236 return True # :TODO:maethor:20120529: Check others things
237
238 def can_vote(idvote, iduser=-1):
239 if not can_see_vote(idvote, iduser):
240 return False
241 return True # :TODO:maethor:20120529: Check others things
242
243 @app.route('/vote/<idvote>')
244 def show_vote(idvote):
245 vote = query_db('select *, roles.name as rolename from votes join roles on roles.id=votes.id_role where votes.id=?', [idvote], one=True)
246 if vote is None:
247 abort(404)
248 if can_see_vote(idvote, session.get('user').get('id')):
249 choices = query_db('select * from choices where id_vote=?', [idvote])
250 attachments = query_db('select * from attachments where id_vote=?', [idvote])
251 return render_template('vote.html', vote=vote, attachments=attachments, choices=choices, can_vote=can_vote(idvote, session.get('user').get('id')))
252 flash('Vous n\'avez pas le droit de voir ce vote, désolé.')
253 return(url_for('home'))
254
255 #-------------
256 # Votes admin
257
258 @app.route('/votes/admin/list')
259 def admin_votes():
260 if not session.get('user').get('is_admin'):
261 abort(401)
262 votes = query_db('select *, roles.name as rolename from votes join roles on roles.id=votes.id_role order by id desc')
263 return render_template('admin_votes.html', votes=votes)
264
265 @app.route('/votes/admin/add', methods=['GET', 'POST'])
266 def add_vote():
267 if not session.get('user').get('is_admin'):
268 abort(401)
269 if request.method == 'POST':
270 if request.form['title']:
271 date_begin = date.today()
272 date_end = date.today() + timedelta(days=int(request.form['days']))
273 transparent = 0
274 public = 0
275 multiplechoice = 0
276 if 'transparent' in request.form.keys():
277 transparent = 1
278 if 'public' in request.form.keys():
279 public = 1
280 if 'multiplechoice' in request.form.keys():
281 multiplechoice = 1
282 role = query_db('select id from roles where name = ?', [request.form['role']], one=True)
283 if role is None:
284 role[id] = 1
285 g.db.execute('insert into votes (title, description, category, date_begin, date_end, is_transparent, is_public, is_multiplechoice, id_role, id_author) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
286 [request.form['title'], request.form['description'], request.form['category'], date_begin, date_end, transparent, public, multiplechoice, role['id'], session['user']['id']])
287 g.db.commit()
288 vote = query_db('select * from votes where title = ? and date_begin = ? order by id desc',
289 [request.form['title'], date_begin], one=True) # :DEBUG:maethor:20120528: Bug possible car le titre n'est pas unique
290 if vote is None:
291 flash(u'Une erreur est survenue !', 'error')
292 return redirect(url_for('home'))
293 else:
294 flash(u"Le vote a été créé", 'info')
295 return redirect(url_for('edit_vote', voteid=vote['id']))
296 else:
297 flash(u'Vous devez spécifier un titre.', 'error')
298 groups = query_db('select * from roles')
299 return render_template('new_vote.html', groups=groups)
300
301 @app.route('/votes/admin/edit/<voteid>', methods=['GET', 'POST'])
302 def edit_vote(voteid):
303 if not session.get('user').get('is_admin'):
304 abort(401)
305 vote = query_db('select * from votes where id = ?', [voteid], one=True)
306 if vote is None:
307 abort(404)
308 if request.method == 'POST':
309 if request.form['title']:
310 # :TODO:maethor:120529: Calculer date_begin pour pouvoir y ajouter duration et obtenir date_end
311 transparent = 0
312 public = 0
313 if 'transparent' in request.form.keys():
314 transparent = 1
315 if 'public' in request.form.keys():
316 public = 1
317 isopen = 0
318 if request.form['status'] == 'Ouvert': # :TODO:maethor:20120529: Check if there is at least 2 choices before
319 isopen = 1
320 g.db.execute('update votes set title = ?, description = ?, category = ?, is_transparent = ?, is_public = ?, is_open = ? where id = ?',
321 [request.form['title'], request.form['description'], request.form['category'], transparent, public, isopen, voteid])
322 g.db.commit()
323 vote = query_db('select * from votes where id = ?', [voteid], one=True)
324 flash(u"Le vote a bien été mis à jour.", "success")
325 else:
326 flash(u'Vous devez spécifier un titre.', 'error')
327
328 # :TODO:maethor:20120529: Calculer la durée du vote (différence date_end - date_begin)
329 vote['duration'] = 15
330 group = query_db('select name from roles where id = ?', [vote['id_role']], one=True)
331 choices = query_db('select * from choices where id_vote = ?', [voteid])
332 return render_template('edit_vote.html', vote=vote, group=group, choices=choices)
333
334 @app.route('/votes/admin/addchoice/<voteid>', methods=['POST'])
335 def add_choice(voteid):
336 if not session.get('user').get('is_admin'):
337 abort(401)
338 vote = query_db('select * from votes where id = ?', [voteid], one=True)
339 if vote is None:
340 abort(404)
341 g.db.execute('insert into choices (name, id_vote) values (?, ?)', [request.form['title'], voteid])
342 g.db.commit()
343 return redirect(url_for('edit_vote', voteid=voteid))
344
345 @app.route('/votes/admin/editchoice/<voteid>/<choiceid>', methods=['POST', 'DELETE'])
346 def edit_choice(voteid, choiceid):
347 if not session.get('user').get('is_admin'):
348 abort(401)
349 choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
350 if choice is None:
351 abort(404)
352 if request.method == 'POST':
353 g.db.execute('update choices set name=? where id = ? and id_vote = ?', [request.form['title'], choiceid, voteid])
354 g.db.commit()
355 elif request.method == 'DELETE': # :COMMENT:maethor:20120528: I can't find how to use it from template
356 g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
357 g.db.commt()
358 return redirect(url_for('edit_vote', voteid=voteid))
359
360 @app.route('/votes/admin/deletechoice/<voteid>/<choiceid>')
361 def delete_choice(voteid, choiceid):
362 if not session.get('user').get('is_admin'):
363 abort(401)
364 choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
365 if choice is None:
366 abort(404)
367 g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
368 g.db.commit()
369 return redirect(url_for('edit_vote', voteid=voteid))
370
371 #------
372 # Main
373
374 if __name__ == '__main__':
375 app.run()
376