Attachments
[cavote.git] / main.py
diff --git a/main.py b/main.py
index 57c876b..a807a51 100755 (executable)
--- a/main.py
+++ b/main.py
@@ -5,14 +5,14 @@ from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash
 import sqlite3
 from datetime import date, timedelta
+from contextlib import closing
 import locale
 locale.setlocale(locale.LC_ALL, '')
+import hashlib
 
 DATABASE = '/tmp/cavote.db'
 SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
 DEBUG = True
-USERNAME = 'admin'
-PASSWORD = 'admin'
 
 app = Flask(__name__)
 app.config.from_object(__name__)
@@ -30,50 +30,403 @@ def teardown_request(exception):
 
 @app.route('/')
 def home():
-    return render_template('index.html')
-
-@app.route('/admin/votes')
-def show_votes():
-    cur = g.db.execute('select title, description, date from votes order by id desc')
-    votes = [dict(title=row[0], description=row[1], date=row[2]) for row in cur.fetchall()]
-    return render_template('show_votes.html', votes=votes)
-
-@app.route('/admin/vote/add', methods=['POST'])
-def add_vote():
-    if not session.get('logged_in'):
-        abort(401)
-    daten = date.today() + timedelta(days=60)
-    ndate = daten.strftime('%d %B %Y')
-    g.db.execute('insert into votes (title, description, date) values (?, ?, ?)',
-            [request.form['title'], request.form['description'], ndate])
-    g.db.commit()
-    flash('New entry was successfully posted')
-    return redirect(url_for('home'))
+    return render_template('index.html', active_button="home")
+
+def query_db(query, args=(), one=False):
+    cur = g.db.execute(query, args)
+    rv = [dict((cur.description[idx][0], value)
+        for idx, value in enumerate(row)) for row in cur.fetchall()]
+    return (rv[0] if rv else None) if one else rv
+
+def init_db():
+    with closing(connect_db()) as db:
+        with app.open_resource('schema.sql') as f:
+            db.cursor().executescript(f.read())
+        db.commit()
+
+#----------------
+# Login / Logout
+
+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
+    del session['user']['password']
+    del session['user']['key']
+
+def disconnect_user():
+    session.pop('user', None)
+
+def crypt(passwd):
+    return hashlib.sha1(passwd).hexdigest() 
 
 @app.route('/login', methods=['GET', 'POST'])
 def login():
-    error = None
     if request.method == 'POST':
-        if request.form['username'] != app.config['USERNAME']:
-            error = 'Invalid username'
-        elif request.form['password'] != app.config['PASSWORD']:
-            error = 'Invalid password'
+        user = valid_login(request.form['username'], request.form['password'])
+        if user is None:
+            flash('Invalid username/password', 'error')
         else:
-            session['logged_in'] = True
-            session['nickname'] = request.form['username']
-            flash('You were logged in')
+            connect_user(user)
+            flash('You were logged in', 'success')
             return redirect(url_for('home'))
-    return render_template('login.html', error=error)
+    return render_template('login.html')
 
 @app.route('/logout')
 def logout():
-    session.pop('logged_in', None)
-    flash('You were logged out')
+    disconnect_user()
+    flash('You were logged out', 'info')
     return redirect(url_for('home'))
 
+#-----------------
+# Change password
+
+@app.route('/password/lost', methods=['GET', 'POST'])
+def password_lost():
+    info = None
+    if request.method == 'POST':
+        user = query_db('select * from users where email = ?', [request.form['email']], one=True)
+        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
+            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":
+        abort(404)
+    else:
+        connect_user(user)
+        # :TODO:maethor:120528: Remplacer la clé pour qu'elle ne puisse plus être utilisée (invalid)
+        flash(u"Veuillez mettre à jour votre mot de passe", 'info')
+        return redirect(url_for('user_password'), userid=user['userid'])
+
+#---------------
+# User settings
+
+@app.route('/user/<userid>')
+def user(userid):
+    if int(userid) != session.get('user').get('id'):
+        abort(401)
+    groups = query_db('select * from roles join user_role on id=id_role where id_user = ?', userid)
+    return render_template('user.html', groups=groups)
+
+@app.route('/user/settings/<userid>', methods=['GET', 'POST'])
+def user_edit(userid):
+    if int(userid) != session.get('user').get('id'):
+        abort(401)
+    if request.method == 'POST':
+        if query_db('select * from users where email=? and id!=?', [request.form['email'], userid], one=True) is None:
+            if query_db('select * from users where name=? and id!=?', [request.form['name'], userid], one=True) is None:
+                g.db.execute('update users set email = ?, name = ?, organization = ? where id = ?',
+                        [request.form['email'], request.form['name'], request.form['organization'], session['user']['id']])
+                g.db.commit()
+                disconnect_user() # :TODO:maethor:120528: Maybe useless, but this is simple way to refresh session :D
+                user = query_db('select * from users where id=?', [userid], one=True)
+                if user is None:
+                    flash(u'Une erreur s\'est produite.', 'error')
+                    return redirect(url_for('login'))
+                connect_user(user)
+                flash(u'Votre profil a été mis à jour !', 'success')
+            else:
+                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')
+    return render_template('user_edit.html')
+
+@app.route('/user/password/<userid>', methods=['GET', 'POST'])
+def user_password(userid):
+    if int(userid) != session.get('user').get('id'):
+        abort(401)
+    if request.method == 'POST':
+        if request.form['password'] == request.form['password2']:
+            g.db.execute('update users set password = ? where id = ?', [crypt(request.form['password']), session['user']['id']])
+            g.db.commit()
+            flash(u'Votre mot de passe a été mis à jour.', 'success')
+        else:
+            flash(u'Les mots de passe sont différents.', 'error')
+    return render_template('user_edit.html')
+
+#------------
+# User admin
+
+@app.route('/admin/users')
+def admin_users():
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    tuples = query_db('select *, roles.name as rolename from (select *, id as userid, name as username from users join user_role on id=id_user order by id desc) join roles on id_role=roles.id')
+    users = dict()
+    for t in tuples:
+        if t['userid'] in users:
+            users[t['userid']]['roles'].append(t["rolename"])
+        else:
+            users[t['userid']] = dict()
+            users[t['userid']]['userid'] = t['userid']
+            users[t['userid']]['email'] = t['email']
+            users[t['userid']]['username'] = t['username']
+            users[t['userid']]['is_admin'] = t['is_admin']
+            users[t['userid']]['roles'] = [t['rolename']]
+
+    return render_template('admin_users.html', users=users.values())
+
+@app.route('/admin/users/add', methods=['GET', 'POST'])
+def admin_user_add():
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    if request.method == 'POST':
+        if request.form['email']:
+            # :TODO:maethor:120528: Check fields
+            password = "toto" # :TODO:maethor:120528: Generate password
+            admin = 0
+            if 'admin' in request.form.keys():
+                admin = 1
+            g.db.execute('insert into users (email, name, organization, password, is_admin) values (?, ?, ?, ?, ?)',
+                    [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 role in request.form.getlist('roles'):
+                  # :TODO:maethor:120528: Check if this role exist
+                  if query_db('select id from roles where id = ?', role, one=True) is None:
+                      abort(401)
+                  g.db.execute('insert into user_role values (?, ?)', [user['id'], role])
+                  g.db.commit()
+              # :TODO:maethor:120528: Send mail
+              flash(u'Le nouvel utilisateur a été créé avec succès', 'success')
+              return redirect(url_for('admin_users'))
+            else:
+                flash(u'Une erreur s\'est produite.', 'error')
+        else:
+            flash(u"Vous devez spécifier une adresse email.", 'error')
+    groups = query_db('select * from roles where system=0') 
+    return render_template('admin_user_new.html', groups=groups)
+
+#-------------
+# Roles admin
+
+@app.route('/admin/roles')
+def admin_roles():
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    roles = query_db('select * from roles')
+    return render_template('admin_roles.html', roles=roles)
+
+@app.route('/admin/roles/add', methods=['POST'])
+def admin_role_add():
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    if request.method == 'POST':
+        if request.form['name']:
+            g.db.execute('insert into roles (name) values (?)', [request.form['name']])
+            g.db.commit()
+        else:
+            flash(u"Vous devez spécifier un nom.", "error")
+    return redirect(url_for('admin_roles'))
+
+@app.route('/admin/roles/delete/<idrole>')
+def admin_role_del(idrole):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    role = query_db('select * from roles where id = ?', [idrole], one=True)
+    if role is None:
+        abort(404)
+    if role['system']:
+        abort(401)
+    g.db.execute('delete from roles where id = ?', [idrole])
+    g.db.commit()
+    return redirect(url_for('admin_roles'))
+
+#------------
+# Votes list
+
+@app.route('/votes/<votes>')
+def votes(votes):
+    today = date.today()
+    active_button = votes
+    basequery = 'select *, roles.name as rolename from votes join roles on roles.id=votes.id_role where is_open=1'
+    if votes == 'all':
+        votes = query_db(basequery + ' order by id desc')
+    elif votes == 'archive':
+        votes = query_db(basequery + ' and date_end < (?) order by id desc', [today])
+    elif votes == 'current':
+        votes = query_db(basequery + ' and date_end >= (?) order by id desc', [today])
+    else:
+        abort(404)
+    return render_template('votes.html', votes=votes, active_button=active_button)
+
+#------
+# Vote
+
+def can_see_vote(idvote, iduser=-1):
+    user = query_db('select * from users where id=?', [iduser], one=True)
+    vote = query_db('select * from votes where id=?', [idvote], one=True)
+    if user is None and not vote.is_public:
+        return False
+    return True # :TODO:maethor:120529: Check others things
+
+def can_vote(idvote, iduser=-1):
+    if not can_see_vote(idvote, iduser):
+        return False
+    return True # :TODO:maethor:120529: Check others things
 
+@app.route('/vote/<idvote>')
+def vote(idvote):
+    vote = query_db('select *, roles.name as rolename from votes join roles on roles.id=votes.id_role where votes.id=?', [idvote], one=True)
+    if vote is None:
+        abort(404)
+    if can_see_vote(idvote, session.get('user').get('id')):
+        choices = query_db('select * from choices where id_vote=?', [idvote])
+        attachments = query_db('select * from attachments where id_vote=?', [idvote])
+        return render_template('vote.html', vote=vote, attachments=attachments, choices=choices, can_vote=can_vote(idvote, session.get('user').get('id')))
+    flash('Vous n\'avez pas le droit de voir ce vote, désolé.')
+    return(url_for('home'))
+
+#-------------
+# Votes admin
+
+@app.route('/admin/votes/list')
+def admin_votes():
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    votes = query_db('select *, roles.name as rolename from votes join roles on roles.id=votes.id_role order by id desc')
+    return render_template('admin_votes.html', votes=votes)
+
+@app.route('/admin/votes/add', methods=['GET', 'POST'])
+def admin_vote_add():
+    if not session.get('user').get('is_admin'):
+        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
+            role = query_db('select id from roles where name = ?', [request.form['role']], one=True)
+            if role is None:
+                role[id] = 1
+            g.db.execute('insert into votes (title, description, category, date_begin, date_end, is_transparent, is_public, is_multiplechoice, id_role, id_author) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
+                    [request.form['title'], request.form['description'], request.form['category'], date_begin, date_end, transparent, public, multiplechoice, role['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'))
+            else:
+                flash(u"Le vote a été créé", 'info')
+                return redirect(url_for('admin_vote_edit', voteid=vote['id']))
+        else:
+            flash(u'Vous devez spécifier un titre.', 'error')
+    groups = query_db('select * from roles') 
+    return render_template('admin_vote_new.html', groups=groups)
+
+@app.route('/admin/votes/edit/<voteid>', methods=['GET', 'POST'])
+def admin_vote_edit(voteid):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    vote = query_db('select * from votes where id = ?', [voteid], one=True)
+    if vote is None:
+        abort(404)
+    if request.method == 'POST':
+        if request.form['title']:
+            # :TODO:maethor:120529: Calculer date_begin pour pouvoir y ajouter duration et obtenir date_end
+            transparent = 0
+            public = 0
+            if 'transparent' in request.form.keys():
+                transparent = 1
+            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
+            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()
+            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')
+
+    # :TODO:maethor:120529: Calculer la durée du vote (différence date_end - date_begin) 
+    vote['duration'] = 15
+    group = query_db('select name from roles where id = ?', [vote['id_role']], one=True) 
+    choices = query_db('select * from choices where id_vote = ?', [voteid])
+    attachments = query_db('select * from attachments where id_vote = ?', [voteid])
+    return render_template('admin_vote_edit.html', vote=vote, group=group, choices=choices, attachments=attachments)
+
+@app.route('/admin/votes/addchoice/<voteid>', methods=['POST'])
+def admin_vote_addchoice(voteid):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    vote = query_db('select * from votes where id = ?', [voteid], one=True)
+    if vote is None:
+        abort(404)
+    g.db.execute('insert into choices (name, id_vote) values (?, ?)', [request.form['title'], voteid])
+    g.db.commit()
+    return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+@app.route('/admin/votes/editchoice/<voteid>/<choiceid>', methods=['POST', 'DELETE'])
+def admin_vote_editchoice(voteid, choiceid):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
+    if choice is None:
+        abort(404)
+    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>')
+def admin_vote_deletechoice(voteid, choiceid):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    choice = query_db('select * from choices where id = ? and id_vote = ?', [choiceid, voteid], one=True)
+    if choice is None:
+        abort(404)
+    g.db.execute('delete from choices where id = ? and id_vote = ?', [choiceid, voteid])
+    g.db.commit()
+    return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+@app.route('/admin/votes/addattachment/<voteid>', methods=['POST'])
+def admin_vote_addattachment(voteid):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    vote = query_db('select * from votes where id = ?', [voteid], one=True)
+    if vote is None:
+        abort(404)
+    g.db.execute('insert into attachments (url, id_vote) values (?, ?)', [request.form['url'], voteid])
+    g.db.commit()
+    return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+@app.route('/admin/votes/deleteattachment/<voteid>/<attachmentid>')
+def admin_vote_deleteattachment(voteid, attachmentid):
+    if not session.get('user').get('is_admin'):
+        abort(401)
+    attachment = query_db('select * from attachments where id = ? and id_vote = ?', [attachmentid, voteid], one=True)
+    if attachment is None:
+        abort(404)
+    g.db.execute('delete from attachments where id = ? and id_vote = ?', [attachmentid, voteid])
+    g.db.commit()
+    return redirect(url_for('admin_vote_edit', voteid=voteid))
+
+#------
+# Main
 
 if __name__ == '__main__':
     app.run()
 
-