Use db_query() function to get entries from db
[cavote.git] / main.py
diff --git a/main.py b/main.py
index ea1179e..f749cc4 100755 (executable)
--- a/main.py
+++ b/main.py
@@ -5,6 +5,7 @@ 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, '')
 
@@ -32,35 +33,52 @@ def teardown_request(exception):
 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 username == app.config['USERNAME'] and password == app.config['PASSWORD']
+
 @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'
-        else:
-            session['logged_in'] = True
-            session['nickname'] = request.form['username']
-            if session['nickname'] == 'admin':
+        if valid_login(request.form['username'], request.form['password']):
+            session['username'] = request.form['username']
+            if session['username'] == 'admin':
                 session['is_admin'] = True
             flash('You were logged in')
             return redirect(url_for('home'))
+        else:
+            error = "Invalid username/password"
     return render_template('login.html', error=error)
 
 @app.route('/logout')
 def logout():
-    session.pop('logged_in', None)
+    session.pop('username', None)
+    session.pop('is_admin', None)
     flash('You were logged out')
     return redirect(url_for('home'))
 
 #---------------
 # User settings
+@app.route('/user/settings/<username>')
+def show_settings(username):
+    if username != session['username']:
+        abort(401)
+
 
 #------------
 # User admin
@@ -71,17 +89,15 @@ def logout():
 
 @app.route('/votes/<votes>')
 def show_votes(votes):
-    today = date.today().strftime('%d %B %Y')
+    today = date.today()
     if votes == 'all':
-        cur = g.db.execute('select title, description, date_begin, date_end from votes order by id desc')
-    elif votes == 'archives':
-        cur = g.db.execute('select title, description, date_begin, date_end from votes where date_end < :today order by id desc', {"today" : today})
-    elif votes == 'currently':
-        cur = g.db.execute('select title, description, date_begin, date_end from votes where date_end > :today order by id desc', {"today" : today})
+        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)
-    votes = [dict(title=row[0], description=row[1], date_begin=row[2], date_end=row[3], 
-        pourcent=60) for row in cur.fetchall()]
     return render_template('show_votes.html', votes=votes)
 
 #-------------
@@ -89,16 +105,16 @@ def show_votes(votes):
 
 @app.route('/votes/admin/new')
 def new_vote():
-    if not session.get('logged_in'):
+    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('logged_in'):
+    if not session.get('is_admin'):
         abort(401)
-    daten = date.today() + timedelta(days=int(request.form['days']))
-    ndate = daten.strftime('%d %B %Y')
+    date_begin = date.today()
+    date_end = date.today() + timedelta(days=int(request.form['days']))
     transparent = 0
     public = 0
     multiplechoice = 0
@@ -108,8 +124,8 @@ def add_vote():
         public = 1
     if 'multiplechoice' in request.form.keys():
         multiplechoice = 1
-    g.db.execute('insert into votes (title, description, date_end, is_transparent, is_public, is_multiplechoice) values (?, ?, ?, ?, ?, ?)',
-            [request.form['title'], request.form['description'], ndate, transparent, public, multiplechoice])
+    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')
     return redirect(url_for('home'))