from flask import Flask
from flask import render_template, redirect
from flask import request
+from functools import wraps
import postgresql
import filters
from flaskext.markdown import Markdown
from markdown.extensions import Extension
+from datetime import date, time, datetime
def get_db():
db = getattr(g, '_database', None)
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')
times = ConfigProxy("DURATION")
debuguser = ConfigProxy("DEBUGUSER")
+max_proxy=app.config.get("MAX_PROXY")
+
@app.before_request
def lookup_user():
global prefix
user = env.get("USER")
roles = env.get("ROLES")
-
if user is None:
return "Server misconfigured", 500
roles = roles.split(" ")
db.prepare("INSERT INTO voter(\"email\") VALUES($1)")(user)
rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
g.voter = rv[0].get("id");
+ rv = db.prepare("SELECT email FROM voter, proxy WHERE proxy.proxy_id = voter.id AND proxy.revoked IS NULL AND proxy.voter_id = $1 ")(g.voter)
+ if len(rv) != 0:
+ g.proxies_given = rv[0].get("email")
+ rv = db.prepare("SELECT email FROM voter, proxy WHERE proxy.voter_id = voter.id AND proxy.revoked IS NULL AND proxy.proxy_id = $1 ")(g.voter)
+ if len(rv) != 0:
+ sep = ""
+ g.proxies_received = ""
+ for x in range(0, len(rv)):
+ g.proxies_received += sep + rv[x].get("email")
+ sep =", "
+
g.user = user
g.roles = {}
g.roles[a[0]] = [group for group in prefix.per_host]
else:
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, []);
def may(action, motion):
return motion in get_allowed_cats(action)
+def may_admin(action):
+ return action in g.roles
+
+def get_voters():
+ rv = get_db().prepare("SELECT email FROM voter")
+ return rv
+
+def get_all_proxies():
+ rv = get_db().prepare("SELECT p.id as id, v1.email as voter_email, v1.id as voterid, v2.email as proxy_email, v2.id as proxyid FROM voter AS v1, voter AS v2, proxy AS p WHERE v2.id = p.proxy_id AND v1.id = p.voter_id AND p.revoked is NULL ORDER BY voter_email, proxy_email")
+ return rv
+
@app.teardown_appcontext
def close_connection(exception):
db = getattr(g, '_database', None)
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:
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"):
db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"host\" SET NOT NULL")()
db.prepare("UPDATE \"schema_version\" SET \"version\"=3")()
+ if ver < 4:
+ with app.open_resource('sql/from_3.sql', mode='r') as f:
+ db.execute(f.read())
+ db.prepare("UPDATE \"schema_version\" SET \"version\"=4")()
init_db()
+
@app.route("/")
def main():
start=int(request.args.get("start", "-1"));
else:
prev = -1
return render_template('index.html', motions=rv[:10], more=rv[10]["id"] if len(rv) == 11 else None, times=times.per_host, prev=prev,
- categories=get_allowed_cats("create"))
+ categories=get_allowed_cats("create"), singlemotion=False, may_proxyadmin=may_admin("proxyadmin"))
def rel_redirect(loc):
r = redirect(loc)
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];
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_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):
- rv = get_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
- id = rv[0].get("id")
- if not may("cancel", rv[0].get("type")):
- return "Forbidden", 403
+@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'])
+@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)
+
@app.route("/motion/<string:motion>")
def show_motion(motion):
p = get_db().prepare("SELECT motion.*, poser.email AS poser, canceler.email AS canceler, (motion.deadline > CURRENT_TIMESTAMP AND canceled is NULL) AS running, vote.result FROM motion "\
votes = None
if may("audit", rv[0].get("type")) and not rv[0].get("running") and not rv[0].get("canceled"):
votes = get_db().prepare("SELECT vote.result, voter.email FROM vote INNER JOIN voter ON voter.id = vote.voter_id WHERE vote.motion_id=$1")(rv[0].get("id"));
- 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")), votes=votes)
+ 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, may_proxyadmin=may_admin("proxyadmin"))
@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)
+
+@app.route("/proxy")
+def proxy():
+ if not may_admin("proxyadmin"):
+ return "Forbidden", 403
+ return render_template('proxy.html', voters=get_voters(), proxies=get_all_proxies(), may_proxyadmin=may_admin("proxyadmin"))
+
+@app.route("/proxy/add", methods=['POST'])
+def add_proxy():
+ if not may_admin("proxyadmin"):
+ return "Forbidden", 403
+ voter=request.form.get("voter", "")
+ proxy=request.form.get("proxy", "")
+ if voter == proxy :
+ return "Error, voter equals proxy.", 400
+ rv = get_db().prepare("SELECT id FROM voter WHERE email=$1")(voter);
+ if len(rv) == 0:
+ return "Error, voter not found.", 400
+ voterid = rv[0].get("id")
+ rv = get_db().prepare("SELECT id FROM voter WHERE email=$1")(proxy);
+ if len(rv) == 0:
+ return "Error, proxy not found.", 400
+ proxyid = rv[0].get("id")
+ rv = get_db().prepare("SELECT id FROM proxy WHERE voter_id=$1 AND revoked is NULL")(voterid);
+ if len(rv) != 0:
+ return "Error, proxy allready given.", 400
+ rv = get_db().prepare("SELECT COUNT(id) as c FROM proxy WHERE proxy_id=$1 AND revoked is NULL GROUP BY proxy_id")(proxyid);
+ if len(rv) != 0:
+ if rv[0].get("c") >= max_proxy:
+ return "Error, Max proxy for '" + proxy + "' reached.", 400
+ rv = get_db().prepare("INSERT INTO proxy(voter_id, proxy_id, granted_by) VALUES ($1,$2,$3)")(voterid, proxyid, g.voter)
+ return rel_redirect("/proxy")
+
+@app.route("/proxy/revoke", methods=['POST'])
+def revoke_proxy():
+ if not may_admin("proxyadmin"):
+ return "Forbidden", 403
+ id=request.form.get("id", "")
+ rv = get_db().prepare("UPDATE proxy SET revoked=CURRENT_TIMESTAMP, revoked_by=$1 WHERE id=$2")(g.voter, int(id))
+ return rel_redirect("/proxy")
+
+@app.route("/proxy/revokeall", methods=['POST'])
+def revoke_proxy_all():
+ if not may_admin("proxyadmin"):
+ return "Forbidden", 403
+ rv = get_db().prepare("UPDATE proxy SET revoked=CURRENT_TIMESTAMP, revoked_by=$1 WHERE revoked IS NULL")(g.voter)
+ return rel_redirect("/proxy")
+