]> WPIA git - motion.git/blob - motion.py
upd: ensure that no blank information is stored in motion title and
[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 # Load config
30 app.config.from_pyfile('config.py')
31
32
33 class ConfigProxy:
34     def __init__(self, name):
35         self.name = name
36     @property
37     def per_host(self):
38         dict = app.config.get(self.name)
39         if dict is None:
40             return None
41         return dict.get(request.host)
42
43 prefix = ConfigProxy("GROUP_PREFIX")
44 times = ConfigProxy("DURATION")
45 debuguser = ConfigProxy("DEBUGUSER")
46
47 @app.before_request
48 def lookup_user():
49     global prefix
50
51     env = request.environ
52     user = None
53     my_debuguser = debuguser.per_host
54     if my_debuguser is not None:
55         parts = my_debuguser.split("/", 1)
56         user = parts[0]
57         roles = parts[1]
58
59     if "USER_ROLES" in env:
60         parts = env.get("USER_ROLES").split("/", 1)
61         user = parts[0]
62         roles = parts[1]
63
64     if "USER" in env and "ROLES" in env:
65         user = env.get("USER")
66         roles = env.get("ROLES")
67
68     if user is None:
69         return "Server misconfigured", 500
70     roles = roles.split(" ")
71
72     if user == "<invalid>":
73         return "Access denied", 403;
74
75     db = get_db()
76     with db.xact():
77         rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
78         if len(rv) == 0:
79             db.prepare("INSERT INTO voter(\"email\") VALUES($1)")(user)
80             rv = db.prepare("SELECT id FROM voter WHERE email=$1")(user)
81         g.voter = rv[0].get("id");
82     g.user = user
83     g.roles = {}
84
85     for r in roles:
86         a = r.split(":", 1)
87         if len(r)!=0:
88             val = a[1]
89             if a[0] not in g.roles:
90                 g.roles[a[0]] = []
91             if val == "*":
92                 g.roles[a[0]] = [group for group in prefix.per_host]
93             else:
94                 g.roles[a[0]].append(val)
95     return None
96
97 def get_allowed_cats(action):
98     return g.roles.get(action, []);
99
100 def may(action, motion):
101     return motion in get_allowed_cats(action)
102
103 @app.teardown_appcontext
104 def close_connection(exception):
105     db = getattr(g, '_database', None)
106     if db is not None:
107         db.close()
108
109 def init_db():
110     with app.app_context():
111         db = get_db()
112         try:
113             ver = db.prepare("SELECT version FROM schema_version")()[0][0];
114             print("Database Schema version: ", ver)
115         except postgresql.exceptions.UndefinedTableError:
116             ver = 0
117
118         if ver < 1:
119             with app.open_resource('sql/schema.sql', mode='r') as f:
120                 db.execute(f.read())
121             return
122
123         if ver < 2:
124             with app.open_resource('sql/from_1.sql', mode='r') as f:
125                 db.execute(f.read())
126                 ct={}
127                 for g in [group for group in prefix[app.config.get("DEFAULT_HOST")]]:
128                     ct[g] = {"dt": "", "c": 0}
129
130                 p = db.prepare("UPDATE \"motion\" SET \"identifier\"=$1 WHERE \"id\"=$2")
131                 for row in db.prepare("SELECT id, \"type\", \"posed\" FROM \"motion\" ORDER BY \"id\" ASC"):
132                     dt=row[2].strftime("%Y%m%d")
133                     if ct[row[1]]["dt"] != dt:
134                         ct[row[1]]["dt"] = dt
135                         ct[row[1]]["c"] = 0
136                     ct[row[1]]["c"] = ct[row[1]]["c"] + 1
137                     name=prefix[app.config.get("DEFAULT_HOST")][row[1]]+"."+dt+"."+("%03d" % ct[row[1]]["c"])
138                     p(name, row[0])
139                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"identifier\" SET NOT NULL")()
140                 db.prepare("UPDATE \"schema_version\" SET \"version\"=2")()
141                 db.prepare("CREATE UNIQUE INDEX motion_ident ON motion (identifier)")()
142
143         if ver < 3:
144             with app.open_resource('sql/from_2.sql', mode='r') as f:
145                 db.execute(f.read())
146                 db.prepare("UPDATE \"motion\" SET \"host\"=$1")(app.config.get("DEFAULT_HOST"))
147                 db.prepare("ALTER TABLE \"motion\" ALTER COLUMN \"host\" SET NOT NULL")()
148                 db.prepare("UPDATE \"schema_version\" SET \"version\"=3")()
149
150
151 init_db()
152
153 @app.route("/")
154 def main():
155     start=int(request.args.get("start", "-1"));
156     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, "\
157                              + "COUNT(CASE WHEN result='yes' THEN 'yes' ELSE NULL END) as yes, "\
158                              + "COUNT(CASE WHEN result='no' THEN 'no' ELSE NULL END) as no, "\
159                              + "COUNT(CASE WHEN result='abstain' THEN 'abstain' ELSE NULL END) as abstain "\
160                              + "FROM vote GROUP BY motion_id) as votes ON votes.motion_id=motion.id "\
161                              + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
162                              + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
163     prev=None
164     if start == -1:
165         p = get_db().prepare(q + "WHERE motion.host = $1 ORDER BY motion.id DESC LIMIT 11")
166         rv = p(request.host)
167     else:
168         p = get_db().prepare(q + "WHERE motion.host = $1 AND motion.id <= $2 ORDER BY motion.id DESC LIMIT 11")
169         rv = p(request.host, start)
170         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)
171         if len(rs) == 10:
172             prev = rs[9][0]
173         else:
174             prev = -1
175     return render_template('index.html', motions=rv[:10], more=rv[10]["id"] if len(rv) == 11 else None, times=times.per_host, prev=prev,
176                            categories=get_allowed_cats("create"), singlemotion=False)
177
178 def rel_redirect(loc):
179     r = redirect(loc)
180     r.autocorrect_location_header = False
181     return r
182
183 @app.route("/motion", methods=['POST'])
184 def put_motion():
185     cat=request.form.get("category", "")
186     if cat not in get_allowed_cats("create"):
187         return "Forbidden", 403
188     time = int(request.form.get("days", "3"));
189     if time not in times.per_host:
190         return "Error, invalid length", 400
191     title=request.form.get("title", "")
192     title=title.strip()
193     if title =='':
194         return "Error, missing title", 400
195     content=request.form.get("content", "")
196     content=content.strip()
197     if content =='':
198         return "Error, missing content", 400
199
200     db = get_db()
201     with db.xact():
202         t = db.prepare("SELECT CURRENT_TIMESTAMP")()[0][0];
203         s = db.prepare("SELECT MAX(\"identifier\") FROM \"motion\" WHERE \"type\"=$1 AND \"host\"=$2 AND DATE(\"posed\")=DATE(CURRENT_TIMESTAMP)")
204         sr = s(cat, request.host)
205         ident=""
206         if len(sr) == 0 or sr[0][0] is None:
207             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+".001"
208         else:
209             ident=prefix.per_host[cat]+"."+t.strftime("%Y%m%d")+"."+("%03d" % (int(sr[0][0].split(".")[2])+1))
210         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)")
211         p(title, content, time, g.voter, cat, ident, request.host)
212     return rel_redirect("/")
213
214 def motion_edited(motion):
215     return rel_redirect("/?start=" + str(motion) + "#motion-" + str(motion))
216
217 def validate_motion_access(privilege):
218     def decorator(f):
219         def decorated_function(motion):
220             db = get_db()
221             with db.xact():
222                 rv = db.prepare("SELECT id, type, deadline < CURRENT_TIMESTAMP AS expired, canceled FROM motion WHERE identifier=$1 AND host=$2")(motion, request.host);
223                 if len(rv) == 0:
224                     return "Error, Not found", 404
225                 id = rv[0].get("id")
226                 if not may(privilege, rv[0].get("type")):
227                     return "Forbidden", 403
228                 if rv[0].get("canceled") is not None:
229                     return "Error, motion was canceled", 403
230                 if rv[0].get("expired"):
231                     return "Error, out of time", 403
232             return f(motion, id)
233         decorated_function.__name__ = f.__name__
234         return decorated_function
235     return decorator
236     
237 @app.route("/motion/<string:motion>/cancel", methods=['POST'])
238 @validate_motion_access('cancel')
239 def cancel_motion(motion, id):
240     if request.form.get("reason", "none") == "none":
241         return "Error, form requires reason", 500
242     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)
243     return motion_edited(id)
244
245 @app.route("/motion/<string:motion>/finish", methods=['POST'])
246 @validate_motion_access('finish')
247 def finish_motion(motion, id):
248     rv = get_db().prepare("UPDATE motion SET deadline=CURRENT_TIMESTAMP WHERE identifier=$1 AND host=$2 AND canceled is NULL")(motion, request.host)
249     return motion_edited(id)
250
251 @app.route("/motion/<string:motion>")
252 def show_motion(motion):
253     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 "\
254                          + "LEFT JOIN vote on vote.motion_id=motion.id AND vote.voter_id=$2 "\
255                          + "LEFT JOIN voter poser ON poser.id = motion.posed_by "\
256                          + "LEFT JOIN voter canceler ON canceler.id = motion.canceled_by "
257                          + "WHERE motion.identifier=$1 AND motion.host=$3")
258     rv = p(motion, g.voter, request.host)
259     if len(rv) == 0:
260         return "Error, Not found", 404
261     votes = None
262     if may("audit", rv[0].get("type")) and not rv[0].get("running") and not rv[0].get("canceled"):
263         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"));
264     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)
265
266 @app.route("/motion/<string:motion>/vote", methods=['POST'])
267 @validate_motion_access('vote')
268 def vote(motion, id):
269     v = request.form.get("vote", "abstain")
270     db = get_db()
271     p = db.prepare("SELECT * FROM vote WHERE motion_id = $1 AND voter_id = $2")
272     rv = p(id, g.voter)
273     if len(rv) == 0:
274         db.prepare("INSERT INTO vote(motion_id, voter_id, result) VALUES($1,$2,$3)")(id, g.voter, v)
275     else:
276         db.prepare("UPDATE vote SET result=$3, entered=CURRENT_TIMESTAMP WHERE motion_id=$1 AND voter_id = $2")(id, g.voter, v)
277     return motion_edited(id)