Admin roles
[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')
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/add', methods=['GET', 'POST'])
148 def add_user():
149 if not session.get('user').get('is_admin'):
150 abort(401)
151 if request.method == 'POST':
152 if request.form['email']:
153 # :TODO:maethor:120528: Check fields
154 password = "toto" # :TODO:maethor:120528: Generate password
155 admin = 0
156 if 'admin' in request.form.keys():
157 admin = 1
158 g.db.execute('insert into users (email, name, organization, password, is_admin) values (?, ?, ?, ?, ?)',
159 [request.form['email'], request.form['username'], request.form['organization'], password, admin])
160 g.db.commit()
161 # :TODO:maethor:120528: Send mail
162 flash(u'Le nouvel utilisateur a été créé avec succès', 'success')
163 return redirect(url_for('home'))
164 else:
165 flash(u"Vous devez spécifier une adresse email.", 'error')
166 return render_template('add_user.html')
167
168 #-------------
169 # Roles admin
170
171 @app.route('/roles')
172 def show_roles():
173 if not session.get('user').get('is_admin'):
174 abort(401)
175 roles = query_db('select * from roles')
176 return render_template('show_roles.html', roles=roles)
177
178 @app.route('/roles/admin/add', methods=['POST'])
179 def add_role():
180 if not session.get('user').get('is_admin'):
181 abort(401)
182 if request.method == 'POST':
183 if request.form['name']:
184 g.db.execute('insert into roles (name) values (?)', [request.form['name']])
185 g.db.commit()
186 else:
187 flash(u"Vous devez spécifier un nom.", "error")
188 return redirect(url_for('show_roles'))
189
190 @app.route('/roles/admin/delete/<idrole>')
191 def del_role(idrole):
192 if not session.get('user').get('is_admin'):
193 abort(401)
194 role = query_db('select * from roles where id = ?', [idrole], one=True)
195 if role is None:
196 abort(404)
197 if role['system']:
198 abort(401)
199 g.db.execute('delete from roles where id = ?', [idrole])
200 g.db.commit()
201 return redirect(url_for('show_roles'))
202
203 #------------
204 # Votes list
205
206 @app.route('/votes/<votes>')
207 def show_votes(votes):
208 today = date.today()
209 if votes == 'all':
210 votes = query_db('select title, description, date_begin, date_end from votes order by id desc')
211 elif votes == 'archive':
212 votes = query_db('select title, description, date_begin, date_end from votes where date_end < (?) order by id desc', [today])
213 elif votes == 'current':
214 votes = query_db('select title, description, date_begin, date_end from votes where date_end >= (?) order by id desc', [today])
215 else:
216 abort(404)
217 return render_template('show_votes.html', votes=votes)
218
219 #-------------
220 # Votes admin
221
222 @app.route('/votes/admin/add', methods=['GET', 'POST'])
223 def add_vote():
224 if not session.get('user').get('is_admin'):
225 abort(401)
226 if request.method == 'POST':
227 if request.form['title']:
228 date_begin = date.today()
229 date_end = date.today() + timedelta(days=int(request.form['days']))
230 transparent = 0
231 public = 0
232 multiplechoice = 0
233 if 'transparent' in request.form.keys():
234 transparent = 1
235 if 'public' in request.form.keys():
236 public = 1
237 if 'multiplechoice' in request.form.keys():
238 multiplechoice = 1
239 role = query_db('select id from roles where name = ?', [request.form['role']], one=True)
240 if role is None:
241 role[id] = 1
242 g.db.execute('insert into votes (title, description, category, date_begin, date_end, is_transparent, is_public, is_multiplechoice, id_role, id_author) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
243 [request.form['title'], request.form['description'], request.form['category'], date_begin, date_end, transparent, public, multiplechoice, role['id'], session['user']['id']])
244 g.db.commit()
245 vote = query_db('select * from votes where title = ? and date_begin = ? order by id desc',
246 [request.form['title'], date_begin], one=True) # :DEBUG:maethor:20120528: Bug possible car le titre n'est pas unique
247 if vote is None:
248 flash(u'Une erreur est survenue !', 'error')
249 return redirect(url_for('home'))
250 else:
251 flash(u"Le vote a été créé", 'info')
252 return redirect(url_for('edit_vote', voteid=vote['id']))
253 else:
254 flash(u'Vous devez spécifier un titre.', 'error')
255 groups = query_db('select * from roles')
256 return render_template('new_vote.html', groups=groups)
257
258 @app.route('/votes/admin/edit/<voteid>', methods=['GET', 'POST'])
259 def edit_vote(voteid):
260 if not session.get('user').get('is_admin'):
261 abort(401)
262 vote = query_db('select * from votes where id = ?', [voteid], one=True)
263 if vote is None:
264 abort(404)
265 if request.method == 'POST':
266 if request.form['title']:
267 # :TODO:maethor:120529: Calculer date_begin pour pouvoir y ajouter duration et obtenir date_end
268 transparent = 0
269 public = 0
270 if 'transparent' in request.form.keys():
271 transparent = 1
272 if 'public' in request.form.keys():
273 public = 1
274 isopen = 0
275 if request.form['status'] == 'Ouvert':
276 isopen = 1
277 g.db.execute('update votes set title = ?, description = ?, category = ?, is_transparent = ?, is_public = ?, is_open = ? where id = ?',
278 [request.form['title'], request.form['description'], request.form['category'], transparent, public, isopen, voteid])
279 g.db.commit()
280 vote = query_db('select * from votes where id = ?', [voteid], one=True)
281 flash(u"Le vote a bien été mis à jour.", "success")
282 else:
283 flash(u'Vous devez spécifier un titre.', 'error')
284
285 # :TODO:maethor:20120529: Calculer la durée du vote (différence date_end - date_begin)
286 vote['duration'] = 15
287 group = query_db('select name from roles where id = ?', [vote['id_role']], one=True)
288 choices = query_db('select * from choices where id_vote = ?', [voteid])
289 return render_template('edit_vote.html', vote=vote, group=group, choices=choices)
290
291 @app.route('/votes/admin/addchoice/<voteid>', methods=['POST'])
292 def add_choice(voteid):
293 if not session.get('user').get('is_admin'):
294 abort(401)
295 vote = query_db('select * from votes where id = ?', [voteid], one=True)
296 if vote is None:
297 abort(404)
298 g.db.execute('insert into choices (name, id_vote) values (?, ?)', [request.form['title'], voteid])
299 g.db.commit()
300 return redirect(url_for('edit_vote', voteid=voteid))
301
302 @app.route('/votes/admin/editchoice/<voteid>/<choiceid>', methods=['POST', 'DELETE'])
303 def edit_choice(voteid, choiceid):
304 if not session.get('user').get('is_admin'):
305 abort(401)
306 choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
307 if choice is None:
308 abort(404)
309 if request.method == 'POST':
310 g.db.execute('update choices set name=? where id = ? and id_vote = ?', [request.form['title'], choiceid, voteid])
311 g.db.commit()
312 elif request.method == 'DELETE': # :COMMENT:maethor:20120528: I can't find how to use it from template
313 g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
314 g.db.commt()
315 return redirect(url_for('edit_vote', voteid=voteid))
316
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 #------
329 # Main
330
331 if __name__ == '__main__':
332 app.run()
333