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