]> WPIA git - motion.git/blob - motion.py
Merge branch 'proxy-vote' into 'master'
[motion.git] / motion.py
1 from flask import g
2 from flask import Flask
3 from flask import render_template, redirect
4 from flask import request
5 from functools import wraps
6 import postgresql
7 import filters
8 from flaskext.markdown import Markdown
9 from markdown.extensions import Extension
10 from datetime import date, time, datetime
11
12 def get_db():
13     db = getattr(g, '_database', None)
14     if db is None:
15         db = g._database = postgresql.open(app.config.get("DATABASE"), user=app.config.get("USER"), password=app.config.get("PASSWORD"))
16     #db.row_factory = sqlite3.Row
17     return db
18
19 app = Flask(__name__)
20 app.register_blueprint(filters.blueprint)
21
22 class EscapeHtml(Extension):
23     def extendMarkdown(self, md, md_globals):
24         del md.preprocessors['html_block']
25         del md.inlinePatterns['html']
26
27 md = Markdown(app, extensions=[EscapeHtml()])
28
29 class default_settings(object):
30     COPYRIGHTSTART="2017"
31     COPYRIGHTNAME="WPIA"
32     COPYRIGHTLINK="https://wpia.club"
33     IMPRINTLINK="https://documents.wpia.club/imprint.html"
34     DATAPROTECTIONLINK="https://documents.wpia.club/data_privacy_policy_html_pages_en.html"
35
36
37 # Load config
38 app.config.from_object('motion.default_settings')
39 app.config.from_pyfile('config.py')
40
41
42 class ConfigProxy:
43     def __init__(self, name):
44         self.name = name
45     @property
46     def per_host(self):
47         dict = app.config.get(self.name)
48         if dict is None:
49             return None
50         return dict.get(request.host)
51
52 prefix = ConfigProxy("GROUP_PREFIX")
53 times = ConfigProxy("DURATION")
54 debuguser = ConfigProxy("DEBUGUSER")
55
56 max_proxy=app.config.get("MAX_PROXY")
57
58 @app.before_request
59 def lookup_user():
60     global prefix
61
62     env = request.environ
63     user = None
64     my_debuguser = debuguser.per_host
65     if my_debuguser is not None:
66         parts = my_debuguser.split("/", 1)
67         user = parts[0]
68         roles = parts[1]
69
70     if "USER_ROLES" in env:
71         parts = env.get("USER_ROLES").split("/", 1)
72         user = parts[0]
73         roles = parts[1]
74
75     if "USER" in env and "ROLES" in env:
76         user = env.get("USER")
77         roles = env.get("ROLES")
78
79     if user is None:
80         return "Server misconfigured", 500
81     roles = roles.split(" ")
82
83     if user == "<invalid>":
84         return "Access denied", 403;
85
86     db = get_db()
87     with db.xact():
88         rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
89         if len(rv) == 0:
90             db.prepare("INSERT INTO voter(\"email\") VALUES($1)")(user)
91             rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
92         g.voter = rv[0].get("id");
93         g.proxies_given = ""
94         rv = db.prepare("SELECT email, voter_id FROM voter, proxy WHERE proxy.proxy_id = voter.id AND proxy.revoked IS NULL AND proxy.voter_id = $1 ")(g.voter)
95         if len(rv) != 0:
96             g.proxies_given = rv[0].get("email")
97         rv = db.prepare("SELECT email, voter_id FROM voter, proxy WHERE proxy.voter_id = voter.id AND proxy.revoked IS NULL AND proxy.proxy_id = $1 ")(g.voter)
98         if len(rv) != 0:
99             sep = ""
100             g.proxies_received = ""
101             for x in range(0, len(rv)):
102                 g.proxies_received += sep + rv[x].get("email")
103                 sep =", "
104
105     g.user = user
106     g.roles = {}
107
108     for r in roles:
109         a = r.split(":", 1)
110         if len(r)!=0:
111             val = a[1]
112             if a[0] not in g.roles:
113                 g.roles[a[0]] = []
114             if val == "*":
115                 g.roles[a[0]] = [group for group in prefix.per_host]
116             else:
117                 g.roles[a[0]].append(val)
118
119     return None
120
121 @app.context_processor
122 def init_footer_variables():
123     if int(app.config.get("COPYRIGHTSTART"))<datetime.now().year:
124         version_year = "%s - %s" % (app.config.get("COPYRIGHTSTART"), datetime.now().year)
125     else:
126         version_year = datetime.now().year
127
128     return dict(
129         footer = dict( version_year=version_year, 
130             copyright_link=app.config.get("COPYRIGHTLINK"),
131             copyright_name=app.config.get("COPYRIGHTNAME"),
132             imprint_link=app.config.get("DATAPROTECTIONLINK"),
133             dataprotection_link=app.config.get("DATAPROTECTIONLINK")
134         )
135     )
136
137
138 def get_allowed_cats(action):
139     return g.roles.get(action, []);
140
141 def may(action, motion):
142     return motion in get_allowed_cats(action)
143
144 def may_admin(action):
145     return action in g.roles
146
147 def get_voters():
148     rv = get_db().prepare("SELECT email FROM voter")
149     return rv
150
151 def get_all_proxies():
152     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")
153     return rv
154
155 @app.teardown_appcontext
156 def close_connection(exception):
157     db = getattr(g, '_database', None)
158     if db is not None:
159         db.close()
160
161 def init_db():
162     with app.app_context():
163         db = get_db()
164         try:
165             ver = db.prepare("SELECT version FROM schema_version")()[0][0];
166             print("Database Schema version: ", ver)
167         except postgresql.exceptions.UndefinedTableError:
168             g._database = None
169             db = get_db()
170             ver = 0
171
172         if ver < 1:
173             with app.open_resource('sql/schema.sql', mode='r') as f:
174                 db.execute(f.read())
175             return
176
177         if ver < 2:
178             with app.open_resource('sql/from_1.sql', mode='r') as f:
179                 db.execute(f.read())
180                 ct={}
181                 for group in [group for group in prefix[app.config.get("DEFAULT_HOST")]]:
182                     ct[group] = {"dt": "", "c": 0}
183
184                 p = db.prepare("UPDATE \"motion\" SET \"identifier\"=$1 WHERE \"id\"=$2")
185                 for row in db.prepare("SELECT id, \"type\", \"posed\" FROM \"motion\" ORDER BY \"id\" ASC"):
186                     dt=row[2].strftime("%Y%m%d")
187                     if ct[row[1]]["dt"] != dt:
188                         ct[row[1]]["dt"] = dt
189                         ct[row[1]]["c"] = 0
190                     ct[row[1]]["c"] = ct[row[1]]["c"] + 1
191                     name=prefix[app.config.get("DEFAULT_HOST")][row[1]]+"."+dt+"."+("%03d" % ct[row[1]]["c"])
192                     p(name, row[0])
193                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"identifier\" SET NOT NULL")()
194                 db.prepare("UPDATE \"schema_version\" SET \"version\"=2")()
195                 db.prepare("CREATE UNIQUE INDEX motion_ident ON motion (identifier)")()
196
197         if ver < 3:
198             with app.open_resource('sql/from_2.sql', mode='r') as f:
199                 db.execute(f.read())
200                 db.prepare("UPDATE \"motion\" SET \"host\"=$1")(app.config.get("DEFAULT_HOST"))
201                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"host\" SET NOT NULL")()
202                 db.prepare("UPDATE \"schema_version\" SET \"version\"=3")()
203
204         if ver < 4:
205             with app.open_resource('sql/from_3.sql', mode='r') as f:
206                 db.execute(f.read())
207                 db.prepare("UPDATE \"schema_version\" SET \"version\"=4")()
208
209         if ver < 5:
210             with app.open_resource('sql/from_4.sql', mode='r') as f:
211                 db.execute(f.read())
212                 db.prepare("UPDATE \"schema_version\" SET \"version\"=5")()
213
214 init_db()
215
216
217 @app.route("/")
218 def main():
219     start=int(request.args.get("start", "-1"));
220     q = "SELECT motion.*, votes.*, poser.email AS poser, canceler.email AS canceler, (motion.deadline > CURRENT_TIMESTAMP AND canceled is NULL) AS running FROM motion LEFT JOIN (SELECT motion_id, "\
221                              + "COUNT(CASE WHEN result='yes' THEN 'yes' ELSE NULL END) as yes, "\
222                              + "COUNT(CASE WHEN result='no' THEN 'no' ELSE NULL END) as no, "\
223                              + "COUNT(CASE WHEN result='abstain' THEN 'abstain' ELSE NULL END) as abstain "\
224                              + "FROM vote GROUP BY motion_id) as votes ON votes.motion_id=motion.id "\
225                              + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
226                              + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
227     prev=None
228     if start == -1:
229         p = get_db().prepare(q + "WHERE motion.host = $1 ORDER BY motion.id DESC LIMIT 11")
230         rv = p(request.host)
231     else:
232         p = get_db().prepare(q + "WHERE motion.host = $1 AND motion.id <= $2 ORDER BY motion.id DESC LIMIT 11")
233         rv = p(request.host, start)
234         rs = get_db().prepare("SELECT id FROM motion WHERE motion.host = $1 AND motion.id > $2 ORDER BY id ASC LIMIT 10")(request.host, start)
235         if len(rs) == 10:
236             prev = rs[9][0]
237         else:
238             prev = -1
239     return render_template('index.html', motions=rv[:10], more=rv[10]["id"] if len(rv) == 11 else None, times=times.per_host, prev=prev,
240                            categories=get_allowed_cats("create"), singlemotion=False, may_proxyadmin=may_admin("proxyadmin"))
241
242 def rel_redirect(loc):
243     r = redirect(loc)
244     r.autocorrect_location_header = False
245     return r
246
247 @app.route("/motion", methods=['POST'])
248 def put_motion():
249     cat=request.form.get("category", "")
250     if cat not in get_allowed_cats("create"):
251         return "Forbidden", 403
252     time = int(request.form.get("days", "3"));
253     if time not in times.per_host:
254         return "Error, invalid length", 400
255     title=request.form.get("title", "")
256     title=title.strip()
257     if title =='':
258         return "Error, missing title", 400
259     content=request.form.get("content", "")
260     content=content.strip()
261     if content =='':
262         return "Error, missing content", 400
263
264     db = get_db()
265     with db.xact():
266         t = db.prepare("SELECT CURRENT_TIMESTAMP")()[0][0];
267         s = db.prepare("SELECT MAX(\"identifier\") FROM \"motion\" WHERE \"type\"=$1 AND \"host\"=$2 AND DATE(\"posed\")=DATE(CURRENT_TIMESTAMP)")
268         sr = s(cat, request.host)
269         ident=""
270         if len(sr) == 0 or sr[0][0] is None:
271             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+".001"
272         else:
273             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+"."+("%03d" % (int(sr[0][0].split(".")[2])+1))
274         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)")
275         p(title, content, time, g.voter, cat, ident, request.host)
276     return rel_redirect("/")
277
278 def motion_edited(motion):
279     return rel_redirect("/motion/" + motion)
280
281 def validate_motion_access(privilege):
282     def decorator(f):
283         def decorated_function(motion):
284             db = get_db()
285             with db.xact():
286                 rv = db.prepare("SELECT id, type, deadline < CURRENT_TIMESTAMP AS expired, canceled FROM motion WHERE identifier=$1 AND host=$2")(motion, request.host);
287                 if len(rv) == 0:
288                     return "Error, Not found", 404
289                 id = rv[0].get("id")
290                 if not may(privilege, rv[0].get("type")):
291                     return "Forbidden", 403
292                 if rv[0].get("canceled") is not None:
293                     return "Error, motion was canceled", 403
294                 if rv[0].get("expired"):
295                     return "Error, out of time", 403
296             return f(motion, id)
297         decorated_function.__name__ = f.__name__
298         return decorated_function
299     return decorator
300     
301 def validate_motion_access_vote(privilege):
302     simple_decorator = validate_motion_access(privilege)
303     def decorator(f):
304         def decorated_function(motion, voter):
305             return simple_decorator(lambda motion, id : f(motion, voter, id))(motion)
306         decorated_function.__name__ = f.__name__
307         return decorated_function
308     return decorator
309
310 @app.route("/motion/<string:motion>/cancel", methods=['POST'])
311 @validate_motion_access('cancel')
312 def cancel_motion(motion, id):
313     if request.form.get("reason", "none") == "none":
314         return "Error, form requires reason", 500
315     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)
316     return motion_edited(motion)
317
318 @app.route("/motion/<string:motion>/finish", methods=['POST'])
319 @validate_motion_access('finish')
320 def finish_motion(motion, id):
321     rv = get_db().prepare("UPDATE motion SET deadline=CURRENT_TIMESTAMP WHERE identifier=$1 AND host=$2 AND canceled is NULL")(motion, request.host)
322     return motion_edited(motion)
323
324 @app.route("/motion/<string:motion>")
325 def show_motion(motion):
326     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 "\
327                          + "LEFT JOIN vote on vote.motion_id=motion.id AND vote.voter_id=$2 "\
328                          + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
329                          + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
330                          + "WHERE motion.identifier=$1 AND motion.host=$3")
331     resultmotion = p(motion, g.voter, request.host)
332     if len(resultmotion) == 0:
333         return "Error, Not found", 404
334
335     p = get_db().prepare("SELECT voter.email FROM vote INNER JOIN voter ON vote.proxy_id = voter.id WHERE vote.motion_id=$1 AND vote.voter_id=$2 AND vote.proxy_id <> vote.voter_id")
336     resultproxyname = p(resultmotion[0][0], g.voter)
337
338     p = get_db().prepare("SELECT v.result, proxy.voter_id, voter.email, CASE WHEN proxy.proxy_id = v.proxy_id THEN NULL ELSE voter.email END AS owneremail FROM proxy LEFT JOIN "\
339                           + "(SELECT vote.voter_id, vote.result, vote.proxy_id FROM vote "\
340                           + "WHERE vote.motion_id=$1) AS v ON proxy.voter_id = v.voter_id "\
341                           + "LEFT JOIN voter ON proxy.voter_id = voter.id "\
342                           + "WHERE proxy.proxy_id=$2 AND proxy.revoked IS NULL")
343     resultproxyvote = p(resultmotion[0][0], g.voter)
344
345     votes = None
346     if may("audit", resultmotion[0].get("type")) and not resultmotion[0].get("running") and not resultmotion[0].get("canceled"):
347         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")(resultmotion[0].get("id"));
348         votes = get_db().prepare("SELECT vote.result, voter.email, CASE voter.email WHEN proxy.email THEN NULL ELSE proxy.email END as proxyemail FROM vote INNER JOIN voter ON voter.id = vote.voter_id INNER JOIN voter as proxy ON proxy.id = vote.proxy_id WHERE vote.motion_id=$1")(resultmotion[0].get("id"));
349     return render_template('single_motion.html', motion=resultmotion[0], may_vote=may("vote", resultmotion[0].get("type")), may_cancel=may("cancel", resultmotion[0].get("type")), votes=votes, proxyvote=resultproxyvote, proxyname=resultproxyname)
350
351 @app.route("/motion/<string:motion>/vote/<string:voter>", methods=['POST'])
352 @validate_motion_access_vote('vote')
353 def vote(motion, voter, id):
354     v = request.form.get("vote", "abstain")
355     voterid=int(voter)
356     db = get_db()
357
358     # test if voter is proxy
359     if (voterid != g.voter):
360         rv = db.prepare("SELECT voter_id FROM proxy WHERE proxy.revoked IS NULL AND proxy.proxy_id = $1 AND proxy.voter_id = $2")(g.voter, voterid);
361         if len(rv) == 0:
362             return "Error, proxy not found.", 400
363
364     p = db.prepare("SELECT * FROM vote WHERE motion_id = $1 AND voter_id = $2")
365     rv = p(id, voterid)
366     if len(rv) == 0:
367         db.prepare("INSERT INTO vote(motion_id, voter_id, result, proxy_id) VALUES($1,$2,$3,$4)")(id, voterid, v, g.voter)
368     else:
369         db.prepare("UPDATE vote SET result=$3, entered=CURRENT_TIMESTAMP, proxy_id=$4 WHERE motion_id=$1 AND voter_id = $2")(id, voterid, v, g.voter)
370     return motion_edited(motion)
371
372 @app.route("/proxy")
373 def proxy():
374     if not may_admin("proxyadmin"):
375         return "Forbidden", 403
376     return render_template('proxy.html', voters=get_voters(), proxies=get_all_proxies(), may_proxyadmin=may_admin("proxyadmin"))
377
378 @app.route("/proxy/add", methods=['POST'])
379 def add_proxy():
380     if not may_admin("proxyadmin"):
381         return "Forbidden", 403
382     voter=request.form.get("voter", "")
383     proxy=request.form.get("proxy", "")
384     if voter == proxy :
385         return "Error, voter equals proxy.", 400
386     rv = get_db().prepare("SELECT id FROM voter WHERE email=$1")(voter);
387     if len(rv) == 0:
388         return "Error, voter not found.", 400
389     voterid = rv[0].get("id")
390     rv = get_db().prepare("SELECT id FROM voter WHERE email=$1")(proxy);
391     if len(rv) == 0:
392         return "Error, proxy not found.", 400
393     proxyid = rv[0].get("id")
394     rv = get_db().prepare("SELECT id FROM proxy WHERE voter_id=$1 AND revoked is NULL")(voterid);
395     if len(rv) != 0:
396         return "Error, proxy allready given.", 400
397     rv = get_db().prepare("SELECT COUNT(id) as c FROM proxy WHERE proxy_id=$1 AND revoked is NULL GROUP BY proxy_id")(proxyid);
398     if len(rv) != 0:
399         if rv[0].get("c") >= max_proxy:
400             return "Error, Max proxy for '" + proxy + "' reached.", 400
401     rv = get_db().prepare("INSERT INTO proxy(voter_id, proxy_id, granted_by) VALUES ($1,$2,$3)")(voterid, proxyid, g.voter)
402     return rel_redirect("/proxy")
403
404 @app.route("/proxy/revoke", methods=['POST'])
405 def revoke_proxy():
406     if not may_admin("proxyadmin"):
407         return "Forbidden", 403
408     id=request.form.get("id", "")
409     rv = get_db().prepare("UPDATE proxy SET revoked=CURRENT_TIMESTAMP, revoked_by=$1 WHERE id=$2")(g.voter, int(id))
410     return rel_redirect("/proxy")
411
412 @app.route("/proxy/revokeall", methods=['POST'])
413 def revoke_proxy_all():
414     if not may_admin("proxyadmin"):
415         return "Forbidden", 403
416     rv = get_db().prepare("UPDATE proxy SET revoked=CURRENT_TIMESTAMP, revoked_by=$1 WHERE revoked IS NULL")(g.voter)
417     return rel_redirect("/proxy")
418