forked from daeken/QuestCompanions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.py
183 lines (162 loc) · 4.61 KB
/
handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import os
from json import dumps
from flask import abort, render_template, request, session
from flask import redirect as _redirect
from werkzeug.exceptions import HTTPException
from metamodel import createLocalSession, closeLocalSession
from model import User
from urllib import quote, urlencode
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
class DictObject(dict):
pass
class StrObject(str):
pass
all = {}
def handler(_tpl=None, _json=False, admin=False, authed=True):
def sub(func):
name = func.func_name
rpc = False
tpl = _tpl
json = _json
if name.startswith('get_'):
name = name[4:]
method = 'GET'
elif name.startswith('post_'):
method = 'POST'
elif name.startswith('rpc_'):
method = 'POST'
rpc = json = True
tpl = None
else:
raise Exception('All handlers must be marked get_ or post_.')
module = func.__module__.split('.')[-1]
if not module in all:
all[module] = DictObject()
setattr(handler, module, all[module])
args = func.__code__.co_varnames[:func.__code__.co_argcount]
hasId = len(args) > 0 and args[0] == 'id' and not rpc
ofunc = func
def func(id=None):
createLocalSession()
if 'csrf' not in session:
token = os.urandom(16)
session['csrf'] = ''.join('%02x' % ord(c) for c in token)
if method == 'POST' and \
('csrf' not in request.form or request.form['csrf'] != session['csrf']):
abort(403)
if 'userId' in session and session['userId']:
session.user = User.one(id=int(session['userId']))
else:
session.user = None
if (authed or admin) and session.user == None:
return _redirect('/')
elif admin and not session.user.admin:
abort(403)
params = request.form if method == 'POST' else request.args
kwargs = {}
for i, arg in enumerate(args):
if i == 0 and arg == 'id' and not rpc:
continue
if arg in params:
kwargs[arg] = params[arg]
else:
assert not rpc # RPC requires all arguments.
try:
if hasId and id != None:
ret = ofunc(int(id), **kwargs)
else:
ret = ofunc(**kwargs)
except RedirectException, r:
return _redirect(r.url)
if json:
ret = dumps(ret)
elif tpl != None:
if ret == None:
ret = {}
ret['handler'] = handler
ret['request'] = request
ret['session'] = session
ret['len'] = len
ret = render_template(tpl + '.html', **ret)
csrf = '<input type="hidden" name="csrf" value="%s">' % session['csrf']
ret = ret.replace('$CSRF$', csrf)
closeLocalSession()
return ret
func.func_name = '__%s__%s__' % (module, name)
def url(_id=None, **kwargs):
if module == 'index':
url = '/'
trailing = True
else:
url = '/%s' % module
trailing = False
if name != 'index':
if not trailing:
url += '/'
url += '%s' % name
trailing = False
if _id != None:
if not trailing:
url += '/'
url += quote(str(_id))
if len(kwargs):
url += '?'
url += urlencode(dict((k, str(v)) for k, v in kwargs.items()))
return url
ustr = StrObject(url())
ustr.__call__ = ofunc
ustr.url = url
func.url = url
if not name in all[module]:
all[module][name] = method, args, rpc, [None, None]
if hasId and not rpc:
all[module][name][3][1] = func
else:
all[module][name][3][0] = func
setattr(all[module], ofunc.func_name, ustr)
return ustr
if _tpl != None and hasattr(_tpl, '__call__'):
func = _tpl
_tpl = None
return sub(func)
return sub
class RedirectException(Exception):
def __init__(self, url):
self.url = url
def redirect(url, _id=None, **kwargs):
if hasattr(url, '__call__') and hasattr(url, 'url'):
url = url.url(_id, **kwargs)
print 'Redirecting to', url
raise RedirectException(url)
from jinja2 import Environment, FileSystemLoader
email_env = Environment(loader=FileSystemLoader('templates/emails'))
def email(recv, tpl, **args):
tpl = email_env.get_template(tpl + '.html')
def render_template(tpl, **args):
return template.render(**args)
html = tpl.render(html=True, handler=handler, **args)
title, html = html.split('\n', 1)
text = tpl.render(html=False, handler=handler, **args)
msg = MIMEMultipart('alternative')
msg['Subject'] = title
_from = msg['From'] = '[email protected]'
msg['To'] = recv
msg.attach(MIMEText(text, 'plain'))
msg.attach(MIMEText(html, 'html'))
try:
s = smtplib.SMTP_SSL('email-smtp.us-east-1.amazonaws.com')
s.login('AKIAJTUVTEOZ2GOXQG7A', 'Anuu9LuAauvS/DL2/V0wAYKNNedacVXlq2d+JaDSYAgB')
s.sendmail(_from, recv, msg.as_string())
s.quit()
return True
except:
return False
handler.email = email
int_ = int
def int(v):
try:
return int_(v)
except:
return 0