Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
executable file
·363 lines (307 loc) · 12.4 KB
/
Copy pathapp.py
File metadata and controls
executable file
·363 lines (307 loc) · 12.4 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#!/usr/bin/env python3
# Copyright (c) 2021 Jarret Dyrbye
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php
import time
import traceback
import logging
from flask import Flask, render_template, request, redirect
from flask_login import current_user, login_user, logout_user
from gunicorn.app.base import BaseApplication
from moneysocket.wad.wad import Wad
from moneysocket.beacon.beacon import MoneysocketBeacon
from moneysocket.beacon.location.websocket import WebsocketLocation
from models import UserModel, AccountAssignment, db, login
from config import read_config
from terminus_rpc import TerminusRpc
###############################################################################
# read config file
###############################################################################
config = read_config()
###############################################################################
# rpc connection
###############################################################################
rpc = TerminusRpc(config)
###############################################################################
# setup flask and db
###############################################################################
app = Flask(__name__)
app.secret_key = config['Db']['SecretKey']
app.config['SQLALCHEMY_DATABASE_URI'] = ("sqlite:////" +
config['Db']['DatabaseFile'])
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
login.init_app(app)
login.login_view = 'login'
db.init_app(app)
app.static_folder ='static'
###############################################################################
# database initialization
###############################################################################
@app.before_first_request
def create_table():
logging.info("create table")
db.create_all()
###############################################################################
# database helpers
###############################################################################
def user_accounts():
return [aa.account_name for aa in current_user.account_assignments]
###############################################################################
# app rpcs
###############################################################################
def getaccountinfo_rpc():
try:
ua = user_accounts()
info = rpc.call(['getaccountinfo'] + ua)
accounts = info['accounts']
for account in accounts:
account['wad'] = str(Wad.from_dict(account['wad']))
account['cap'] = str(Wad.from_dict(account['cap']))
except Exception as e:
logging.error(traceback.format_exc())
logging.error(e)
return {'success': False, 'error': "RPC exception"}
return accounts
def getaccountreceipts_rpc(account):
try:
info = rpc.call(['getaccountreceipts', account])
except Exception as e:
logging.error(traceback.format_exc())
logging.error(e)
return {'success': False, 'error': "RPC exception"}
return info
def connect_rpc(account, beacon):
try:
info = rpc.call(['connect', account, beacon])
except Exception as e:
logging.error(traceback.format_exc())
logging.error(e)
return {'success': False, 'error': "RPC exception"}
return info
def clear_rpc(account):
try:
info = rpc.call(['clear', account])
except Exception as e:
logging.error(traceback.format_exc())
logging.error(e)
return {'success': False, 'error': "RPC exception"}
return info
def rm_rpc(account):
try:
info = rpc.call(['rm', account])
except Exception as e:
logging.error(traceback.format_exc())
logging.error(e)
return {'success': False, 'error': "RPC exception"}
return info
def create_rpc(username):
cap = config['Account']['Cap']
start = config['Account']['StartBalance']
try:
info = rpc.call(['create', '-a', username, '-c', cap, start])
except Exception as e:
logging.error(traceback.format_exc())
logging.error(e)
return {'success': False, 'error': "RPC exception"}
return info
###############################################################################
# templates
###############################################################################
def render_accounts(error=None):
accounts = getaccountinfo_rpc()
return render_template("accounts.html", error=error, accounts=accounts)
def render_receipts(account):
info = getaccountreceipts_rpc(account)
if not info['success']:
return render_accounts(error=info['error'])
receipts = format_receipts(info['receipts'])
return render_template('receipts.html', account_name=account,
receipts=receipts, n_receipts=len(receipts))
def render_login(error=None):
return render_template('login.html', error=error,
account_cap=config['Account']['Cap'])
def render_register(error=None):
return render_template('register.html', error=error)
###############################################################################
# app actions
###############################################################################
def format_receipts(receipts):
# make info easy to render into templete
new = []
for session in receipts:
new_session = {'entries': []}
for entry in session:
new_entry = {'values': []}
for k, v in entry.items():
if k == 'type':
t = v.replace("_", " ").title()
new_entry['type'] = t
elif k == 'time':
t = time.ctime(v)
new_entry['time'] = t
elif k == 'wad':
w = Wad.from_dict(v)
new_entry['values'].append(('Wad', str(w)))
else:
new_entry['values'].append((k.title(), str(v)))
new_session['entries'].append(new_entry)
new.append(new_session)
return new
def list_receipts(account):
return render_receipts(account)
def generate_beacon(account):
beacon = MoneysocketBeacon()
location = WebsocketLocation(config['Beacon']['RelayLocation'])
beacon.add_location(location)
info = connect_rpc(account, str(beacon))
if not info['success']:
return render_accounts(error=info['error'])
return render_accounts()
def clear_beacons(account):
info = clear_rpc(account)
if not info['success']:
return render_accounts(error=info['error'])
return render_accounts()
def remove_account(account):
info = clear_rpc(account)
if not info['success']:
return render_accounts(error=info['error'])
info = rm_rpc(account)
if not info['success']:
return render_accounts(error=info['error'])
aa = AccountAssignment.query.filter_by(account_name=account).first()
db.session.delete(aa)
db.session.commit()
return render_accounts()
def new_account(username):
ua = user_accounts()
limit = int(config['Account']['AccountsPerUser'])
if len(ua) >= limit:
return render_accounts(error="max %d accounts per user" % limit)
info = create_rpc(username)
if not info['success']:
return render_accounts(error=info['error'])
account_name = info['name']
u = UserModel.query.filter_by(username=username).first()
aa = AccountAssignment(user_id=u.id, account_name=account_name)
db.session.add(aa)
db.session.commit()
return render_accounts()
###############################################################################
# redirect
###############################################################################
def redirect_path(path):
return redirect(config['Server']['ExternalBaseUrl'] + path)
###############################################################################
# app interaction
###############################################################################
@app.route('/accounts', methods = ['POST', 'GET'])
def accounts():
if not current_user.is_authenticated:
logging.info("not logged in, redirecting")
return redirect_path('/login')
logging.info("accounts: %s" % request.method)
if request.method == 'POST':
if 'list_receipts' in request.form:
action = 'list_receipts'
logging.info(action)
return list_receipts(request.form[action])
elif 'generate_beacon' in request.form:
action = 'generate_beacon'
logging.info(action)
return generate_beacon(request.form[action])
elif 'clear_beacons' in request.form:
action = 'clear_beacons'
logging.info(action)
return clear_beacons(request.form[action])
elif 'remove_account' in request.form:
action = 'remove_account'
logging.info(action)
return remove_account(request.form[action])
elif 'new_account' in request.form:
# TODO cap max accounts per user
action = 'new_account'
logging.info(action)
return new_account(request.form[action])
else:
logging.info("unknown")
return render_accounts(error="unknown action")
else:
logging.info("render accounts")
# TODO filter by db ownership
return render_accounts()
@app.route('/')
def root():
logging.info("root: %s" % request.method)
if current_user.is_authenticated:
logging.info("current_user: %s" % current_user)
return redirect_path('/accounts')
else:
return redirect_path('/login')
###############################################################################
# login lifecycle
###############################################################################
@app.route('/login', methods = ['POST', 'GET'])
def login():
logging.info("login: %s" % request.method)
if current_user.is_authenticated:
logging.info("current_user: %s" % current_user)
return redirect_path('/accounts')
if request.method == 'POST':
email = request.form['email']
user = UserModel.query.filter_by(email = email).first()
if user is not None and user.check_password(request.form['password']):
login_user(user)
return redirect_path('/accounts')
return render_login(error="invalid username/pw")
return render_login()
@app.route('/register', methods=['POST', 'GET'])
def register():
logging.info("register: %s" % request.method)
if current_user.is_authenticated:
logging.info("current_user: %s" % current_user)
return redirect_path('/accounts')
if request.method == 'POST':
if "email" not in request.form:
return render_register(error='no email?')
if "username" not in request.form:
return render_register(error='no username?')
if "password" not in request.form:
return render_register(error='no password?')
email = request.form['email']
username = request.form['username']
password = request.form['password']
if len(password) < 8:
return render_register(error='password must be 8 chars long')
if UserModel.query.filter_by(email=email).first():
return render_register(error='Email already present')
if UserModel.query.filter_by(username=username).first():
return render_register(error='Username already present')
user = UserModel(email=email, username=username)
user.set_password(password)
db.session.add(user)
db.session.commit()
return redirect_path('/login')
return render_register()
@app.route('/logout')
def logout():
logging.info("logout: %s" % request.method)
logout_user()
return redirect_path('/accounts')
###############################################################################
# load gunicorn stuff
###############################################################################
class CustodialApplication(BaseApplication):
def __init__(self, options):
self.options = options
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
def init(self, parser, opts, args):
pass