Finished password lost
[cavote.git] / main.py
diff --git a/main.py b/main.py
index b3f50ba..74cb0f5 100755 (executable)
--- a/main.py
+++ b/main.py
@@ -4,15 +4,24 @@
 from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
 import sqlite3
-from datetime import date, timedelta
+from datetime import date, time, timedelta
+import time
 from contextlib import closing
 import locale
 locale.setlocale(locale.LC_ALL, '')
+import os
 import hashlib
+import smtplib
+import string
 
 DATABASE = '/tmp/cavote.db'
 SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
 DEBUG = True
+TITLE = u"Cavote FFDN"
+EMAIL = '"' + TITLE + '"' + ' <' + u"cavote@ffdn.org" + '>'
+BASEURL = "http://localhost:5000"
+VERSION = "cavote 0.0.1"
+SMTP_SERVER = "10.33.33.30"
 
 app = Flask(__name__)
 app.config.from_object(__name__)
@@ -51,7 +60,7 @@ def valid_login(username, password):
     return query_db('select * from users where email = ? and password = ?', [username, crypt(password)], one=True)
 
 def connect_user(user):
-    session['user'] = user # :KLUDGE:maethor:120528: Stoquer toute la ligne de la table users dans la session, c'est un peu crade
+    session['user'] = user
     del session['user']['password']
     del session['user']['key']
 
@@ -61,6 +70,9 @@ def disconnect_user():
 def crypt(passwd):
     return hashlib.sha1(passwd).hexdigest() 
 
+def keygen():
+    return hashlib.sha1(os.urandom(24)).hexdigest()
+
 def get_userid():
     user = session.get('user')
     if user is None: 
@@ -99,20 +111,43 @@ def password_lost():
         if user is None:
             flash('Cet utilisateur n\'existe pas !', 'error')
         else:
-            # :TODO:maethor:120528: Generer la cle, la mettre dans la base de données et envoyer le mail
+            key = keygen()
+            g.db.execute('update users set key = ? where id = ?', [key, user['id']])
+            g.db.commit()
+            link = BASEURL + url_for('login_key', userid=user['id'], key=key)
+            BODY = string.join((
+                "From: %s" % EMAIL,
+                "To: %s" % user['email'],
+                "Subject: [Cavote] Password lost",
+                "Date: %s" % time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()),
+                "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.",
+                "",
+                link,
+                "",
+                "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.quit()
             flash(u"Un mail a été envoyé à " + user['email'], 'info')
     return render_template('password_lost.html')
 
 @app.route('/login/<userid>/<key>')
 def login_key(userid, key):
     user = query_db('select * from users where id = ? and key = ?', [userid, key], one=True)
-    if user is None or key == "invalid":
+    if user is None or user['key'] == "invalid":
         abort(404)
     else:
         connect_user(user)
-        # :TODO:maethor:120528: Remplacer la clé pour qu'elle ne puisse plus être utilisée (invalid)
+        g.db.execute('update users set key = "invalid" where id = ?', [user['id']])
+        g.db.commit()
         flash(u"Veuillez mettre à jour votre mot de passe", 'info')
-        return redirect(url_for('user_password'), userid=user['userid'])
+        return redirect(url_for('user_password', userid=user['id']))
 
 #---------------
 # User settings
@@ -193,13 +228,12 @@ def admin_user_add():
             admin = 0
             if 'admin' in request.form.keys():
                 admin = 1
-            g.db.execute('insert into users (email, name, organization, password, is_admin) values (?, ?, ?, ?, ?)',
+            g.db.execute('insert into users (email, name, organization, password, is_admin, key) values (?, ?, ?, ?, ?, "invalid")',
                     [request.form['email'], request.form['username'], request.form['organization'], password, admin])
             g.db.commit()
             user = query_db('select * from users where email = ?', [request.form["email"]], one=True)
             if user:
               for group in request.form.getlist('groups'):
-                  # :TODO:maethor:120528: Check if this group exist
                   if query_db('select id from groups where id = ?', group, one=True) is None:
                       abort(401)
                   g.db.execute('insert into user_group values (?, ?)', [user['id'], group])
@@ -350,31 +384,34 @@ def admin_vote_add():
         abort(401)
     if request.method == 'POST':
         if request.form['title']:
-            date_begin = date.today()
-            date_end = date.today() + timedelta(days=int(request.form['days']))
-            transparent = 0
-            public = 0
-            multiplechoice = 0
-            if 'transparent' in request.form.keys():
-                transparent = 1
-            if 'public' in request.form.keys():
-                public = 1
-            if 'multiplechoice' in request.form.keys():
-                multiplechoice = 1
-            group = query_db('select id from groups where name = ?', [request.form['group']], one=True)
-            if group is None:
-                group[id] = 1
-            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', 
-                    [request.form['title'], date_begin], one=True) # :DEBUG:maethor:120528: Bug possible car le titre n'est pas unique
-            if vote is None:
-                flash(u'Une erreur est survenue !', 'error')
-                return redirect(url_for('home'))
+            if query_db('select * from votes where title = ?', [request.form['title']], one=True) is None:
+                date_begin = date.today()
+                date_end = date.today() + timedelta(days=int(request.form['days']))
+                transparent = 0
+                public = 0
+                multiplechoice = 0
+                if 'transparent' in request.form.keys():
+                    transparent = 1
+                if 'public' in request.form.keys():
+                    public = 1
+                if 'multiplechoice' in request.form.keys():
+                    multiplechoice = 1
+                group = query_db('select id from groups where name = ?', [request.form['group']], one=True)
+                if group is None:
+                    group[id] = 1
+                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', 
+                        [request.form['title'], date_begin], one=True)
+                if vote is None:
+                    flash(u'Une erreur est survenue !', 'error')
+                    return redirect(url_for('home'))
+                else:
+                    flash(u"Le vote a été créé", 'info')
+                    return redirect(url_for('admin_vote_edit', voteid=vote['id']))
             else:
-                flash(u"Le vote a été créé", 'info')
-                return redirect(url_for('admin_vote_edit', voteid=vote['id']))
+                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') 
@@ -397,8 +434,12 @@ def admin_vote_edit(voteid):
             if 'public' in request.form.keys():
                 public = 1
             isopen = 0
-            if request.form['status'] == 'Ouvert': # :TODO:maethor:120529: Check if there is at least 2 choices before
-                isopen = 1
+            if request.form['status'] == 'Ouvert':
+                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
+                else:
+                    flash(u'Vous devez proposer au moins deux choix pour ouvrir le vote.', 'error')
             g.db.execute('update votes set title = ?, description = ?, category = ?, is_transparent = ?, is_public = ?, is_open = ? where id = ?',
                     [request.form['title'], request.form['description'], request.form['category'], transparent, public, isopen, voteid])
             g.db.commit()
@@ -435,9 +476,6 @@ def admin_vote_editchoice(voteid, choiceid):
     if request.method == 'POST':
         g.db.execute('update choices set name=? where id = ? and id_vote = ?', [request.form['title'], choiceid, voteid])
         g.db.commit()
-    elif request.method == 'DELETE': # :COMMENT:maethor:120528: I can't find how to use it from template
-        g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
-        g.db.commt()
     return redirect(url_for('admin_vote_edit', voteid=voteid))
 
 @app.route('/admin/votes/deletechoice/<voteid>/<choiceid>')
@@ -449,6 +487,11 @@ def admin_vote_deletechoice(voteid, choiceid):
         abort(404)
     g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
     g.db.commit()
+    choices = query_db('select id_vote, count(*) as nb from choices where id_vote = ? group by id_vote', [voteid], one=True)
+    if choices is None or choices['nb'] < 2:
+        g.db.execute('update votes set is_open=0 where id = ?', [voteid])
+        g.db.commit()
+        flash(u'Attention ! Il y a moins de deux choix. Le vote a été fermé.', 'error')
     return redirect(url_for('admin_vote_edit', voteid=voteid))
 
 @app.route('/admin/votes/addattachment/<voteid>', methods=['POST'])