def accounts_update(request, user_id): item = db.PlaidItem.query.get(int(request.body['plaid_item_id'])) if item.user_id != user_id: return Response(code=403) item.name = request.body['name'] or None db.session.commit() return Response.json(True)
def static(request, file_path): try: with open(path.join('static', file_path), 'rb') as f: content = f.read() except FileNotFoundError: return Response('not found', 404) content_type, _ = mimetypes.guess_type(file_path) return Response(body=content, content_type=content_type)
def logout(request): response = Response(code=303, location='/') response.set_secure_cookie(request, 'user_id', None, secure=True, max_age=datetime.timedelta()) return response
def static(request, filename): if not filename.endswith('.js') and not filename.endswith('.css'): return Response('not found', 404) try: with open(filename, 'rb') as f: content = f.read() except FileNotFoundError: return Response('not found', 404) content_type, _ = mimetypes.guess_type(filename) return Response(body=content, content_type=content_type)
def test_secure_cookie(self): app = PigWig([], cookie_secret=b"a|b") req = Request(app, None, None, None, None, None, None) r = Response() r.set_secure_cookie(req, "c|d", "e|f") set_cookie = r.headers[-1] self.assertEqual(set_cookie[0], "Set-Cookie") cookies = http.cookies.SimpleCookie(set_cookie[1]) req.cookies = cookies self.assertEqual(req.get_secure_cookie("c|d", None), "e|f")
def test_secure_cookie(self): app = PigWig([], cookie_secret=b'a|b') req = Request(app, None, None, None, None, None, None, None) r = Response() r.set_secure_cookie(req, 'c|d', 'e|f') set_cookie = r.headers[-1] self.assertEqual(set_cookie[0], 'Set-Cookie') cookies = http.cookies.SimpleCookie(set_cookie[1]) req.cookies = cookies self.assertEqual(req.get_secure_cookie('c|d', None), 'e|f')
def fetch_transactions(request, user_id): relogin_items = transactions.process_user(user_id) if len(relogin_items) > 0: return Response.render( request, 'relogin.jinja2', { 'environment': config.plaid.environment, 'plaid_public_key': config.plaid.public_key, 'relogin_items': relogin_items, }) else: return Response(code=303, location='/outcomes')
def test_json(self): r = Response.json(None) self.assertEqual(next(r.body), b"null") big_obj = ["a" * 256] * 256 r = Response.json(big_obj) chunks = list(r.body) self.assertGreater(len(chunks), 1) Response.json_encoder = json.JSONEncoder() r = Response.json(big_obj) chunks = list(r.body) self.assertGreater(len(chunks), 1) self.assertEqual(b"".join(chunks), json.dumps(big_obj).encode())
def test_json(self): r = Response.json(None) self.assertEqual(next(r.body), b'null') self.assertEqual(HTTPHeaders(r.headers)['Content-Type'], 'application/json; charset=utf-8') big_obj = ['a' * 256] * 256 r = Response.json(big_obj) chunks = list(r.body) self.assertGreater(len(chunks), 1) Response.json_encoder = json.JSONEncoder() r = Response.json(big_obj) chunks = list(r.body) self.assertGreater(len(chunks), 1) self.assertEqual(b''.join(chunks), json.dumps(big_obj).encode())
def login(request): try: username = request.body['username'] password = request.body['password'] except KeyError: raise HTTPException(400, 'username or password missing') cur = db.execute('SELECT id, password, salt FROM users WHERE username = ?', (username,)) user = next(cur) hashed = _hash(password, user['salt']) if hmac.compare_digest(user['password'], hashed): response = Response(code=303, location='/admin') response.set_secure_cookie(request, 'user_id', str(user['id']), max_age=LOGIN_TIME) return response else: raise HTTPException(401, 'incorrect username or password')
def test_cookie(self): app = PigWig([]) r = Response() r.set_cookie('cow', 'moo') r.set_cookie('duck', 'quack', path='/pond') cookies = http.cookies.SimpleCookie() for header, value in r.headers: if header == 'Set-Cookie': cookies.load(value) req = Request(app, None, None, None, None, None, cookies, None) self.assertEqual(req.cookies['cow'].value, 'moo') self.assertEqual(req.cookies['cow']['path'], '/') self.assertEqual(req.cookies['duck'].value, 'quack') self.assertEqual(req.cookies['duck']['path'], '/pond')
def posts(request, ids): ids = list(map(int, ids.split('/'))) posts = db.execute(''' SELECT users.username, posts.title, posts.body FROM posts JOIN users on posts.user_id = users.id WHERE posts.id IN (%s) ''' % ','.join('?' * len(ids)), ids) return Response.render(request, 'posts.jinja2', {'posts': posts})
def plaid_access_token(request, user_id): item_id, access_token = plaid.exchange_token(request.body['public_token']) db.session.add( db.PlaidItem(user_id=user_id, item_id=item_id, access_token=access_token)) db.session.commit() return Response.json(None)
def login(request): email = request.body['email'] password = request.body['password'] if 'register' in request.body: user = db.User.register(email, password) db.session.commit() location = '/accounts' else: user = db.User.login(email, password) if user is None: return Response('bad email/password', 403) location = '/outcomes' response = Response(code=303, location=location) response.set_secure_cookie(request, 'user_id', user.user_id, secure=True, max_age=datetime.timedelta(days=30)) return response
def post(request, id): posts = db.execute(''' SELECT users.username, posts.title, posts.body FROM posts JOIN users on posts.user_id = users.id WHERE posts.id = ? ''', id) try: post = next(posts) except StopIteration: raise HTTPException(404, 'invalid post id') return Response.render(request, 'posts.jinja2', {'posts': [post]})
def by_hour(request, guild_id): session = Session() query = session.query(Messages) \ .with_entities(func.strftime('%H', Messages.hour, 'unixepoch').label('agg_hour'), func.sum(Messages.count).label('count')) \ .group_by('agg_hour').order_by('agg_hour') query = _filter(query, int(guild_id), request.query) data = [] for row in query: data.append({'hour': row.agg_hour, 'count': row.count}) return Response.json(data)
def accounts(request, user_id): items = db.PlaidItem.query \ .filter(db.PlaidItem.user_id == user_id) \ .order_by(db.PlaidItem.plaid_item_id) \ .options(joinedload(db.PlaidItem.accounts)) \ .all() return Response.render( request, 'accounts.jinja2', { 'environment': config.plaid.environment, 'plaid_public_key': config.plaid.public_key, 'items': items, })
def root(request): posts = db.execute(''' SELECT posts.id, users.username, posts.title, posts.body FROM posts JOIN users on posts.user_id = users.id ORDER BY posts.id DESC LIMIT 10 ''') logged_in = False if request.get_secure_cookie('user_id', LOGIN_TIME): logged_in = True return Response.render(request, 'root.jinja2', {'posts': posts, 'logged_in': logged_in})
def _trace(code): args = [ '../nsjail/nsjail', '--use_cgroupv2', '--cgroupv2_mount', '/sys/fs/cgroup/NSJAIL', '-Mo', '--chroot', chroot_dir, '-E', 'LANG=en_US.UTF-8', '-R/usr', '-R/lib', '-R/lib64', '-R%s:/traceface' % traceface_dir, '-D/traceface', '--user', 'nobody', '--group', 'nogroup', '--time_limit', '2', '--disable_proc', '--iface_no_lo', '--cgroup_mem_max', str(50 * MB), '--cgroup_pids_max', '1', '--quiet', '--', '/usr/bin/python3', '-q', 'traceface', '-s' ] p = subprocess.run(args, input=code, capture_output=True, timeout=5) return Response(p.stdout, content_type='text/html; charset=UTF-8')
def channel_user_month_list(request, guild_id): session = Session() channels = [] for row in session.query(Channels).filter(Channels.guild_id == guild_id).order_by(Channels.name): channels.append({'id': str(row.channel_id), 'name': row.name}) users = [] for row in session.query(Users).order_by(Users.name): users.append({'id': str(row.int_user_id), 'name': row.name}) months = [] for row in session.query(Months).order_by(Months.month): months.append(row.month) return Response.json({'channels': channels, 'users': users, 'months': months})
def transaction_info(request, user_id): days = int(request.query['days']) plaid_transactions = db.PlaidTransaction.query \ .join(db.PlaidTransaction.account) \ .join(db.PlaidAccount.item) \ .filter(db.PlaidItem.user_id == user_id) \ .options(joinedload(db.PlaidTransaction.category), joinedload(db.PlaidTransaction.account)) \ .order_by(db.PlaidTransaction.date) \ .all() plaid_accounts = db.PlaidAccount.query \ .join(db.PlaidAccount.item) \ .filter(db.PlaidItem.user_id == user_id) \ .order_by(db.PlaidItem.plaid_item_id) \ .options(joinedload(db.PlaidAccount.item)) \ .all() return Response.json( info.transaction_info(plaid_transactions, plaid_accounts, days))
def by_channel(request, guild_id): session = Session() query = session.query(func.sum(Messages.count)) total = _filter(query, int(guild_id), request.query).scalar() query = session.query(Messages) \ .with_entities(Messages.channel_id, Channels.name, func.sum(Messages.count).label('count')) \ .outerjoin(Channels, Messages.channel_id == Channels.channel_id) \ .group_by(Channels.channel_id).order_by(func.sum(Messages.count).desc()) query = _filter(query, int(guild_id), request.query) data = [] for row in query: data.append({ 'name': row.name or str(row.channel_id), 'count': row.count, 'percentage': float('%.2f' % (row.count / total * 100)), }) return Response.json(data)
def http_exception_handler(e, errors, request, app): if e.code == 404: return Response.render(request, '404.jinja2', {}) return default_http_exception_handler(e, errors, request, app)
def guild_page(request, guild_id): guild = Session().query(Guilds).get(int(guild_id)) return Response.render(request, 'guild.html', {'guild': guild})
def wrapped(request): user_id = request.get_secure_cookie('user_id', datetime.timedelta(days=30)) if user_id is None: return Response(code=401) return view_fn(request, int(user_id))
def demo(request): return Response.render(request, 'outcomes.jinja2', {'demo': True})
def outcomes(request): return Response.render(request, 'outcomes.jinja2', {})
def plaid_link_token(request, user_id): item = db.PlaidItem.query.get(int(request.body['plaid_item_id'])) if item.user_id != user_id: return Response(code=403) link_token = plaid.link_token(user_id, item.access_token) return Response.json(link_token)
def root(request): return Response(html, content_type='text/html; charset=UTF-8')
def root(request): user_id = request.get_secure_cookie('user_id', datetime.timedelta(days=30)) return Response.render(request, 'root.jinja2', {'logged_in': user_id is not None})
def trace(request): if len(request.body['paste']) > 0: return Response(code=303, location='/trace/' + request.body['paste']) code = request.body['code'].encode('utf-8') return _trace(code)
def root(request): guilds = Session().query(Guilds).all() return Response.render(request, 'index.html', {'guilds': guilds})
def transaction_info_demo(request): days = int(request.query['days']) fake_transactions, fake_accounts = demo_transactions.data() return Response.json( info.transaction_info(fake_transactions, fake_accounts, days))
def markov_line(request, guild_id): guild_id = int(guild_id) line = markov_models[guild_id].make_short_sentence(150) username = random.choice(usernames[guild_id]) return Response.json({'username': username, 'line': line})
def login_form(request): return Response.render(request, 'login.jinja2', {})
def fetch_transactions(request, user_id): transactions.process_user(user_id) return Response(code=303, location='/outcomes')
def admin(request, user_id): return Response.render(request, 'admin.jinja2', {})
def emoji_stats(request, guild_id): guild = Session().query(Guilds).get(int(guild_id)) return Response.render(request, 'emoji.html', {'guild': guild})