[PATCH] by julm - fix missing check that choice belongs to current vote
[cavote.git] / main.py
diff --git a/main.py b/main.py
index 4bbd46c..253fb87 100755 (executable)
--- a/main.py
+++ b/main.py
@@ -3,7 +3,8 @@
 
 from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
-from flaskext.openid import OpenID
+from flask_openid import OpenID
+from flaskext.babel import Babel, gettext, ngettext
 import sqlite3
 from datetime import date, time, timedelta, datetime
 import time
@@ -15,20 +16,13 @@ import hashlib
 import smtplib
 import string
 
-DATABASE = '/tmp/cavote.db'
-PASSWD_SALT = 'change this value to some random chars!'
-SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
-DEBUG = True
-TITLE = u"Cavote FFDN"
-EMAIL = '"' + TITLE + '"' + ' <' + u"cavote@ffdn.org" + '>'
-VERSION = "cavote 0.1.1"
-SMTP_SERVER = "127.0.0.1"
-PATTERNS = {u'Oui/Non': [u'Oui', u'Non'], u'Oui/Non/Blanc': [u'Oui', u'Non', u'Blanc'], u'Oui/Non/Peut-être': [u'Oui', u'Non', u'Peut-être']}
+from settings import *
 
 app = Flask(__name__)
 app.config.from_object(__name__)
 
 oid = OpenID(app)
+babel = Babel(app)
 
 def connect_db():
     return sqlite3.connect(app.config['DATABASE'])
@@ -93,7 +87,7 @@ def keygen():
 
 def get_userid():
     user = session.get('user')
-    if user is None: 
+    if user is None:
         return -1
     elif user.get('id') < 0:
         return -1
@@ -123,7 +117,7 @@ def create_or_login(resp):
     openid_url = resp.identity_url
     user = query_db('select * from users where openid = ?', [openid_url], one=True)
     if user is not None:
-        flash(u'Successfully signed in')
+        flash(gettext(u'Successfully signed in'))
         connect_user(user)
         return redirect(oid.get_next_url())
     return redirect(url_for('home'))
@@ -154,21 +148,22 @@ def password_lost():
             BODY = string.join((
                 "From: %s" % EMAIL,
                 "To: %s" % user['email'],
-                "Subject: [Cavote] Password lost",
+                "Subject: [Cavote] %s" % gettext(u"Lost password"),
                 "Date: %s" % time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()).decode('utf-8'),
+                "Content-type: text/plain; charset=utf-8",
                 "X-Mailer: %s" % VERSION,
                 "",
-                "You have lost your password.",
-                "This link will log you without password.",
-                "Don't forget to define a new one as soon a possible!",
-                "This link will only work one time.",
+                gettext(u"It seems that you have lost your password."),
+                gettext(u"This link will log you without password."),
+                gettext(u"Don't forget to define a new one as soon a possible!"),
+                gettext(u"This link will only work one time."),
                 "",
                 link,
                 "",
-                "If you think this mail is not for you, please ignore and delete it."
+                gettext(u"If you think this mail is not for you, please ignore and delete it.")
                 ), "\r\n")
             server = smtplib.SMTP(SMTP_SERVER)
-            server.sendmail(EMAIL, [user['email']], BODY)
+            server.sendmail(EMAIL, [user['email']], BODY.encode('utf-8'))
             server.quit()
             flash(u"Un mail a été envoyé à " + user['email'], 'info')
     return render_template('password_lost.html')
@@ -190,7 +185,7 @@ def login_key(userid, key):
 def user(userid):
     if int(userid) != get_userid():
         abort(401)
-    groups = query_db('select * from groups join user_group on id=id_group where id_user = ?', userid)
+    groups = query_db('select * from groups join user_group on id=id_group where id_user = ?', (userid,))
     return render_template('user.html', groups=groups)
 
 @app.route('/user/settings/<userid>', methods=['GET', 'POST'])
@@ -225,9 +220,7 @@ def user_password(userid):
             # new (invalid) key
             key = 'i%s' % keygen() # start with i: invalid key
             print "\n\nchange key for %s\n" % key # FIXME TMP
-            g.db.execute('update users set password = ?, key = ? where id = ?',
-                    [crypt(request.form['password'], key),
-                        key, session['user']['id']])
+            g.db.execute('update users set password = ?, key = ? where id = ?', [crypt(request.form['password'], key), key, session['user']['id']])
             g.db.commit()
             flash(u'Votre mot de passe a été mis à jour.', 'success')
         else:
@@ -290,20 +283,21 @@ def admin_user_add():
                             BODY = string.join((
                             "From: %s" % EMAIL,
                             "To: %s" % user['email'],
-                            "Subject: [Cavote] Welcome",
+                            "Subject: [Cavote] %s" % gettext(u"Welcome"),
                             "Date: %s" % time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()).decode('utf-8'),
+                            "Content-type: text/plain; charset=utf-8",
                             "X-Mailer: %s" % VERSION,
                             "",
-                            "Hi %s!" % user['name'],
-                            "Welcome on %s." % TITLE,
-                            "Your account's adresse is : %s." % user['email'],
+                            "%(text)s %(user)s!" % {"text": gettext(u"Hi"), "user": user['name']},
+                            "%(text2)s %(title)s." % {"text2": gettext(u"Welcome on"), "title": TITLE},
+                            "%(text3)s %(email)s." % {"text3": gettext(u"Your account address is"), "email": user['email']},
                             "",
-                            "To log in for the first time and set your password, please follow this link :",
+                            gettext(u"To log in for the first time and set your password, please follow this link :"),
                             link,
                             ""
                             ), "\r\n")
                             server = smtplib.SMTP(SMTP_SERVER)
-                            server.sendmail(EMAIL, [user['email']], BODY)
+                            server.sendmail(EMAIL, [user['email']], BODY.encode('utf-8'))
                             server.quit()
                             flash(u'Le nouvel utilisateur a été créé avec succès', 'success')
                             return redirect(url_for('admin_users'))
@@ -317,7 +311,7 @@ def admin_user_add():
                 flash(u'Il existe déjà un compte pour cette adresse e-mail : ' + request.form['email'], 'error')
         else:
             flash(u"Vous devez spécifier une adresse email.", 'error')
-    groups = query_db('select * from groups where system=0') 
+    groups = query_db('select * from groups where system=0')
     return render_template('admin_user_new.html', groups=groups)
 
 @app.route('/admin/users/edit/<iduser>', methods=['GET', 'POST'])
@@ -358,7 +352,7 @@ def admin_user_edit(iduser):
                 flash(u'Le nom ' + request.form['name'] + u' est déjà pris ! Veuillez en choisir un autre.', 'error')
         else:
             flash(u'Il existe déjà un compte pour cette adresse e-mail : ' + request.form['email'], 'error')
-    groups = query_db('select * from groups where system=0') 
+    groups = query_db('select * from groups where system=0')
     return render_template('admin_user_edit.html', user=user, groups=groups)
 
 @app.route('/admin/users/delete/<iduser>')
@@ -418,7 +412,7 @@ def votes(votes):
     basequery = 'select votes.*, max_votes from votes left join (' + max_votes + ') as max_votes on votes.id_group = max_votes.id_group'
     nb_votes = 'select id_vote, count(*) as nb_votes from (select id_user, id_vote from user_choice join choices on id_choice = choices.id group by id_user, id_vote) group by id_vote'
     basequery = 'select * from (' + basequery + ') left join (' + nb_votes + ') on id = id_vote'
-    basequery = 'select *, votes.id as voteid, groups.name as groupname from (' + basequery + ') as votes join groups on groups.id = id_group where is_open=1'
+    basequery = 'select *, votes.id as voteid, groups.name as groupname from (' + basequery + ') as votes join groups on groups.id = id_group where is_open=1 and is_hidden=0'
     if votes == 'all':
         votes = query_db(basequery + ' order by date_end')
     elif votes == 'archive':
@@ -433,7 +427,7 @@ def votes(votes):
         abort(404)
     for vote in votes:
         if not vote.get('nb_votes'):
-            vote['nb_votes'] = 0 
+            vote['nb_votes'] = 0
         if vote.get('max_votes'):
             vote['percent'] = int((float(vote['nb_votes']) / float(vote['max_votes'])) * 100)
     return render_template('votes.html', votes=votes, active_button=active_button)
@@ -456,8 +450,8 @@ def can_vote(idvote, iduser=-1):
     if vote is None:
         return False
     if vote['is_terminated'] == 0:
-        if iduser > 0: 
-            if can_see_vote(idvote, iduser): 
+        if iduser > 0:
+            if can_see_vote(idvote, iduser):
                 if not has_voted(idvote, iduser):
                     if query_db('select * from user_group where id_user = ? and id_group = ?', [iduser, vote['id_group']], one=True):
                         return True
@@ -473,18 +467,20 @@ def vote(idvote):
     if vote is None:
         abort(404)
     if can_see_vote(idvote, get_userid()):
+        choices = query_db('select name, id from choices where id_vote=?', [idvote])
         if request.method == 'POST':
             if can_vote(idvote, get_userid()):
                 if vote['is_multiplechoice'] == 0:
-                    if query_db('select * from choices where id = ?', [request.form['choice']], one=True) is not None:
-                        g.db.execute('insert into user_choice (id_user, id_choice) values (?, ?)', 
-                                [session.get('user').get('id'), request.form['choice']])
+                    choice = request.form['choice']
+                    if choice in [str(c['id']) for c in choices] \
+                        and query_db('select * from choices where id = ?', [choice], one=True) is not None:
+                        g.db.execute('insert into user_choice (id_user, id_choice) values (?, ?)',
+                        [session.get('user').get('id'), request.form['choice']])
                         g.db.commit()
                 else:
-                    choices = query_db('select name, id from choices where id_vote=?', [idvote])
                     for choice in choices:
                         if str(choice['id']) in request.form.keys():
-                            g.db.execute('insert into user_choice (id_user, id_choice) values (?, ?)', 
+                            g.db.execute('insert into user_choice (id_user, id_choice) values (?, ?)',
                                     [session.get('user').get('id'), choice['id']])
                             g.db.commit()
             else:
@@ -535,7 +531,7 @@ def vote_deletechoices(idvote, iduser):
 def admin_votes():
     if not session.get('user').get('is_admin'):
         abort(401)
-    votes = query_db('select *, votes.id as voteid, groups.name as groupname from votes join groups on groups.id=votes.id_group order by id desc')
+    votes = query_db('select *, votes.id as voteid, groups.name as groupname from votes join groups on groups.id=votes.id_group where is_hidden=0 order by id desc')
     return render_template('admin_votes.html', votes=votes, today=date.today().strftime("%Y-%m-%d"))
 
 @app.route('/admin/votes/add', methods=['GET', 'POST'])
@@ -562,7 +558,7 @@ def admin_vote_add():
                 g.db.execute('insert into votes (title, description, category, date_begin, date_end, is_transparent, is_public, is_multiplechoice, id_group, id_author) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
                         [request.form['title'], request.form['description'], request.form['category'], date_begin, date_end, transparent, public, multiplechoice, group['id'], session['user']['id']])
                 g.db.commit()
-                vote = query_db('select * from votes where title = ? and date_begin = ? order by id desc', 
+                vote = query_db('select * from votes where title = ? and date_begin = ? order by id desc',
                         [request.form['title'], date_begin], one=True)
                 if vote is None:
                     flash(u'Une erreur est survenue !', 'error')
@@ -579,7 +575,7 @@ def admin_vote_add():
                 flash(u'Le titre que vous avez choisi est déjà pris.', 'error')
         else:
             flash(u'Vous devez spécifier un titre.', 'error')
-    groups = query_db('select * from groups') 
+    groups = query_db('select * from groups')
     return render_template('admin_vote_new.html', groups=groups, patterns=PATTERNS)
 
 @app.route('/admin/votes/edit/<voteid>', methods=['GET', 'POST'])
@@ -606,28 +602,60 @@ def admin_vote_edit(voteid):
                 choices = query_db('select id_vote, count(*) as nb from choices where id_vote = ? group by id_vote', [voteid], one=True)
                 if choices is not None and choices['nb'] >= 2:
                     isopen = 1
+                    previousvote = query_db('select id, is_open, id_group from votes where id = ?', [voteid], one=True)
+                    if previousvote is None or previousvote['is_open'] == 0:
+                        users_to_vote = query_db('select users.email, users.name from users join user_group on users.id=user_group.id_user where user_group.id_group = ?', [previousvote['id_group']])
+                        for user in users_to_vote:
+                            link = request.url_root + url_for('vote', idvote=voteid)
+                            BODY = string.join((
+                                "From: %s" % EMAIL,
+                                "To: %s" % user['email'],
+                                "Subject: [Cavote] %s" % gettext(u"A vote has been opened for your group"),
+                                "Date: %s" % time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()).decode('utf-8'),
+                                "Content-type: text/plain; charset=utf-8",
+                                "X-Mailer: %s" % VERSION,
+                                "",
+                                "%(text)s %(title)s" % {"text": gettext(u"A vote has been opened and you are in a group concerned by it :"), "title": request.form['title']},
+                                "",
+                                gettext(u"This link will bring you to the form where you will be able to vote :"),
+                                link,
+                                "",
+                                gettext(u"If you think this mail is not for you, please ignore and delete it.")
+                                ), "\r\n")
+                            server = smtplib.SMTP(SMTP_SERVER)
+                            server.sendmail(EMAIL, [user['email']], BODY.encode('utf-8'))
+                            server.quit()
                 else:
                     flash(u'Vous devez proposer au moins deux choix pour ouvrir le vote.', 'error')
             elif request.form['status'] == u'Terminé':
                 isterminated = 1
                 if vote['is_open']:
                     isopen = 1
-            g.db.execute('update votes set title = ?, description = ?, category = ?, is_transparent = ?, is_public = ?, is_open = ?, is_terminated = ?, date_end = ? where id = ?',
-                    [request.form['title'], request.form['description'], request.form['category'], transparent, public, isopen, isterminated, date_end, voteid])
+            g.db.execute('update votes set title = ?, description = ?, category = ?, is_transparent = ?, is_public = ?, is_open = ?, is_terminated = ?, date_end = ?, reminder_last_days = ? where id = ?', [request.form['title'], request.form['description'], request.form['category'], transparent, public, isopen, isterminated, date_end, request.form['reminder'], voteid])
             g.db.commit()
             vote = query_db('select * from votes where id = ?', [voteid], one=True)
             flash(u"Le vote a bien été mis à jour.", "success")
         else:
             flash(u'Vous devez spécifier un titre.', 'error')
-    vote['duration'] = (datetime.strptime(vote['date_end'], "%Y-%m-%d") 
-            - datetime.strptime(vote['date_begin'], "%Y-%m-%d")).days
-    group = query_db('select name from groups where id = ?', [vote['id_group']], one=True) 
+    vote['duration'] = (datetime.strptime(vote['date_end'], "%Y-%m-%d") - datetime.strptime(vote['date_begin'], "%Y-%m-%d")).days
+    group = query_db('select name from groups where id = ?', [vote['id_group']], one=True)
     choices = query_db('select * from choices where id_vote = ?', [voteid])
     attachments = query_db('select * from attachments where id_vote = ?', [voteid])
     if date.today().strftime("%Y-%m-%d") > vote['date_end']:
         flash(u'La deadline du vote est expirée, vous devriez terminer le vote.')
     return render_template('admin_vote_edit.html', vote=vote, group=group, choices=choices, attachments=attachments)
 
+@app.route('/admin/votes/delete/<idvote>')
+def admin_vote_del(idvote):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    vote = query_db('select * from votes where id = ?', [idvote], one=True)
+    if vote is None:
+        abort(404)
+    g.db.execute('update votes set is_hidden=1 where id = ?', [idvote])
+    g.db.commit()
+    return redirect(url_for('admin_votes'))
+
 @app.route('/admin/votes/addchoice/<voteid>', methods=['POST'])
 def admin_vote_addchoice(voteid):
     if not session.get('user').get('is_admin'):
@@ -694,4 +722,3 @@ def admin_vote_deleteattachment(voteid, attachmentid):
 
 if __name__ == '__main__':
     app.run()
-