123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171 |
- #!/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')
- 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['userid'] = user['id']
- session['username'] = user['name']
- session['email'] = user['email']
- session['organization'] = user['organization']
- if user['is_admin'] == 1:
- session['is_admin'] = True
- def disconnect_user():
- session.pop('username', None)
- session.pop('is_admin', 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/<username>/<key>')
- def login_key(username, key):
- user = query_db('select * from users where email = ? and key = ?', [username, key], one=True)
- if user is None:
- abort(404)
- else:
- connect_user(user)
- # :TODO:maethor:120528: Remplacer la clé pour qu'elle ne puisse plus être utilisée
- return redirect(url_for('home'))
- #---------------
- # User settings
- @app.route('/user/settings/<username>')
- def show_user(username):
- if username != session.get('username'):
- abort(401)
- return render_template('user_settings.html')
- #------------
- # User admin
- #------------
- # Votes list
- @app.route('/votes/<votes>')
- def show_votes(votes):
- today = date.today()
- if votes == 'all':
- votes = query_db('select title, description, date_begin, date_end from votes order by id desc')
- elif votes == 'archive':
- votes = query_db('select title, description, date_begin, date_end from votes where date_end < (?) order by id desc', [today])
- elif votes == 'current':
- votes = query_db('select title, description, date_begin, date_end from votes where date_end >= (?) order by id desc', [today])
- else:
- abort(404)
- return render_template('show_votes.html', votes=votes)
- #-------------
- # Votes admin
- @app.route('/votes/admin/new')
- def new_vote():
- if not session.get('is_admin'):
- abort(401)
- return render_template('new_vote.html')
- @app.route('/votes/admin/add', methods=['POST'])
- def add_vote():
- if not session.get('is_admin'):
- abort(401)
- 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
- g.db.execute('insert into votes (title, description, date_begin, date_end, is_transparent, is_public, is_multiplechoice) values (?, ?, ?, ?, ?, ?, ?)',
- [request.form['title'], request.form['description'], date_begin, date_end, transparent, public, multiplechoice])
- g.db.commit()
- flash('New entry was successfully posted', 'info')
- return redirect(url_for('home'))
- #------
- # Main
- if __name__ == '__main__':
- app.run()
|