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__)
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']
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:
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
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])
def votes(votes):
today = date.today()
active_button = votes
- basequery = 'select *, votes.id as voteid, groups.name as groupname from votes join groups on groups.id = id_group where is_open=1'
+ max_votes ='select id_group, count(*) as max_votes from user_group group by id_group'
+ basequery = 'select votes.*, max_votes from votes 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 + ') 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'
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])
else:
abort(404)
+ for vote in votes:
+ vote['percent'] = int((float(vote['nb_votes']) / float(vote['max_votes'])) * 100)
return render_template('votes.html', votes=votes, active_button=active_button)
#------
users[t['userid']]['choices'] = [t['choiceid']]
choices = query_db('select choices.name, choices.id, choices.name, choices.id_vote, count(id_choice) as nb from choices left join user_choice on id_choice = choices.id where id_vote = ? group by id_choice, name, id_vote order by id', [idvote])
attachments = query_db('select * from attachments where id_vote=?', [idvote])
+ tmp = query_db('select id_group, count(*) as nb from user_group where id_group = ? group by id_group', [vote['id_group']], one=True)
+ if tmp is None:
+ vote['percent'] = 0
+ else:
+ vote['max_votes'] = tmp['nb']
+ tmp = query_db('select id_vote, count(*) as nb from (select id_user, id_vote from user_choice join choices on id_choice = choices.id group by id_user, id_vote) where id_vote = ? group by id_vote', [idvote], one=True)
+ if tmp is None:
+ vote['percent'] = 0
+ else:
+ vote['nb_votes'] = tmp['nb']
+ vote['percent'] = int((float(vote['nb_votes']) / float(vote['max_votes'])) * 100)
return render_template('vote.html', vote=vote, attachments=attachments, choices=choices, users=users.values(), can_vote=can_vote(idvote, get_userid()))
flash('Vous n\'avez pas le droit de voir ce vote, désolé.')
return(url_for('home'))
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
+ 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