]> WPIA git - motion.git/blobdiff - motion.py
Merge branch 'footer' into 'master'
[motion.git] / motion.py
index 1c83fc997a0460005b1947d9cb91e4b2831ba816..80ac5a36029eb728e0bf7031fb0404caf0397c8e 100644 (file)
--- a/motion.py
+++ b/motion.py
@@ -26,7 +26,16 @@ class EscapeHtml(Extension):
 
 md = Markdown(app, extensions=[EscapeHtml()])
 
+class default_settings(object):
+    COPYRIGHTSTART="2017"
+    COPYRIGHTNAME="WPIA"
+    COPYRIGHTLINK="https://wpia.club"
+    IMPRINTLINK="https://documents.wpia.club/imprint.html"
+    DATAPROTECTIONLINK="https://documents.wpia.club/data_privacy_policy_html_pages_en.html"
+
+
 # Load config
+app.config.from_object('motion.default_settings')
 app.config.from_pyfile('config.py')
 
 
@@ -94,6 +103,23 @@ def lookup_user():
                 g.roles[a[0]].append(val)
     return None
 
+@app.context_processor
+def init_footer_variables():
+    if int(app.config.get("COPYRIGHTSTART"))<datetime.now().year:
+        version_year = "%s - %s" % (app.config.get("COPYRIGHTSTART"), datetime.now().year)
+    else:
+        version_year = datetime.now().year
+
+    return dict(
+        footer = dict( version_year=version_year, 
+            copyright_link=app.config.get("COPYRIGHTLINK"),
+            copyright_name=app.config.get("COPYRIGHTNAME"),
+            imprint_link=app.config.get("DATAPROTECTIONLINK"),
+            dataprotection_link=app.config.get("DATAPROTECTIONLINK")
+        )
+    )
+
+
 def get_allowed_cats(action):
     return g.roles.get(action, []);
 
@@ -113,6 +139,8 @@ def init_db():
             ver = db.prepare("SELECT version FROM schema_version")()[0][0];
             print("Database Schema version: ", ver)
         except postgresql.exceptions.UndefinedTableError:
+            g._database = None
+            db = get_db()
             ver = 0
 
         if ver < 1:
@@ -124,8 +152,8 @@ def init_db():
             with app.open_resource('sql/from_1.sql', mode='r') as f:
                 db.execute(f.read())
                 ct={}
-                for g in [group for group in prefix[app.config.get("DEFAULT_HOST")]]:
-                    ct[g] = {"dt": "", "c": 0}
+                for group in [group for group in prefix[app.config.get("DEFAULT_HOST")]]:
+                    ct[group] = {"dt": "", "c": 0}
 
                 p = db.prepare("UPDATE \"motion\" SET \"identifier\"=$1 WHERE \"id\"=$2")
                 for row in db.prepare("SELECT id, \"type\", \"posed\" FROM \"motion\" ORDER BY \"id\" ASC"):
@@ -147,7 +175,6 @@ def init_db():
                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"host\" SET NOT NULL")()
                 db.prepare("UPDATE \"schema_version\" SET \"version\"=3")()
 
-
 init_db()
 
 @app.route("/")
@@ -187,7 +214,16 @@ def put_motion():
         return "Forbidden", 403
     time = int(request.form.get("days", "3"));
     if time not in times.per_host:
-        return "Error, invalid length", 500
+        return "Error, invalid length", 400
+    title=request.form.get("title", "")
+    title=title.strip()
+    if title =='':
+        return "Error, missing title", 400
+    content=request.form.get("content", "")
+    content=content.strip()
+    if content =='':
+        return "Error, missing content", 400
+
     db = get_db()
     with db.xact():
         t = db.prepare("SELECT CURRENT_TIMESTAMP")()[0][0];
@@ -199,40 +235,43 @@ def put_motion():
         else:
             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+"."+("%03d" % (int(sr[0][0].split(".")[2])+1))
         p = db.prepare("INSERT INTO motion(\"name\", \"content\", \"deadline\", \"posed_by\", \"type\", \"identifier\", \"host\") VALUES($1, $2, CURRENT_TIMESTAMP + $3 * interval '1 days', $4, $5, $6, $7)")
-        p(request.form.get("title", ""), request.form.get("content",""), time, g.voter, cat, ident, request.host)
+        p(title, content, time, g.voter, cat, ident, request.host)
     return rel_redirect("/")
 
 def motion_edited(motion):
     return rel_redirect("/?start=" + str(motion) + "#motion-" + str(motion))
-    
-
-def validate_access(data):
-    rv = get_db().prepare("SELECT id, type, deadline, canceled FROM motion WHERE identifier=$1 AND host=$2")(data[0], data[1]);
-    if len(rv) == 0:
-        return "Error, Not found", 404
-    id = rv[0].get("id")
-    if not may(data[2], rv[0].get("type")):
-        return "Forbidden", 403
-    if rv[0].get("deadline") < datetime.now() or rv[0].get("canceled") is not None:
-        return "Error, out of time", 403
-    return id
 
+def validate_motion_access(privilege):
+    def decorator(f):
+        def decorated_function(motion):
+            db = get_db()
+            with db.xact():
+                rv = db.prepare("SELECT id, type, deadline < CURRENT_TIMESTAMP AS expired, canceled FROM motion WHERE identifier=$1 AND host=$2")(motion, request.host);
+                if len(rv) == 0:
+                    return "Error, Not found", 404
+                id = rv[0].get("id")
+                if not may(privilege, rv[0].get("type")):
+                    return "Forbidden", 403
+                if rv[0].get("canceled") is not None:
+                    return "Error, motion was canceled", 403
+                if rv[0].get("expired"):
+                    return "Error, out of time", 403
+            return f(motion, id)
+        decorated_function.__name__ = f.__name__
+        return decorated_function
+    return decorator
     
 @app.route("/motion/<string:motion>/cancel", methods=['POST'])
-def cancel_motion(motion):
-    id = validate_access([motion, request.host, 'cancel'])
-    if not isinstance(id, int):
-        return id[0], id[1]
+@validate_motion_access('cancel')
+def cancel_motion(motion, id):
     if request.form.get("reason", "none") == "none":
         return "Error, form requires reason", 500
     rv = get_db().prepare("UPDATE motion SET canceled=CURRENT_TIMESTAMP, cancelation_reason=$1, canceled_by=$2 WHERE identifier=$3 AND host=$4 AND canceled is NULL")(request.form.get("reason", ""), g.voter, motion, request.host)
     return motion_edited(id)
 
 @app.route("/motion/<string:motion>/finish", methods=['POST'])
-def finish_motion(motion):
-    id = validate_access([motion, request.host, 'finish'])
-    if not isinstance(id, int):
-        return id[0], id[1]
+@validate_motion_access('finish')
+def finish_motion(motion, id):
     rv = get_db().prepare("UPDATE motion SET deadline=CURRENT_TIMESTAMP WHERE identifier=$1 AND host=$2 AND canceled is NULL")(motion, request.host)
     return motion_edited(id)
 
@@ -252,23 +291,14 @@ def show_motion(motion):
     return render_template('single_motion.html', motion=rv[0], may_vote=may("vote", rv[0].get("type")), may_cancel=may("cancel", rv[0].get("type")), may_finish=may("finish", rv[0].get("type")), votes=votes, singlemotion=True)
 
 @app.route("/motion/<string:motion>/vote", methods=['POST'])
-def vote(motion):
+@validate_motion_access('vote')
+def vote(motion, id):
     v = request.form.get("vote", "abstain")
     db = get_db()
-    with db.xact():
-        rv = db.prepare("SELECT id, type FROM motion WHERE identifier=$1 AND host=$2")(motion, request.host);
-        if len(rv) == 0:
-            return "Error, Not found", 404
-        if not may("vote", rv[0].get("type")):
-            return "Forbidden", 403
-        p = db.prepare("SELECT deadline > CURRENT_TIMESTAMP FROM motion WHERE identifier = $1 AND host=$2")
-        id = rv[0].get("id")
-        if not p(motion, request.host)[0][0]:
-            return "Error, motion deadline has passed", 500
-        p = db.prepare("SELECT * FROM vote WHERE motion_id = $1 AND voter_id = $2")
-        rv = p(id, g.voter)
-        if len(rv) == 0:
-            db.prepare("INSERT INTO vote(motion_id, voter_id, result) VALUES($1,$2,$3)")(id, g.voter, v)
-        else:
-            db.prepare("UPDATE vote SET result=$3, entered=CURRENT_TIMESTAMP WHERE motion_id=$1 AND voter_id = $2")(id, g.voter, v)
+    p = db.prepare("SELECT * FROM vote WHERE motion_id = $1 AND voter_id = $2")
+    rv = p(id, g.voter)
+    if len(rv) == 0:
+        db.prepare("INSERT INTO vote(motion_id, voter_id, result) VALUES($1,$2,$3)")(id, g.voter, v)
+    else:
+        db.prepare("UPDATE vote SET result=$3, entered=CURRENT_TIMESTAMP WHERE motion_id=$1 AND voter_id = $2")(id, g.voter, v)
     return motion_edited(id)