-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatomat_wsgi.py
256 lines (223 loc) · 6.05 KB
/
matomat_wsgi.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import os
import sys
sys.path.append(os.path.dirname(__file__))
import config
from matomat import NotAuthenticatedError, matomat_factory, matomat
import database as db
import json
from datetime import datetime
from cgi import parse_qs
from sqlalchemy.orm import scoped_session
class matomat_wsgi(object):
def __init__(self,matomat):
self.matomat=matomat
def OK(self):
self.start_response('200 OK',[])
return []
def created(self):
self.start_response('201 CREATED',[])
return []
def bad_request(self):
self.start_response('400 BAD REQUEST',[])
return []
def forbidden(self):
self.start_response('403 FORBIDDEN',[])
return []
def not_found(self):
self.start_response('404 NOT FOUND',[])
return []
def conflict(self):
self.start_response('409 CONFLICT',[])
return []
def json_response(self,data):
self.start_response('200 OK',[("Content-type", "application/json"),("Cache-Control", "no-cache")])
return [json.dumps(data)]
return [json.dumps(data).encode('UTF-8')]
def init(self):
parts=self.path.split('/')
parts.pop(0)
if len(parts)>1:
password=self.environ.get('HTTP_PASS',None)
self.matomat.auth(parts.pop(0),password)
if len(parts):
cmd=parts.pop(0)
else:
cmd=None
return (cmd,parts)
def load_json(self):
length=int(self.environ.get('CONTENT_LENGTH',0))
if length==0:
return None
try:
d=(self.environ['wsgi.input'].read(length).decode('ASCII'))
data=json.loads(d)
except ValueError as ex:
return None
return data
def do_GET(self):
try:
if self.cmd=='balance':return self.balance()
elif self.cmd=='items':return self.items()
elif self.cmd=='details':return self.details()
elif self.cmd=='user':return self.user_get()
elif self.cmd=='date':return self.date_get()
return self.not_found()
except NotAuthenticatedError:
return self.forbidden()
def do_PUT(self):
try:
if self.cmd=='items':return self.items_put()
return self.not_found()
except NotAuthenticatedError:
return self.forbidden()
def do_POST(self):
try:
if self.cmd=='pay': return self.pay()
elif self.cmd=='payexternal': return self.payexternal()
elif self.cmd=='buy': return self.buy()
elif self.cmd=='undo': return self.undo()
elif self.cmd=='user': return self.user()
elif self.cmd=='transfer': return self.transfer()
elif self.cmd=='items':return self.items_post()
return self.not_found()
except NotAuthenticatedError:
return self.forbidden()
def do_DELETE(self):
try:
if self.cmd=='items':return self.items_delete()
return self.not_found()
except NotAuthenticatedError:
return self.forbidden()
def balance(self):
return self.json_response(self.matomat.balance())
def items(self):
return self.json_response(self.matomat.items())
def details(self):
return self.json_response(self.matomat.details())
def user_get(self):
qs=parse_qs(self.environ['QUERY_STRING'])
if 'key' in qs:
username=self.matomat.lookup_user(qs['key'][0])
else:
username=self.matomat.username()
return self.json_response({'username':username})
def date_get(self):
return self.json_response({'date':datetime.now().isoformat()})
def items_put(self):
try:
item=self.arg.pop(0)
except IndexError:
return self.not_found()
if not item is None:
try:
item=int(item)
except ValueError:
return self.bad_request()
data=self.load_json()
try:
name=data['name']
price=int(data['price'])
except KeyError:
return self.bad_request()
except ValueError:
return self.bad_request()
self.matomat.add_item(id=item,name=name,price=price)
return self.OK()
def items_post(self):
self.arg=[None]
return self.items_put()
def items_delete(self):
try:
item=self.arg.pop(0)
except IndexError:
return self.not_found()
try:
item=int(item)
except ValueError:
return self.bad_request()
self.matomat.delete_item(item)
return self.OK()
def pay(self):
data=self.load_json()
try:
amount=int(data)
except ValueError:
return self.bad_request()
self.matomat.pay(amount)
return self.created()
def payexternal(self):
data=self.load_json()
try:
amount=int(data)
except ValueError:
return self.bad_request()
try:
self.matomat.payexternal(amount)
except EnvironmentError:
return self.conflict()
return self.created()
def buy(self):
data=self.load_json()
try:
item_id=int(data)
except ValueError:
return self.bad_request()
self.matomat.buy(self.matomat.lookup_item(item_id))
return self.created()
def undo(self):
try:
self.matomat.undo()
except ValueError:
return self.conflict()
return self.created()
def user(self):
data=self.load_json()
try:
username=data['username']
password=data.get('password',None)
public_key=data.get('public_key',None)
except:
return self.bad_request()
try:
self.matomat.create_user(username,password,public_key)
except ValueError:
return self.bad_request()
return self.created()
def transfer(self):
data=self.load_json()
try:
amount=data['amount']
recipient=data['recipient']
except:
return self.bad_request()
try:
self.matomat.transfer(amount,recipient)
except ValueError:
return self.bad_request()
return self.created()
def __call__(self,environ,start_response):
try:
self.environ=environ
self.start_response=start_response
self.method=environ['REQUEST_METHOD']
self.path=environ['PATH_INFO']
self.cmd,self.arg=self.init()
if self.method=='GET': return self.do_GET()
if self.method=='PUT': return self.do_PUT()
if self.method=='POST': return self.do_POST()
if self.method=='DELETE': return self.do_DELETE()
return self.bad_request()
finally:
self.matomat.close()
def application(environ,start_response):
app=matomat_wsgi(matomat_factory(config.dbengine).get())
return app(environ,start_response)
class application_single_db:
def __init__(self):
self.Session=scoped_session(db.create_sessionmaker(config.dbengine))
def __call__(self,environ,start_response):
try:
self.Session()
return matomat_wsgi(matomat(self.Session))(environ,start_response)
finally:
self.Session.remove()