123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376 |
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- 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, '')
- DATABASE = '/tmp/cavote.db'
- SECRET_KEY = '{J@uRKO,xO-PK7B,jF?>iHbxLasF9s#zjOoy=+:'
- DEBUG = True
- app = Flask(__name__)
- app.config.from_object(__name__)
- def connect_db():
- return sqlite3.connect(app.config['DATABASE'])
- @app.before_request
- def before_request():
- g.db = connect_db()
- @app.teardown_request
- def teardown_request(exception):
- g.db.close()
- @app.route('/')
- def 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, 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']['id'] = user['id']
- #session['user']['name'] = user['name']
- #session['user']['email'] = user['email']
- #session['user']['organization'] = user['organization']
- #if user['is_admin'] == 1:
- # session['user']['is_admin'] = True
- def disconnect_user():
- session.pop('user', None)
- @app.route('/login', methods=['GET', 'POST'])
- def login():
- if request.method == 'POST':
- user = valid_login(request.form['username'], request.form['password'])
- if user is None:
- flash('Invalid username/password', 'error')
- else:
- connect_user(user)
- flash('You were logged in', 'success')
- return redirect(url_for('home'))
- return render_template('login.html')
- @app.route('/logout')
- def logout():
- 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: Générer la clé, 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 show_user(userid):
- if int(userid) != session.get('user').get('id'):
- abort(401)
- return render_template('show_user.html')
- @app.route('/user/settings/<userid>', methods=['GET', 'POST'])
- def user_settings(userid):
- if int(userid) != session.get('user').get('id'):
- abort(401)
- if request.method == 'POST':
- 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
- flash(u'Votre profil a été mis à jour !', 'success')
- return redirect(url_for('login'))
- return render_template('user_settings.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']:
- # :TODO:maethor:120528: Chiffrer le mot de passe !
- g.db.execute('update users set password = ? where id = ?', [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_settings.html')
- #------------
- # User admin
- @app.route('/users/admin/list')
- def admin_users():
- if not session.get('user').get('is_admin'):
- abort(401)
- users = query_db('select * from users order by id desc')
- return render_template('admin_users.html', users=users)
- @app.route('/users/admin/add', methods=['GET', 'POST'])
- def add_user():
- 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()
- # :TODO:maethor:120528: Send mail
- flash(u'Le nouvel utilisateur a été créé avec succès', 'success')
- return redirect(url_for('home'))
- else:
- flash(u"Vous devez spécifier une adresse email.", 'error')
- return render_template('add_user.html')
- #-------------
- # Roles admin
- @app.route('/roles')
- def show_roles():
- if not session.get('user').get('is_admin'):
- abort(401)
- roles = query_db('select * from roles')
- return render_template('show_roles.html', roles=roles)
- @app.route('/roles/admin/add', methods=['POST'])
- def add_role():
- 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('show_roles'))
- @app.route('/roles/admin/delete/<idrole>')
- def del_role(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('show_roles'))
- #------------
- # Votes list
- @app.route('/votes/<votes>')
- def show_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 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('show_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:20120529: Check others things
- def can_vote(idvote, iduser=-1):
- if not can_see_vote(idvote, iduser):
- return False
- return True # :TODO:maethor:20120529: Check others things
- @app.route('/vote/<idvote>')
- def show_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('/votes/admin/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('/votes/admin/add', methods=['GET', 'POST'])
- def add_vote():
- 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:20120528: 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('edit_vote', voteid=vote['id']))
- else:
- flash(u'Vous devez spécifier un titre.', 'error')
- groups = query_db('select * from roles')
- return render_template('new_vote.html', groups=groups)
- @app.route('/votes/admin/edit/<voteid>', methods=['GET', 'POST'])
- def edit_vote(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:20120529: 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:20120529: 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])
- return render_template('edit_vote.html', vote=vote, group=group, choices=choices)
- @app.route('/votes/admin/addchoice/<voteid>', methods=['POST'])
- def add_choice(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('edit_vote', voteid=voteid))
- @app.route('/votes/admin/editchoice/<voteid>/<choiceid>', methods=['POST', 'DELETE'])
- def edit_choice(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:20120528: 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('edit_vote', voteid=voteid))
- @app.route('/votes/admin/deletechoice/<voteid>/<choiceid>')
- def delete_choice(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('edit_vote', voteid=voteid))
- #------
- # Main
- if __name__ == '__main__':
- app.run()
|