async def handle_request(request): urls = request.args.getlist('url') callback = request.args.get('callback') if urls: if len(urls) > 10: return response.json([{ 'ok': False, 'error': 'Max 10 URLs allowed' }], status=400) async with aiohttp.ClientSession() as session: head_infos = await asyncio.gather(*[ head(session, url) for url in urls ]) if callback and is_valid_callback(callback): return response.text( '{}({})'.format(callback, json.dumps(head_infos, indent=2)), content_type='application/javascript', headers={'Access-Control-Allow-Origin': '*'}, ) else: return response.json( head_infos, headers={'Access-Control-Allow-Origin': '*'}, ) else: return response.html(INDEX)
async def score(request): from auth import get_hash, get_random_base64, validate_hash instance = request.app.config['LAZY_UMONGO'] req_data = await request.app.config['REQDATA_EXTRACTOR'](request) if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)): return _response.json({"error":"Missing authorization"}, status=403) username = req_data.get('username', '') user = await instance.User.find_one({'username':username}) node_id = req_data.get('node_id', '') prev_score = user.online_scores[node_id] action = req_data.get('action', '') if action == '4': new_score = max(0, prev_score - 0.5) user.dictset('online_scores', node_id, new_score) await user.commit() elif action == '5': new_score = max(0, prev_score - 0.1) user.dictset('online_scores', node_id, new_score) await user.commit() elif action == '6': new_score = min(1, prev_score + 0.1) user.dictset('online_scores', node_id, new_score) await user.commit() elif action == '9': new_score = min(1, prev_score + 0.5) user.dictset('online_scores', node_id, new_score) await user.commit() else: return _response.json({'error':'Invalid action'}, status=400) return _response.json({'successful':True, 'new_score':new_score})
async def wrapped(req, *args, **kwargs): try: return await func(req, *args, **kwargs) except SanicException as http_error: return json({"error": str(http_error)}, http_error.status_code) except IntegrityConstraintViolationError as sql_error: return json({"error": sql_error.args[0]}, 400)
async def get_wallet(request, account_id): """Get a single wallet. Can be user or taxbank. """ account = await request.app.db.fetchrow(""" SELECT account_id, account_type, amount FROM account_amount WHERE account_id = $1 """, account_id) if not account: raise AccountNotFoundError('Account not found') daccount = dict(account) if account['account_type'] == AccountType.USER: wallet = await request.app.db.fetchrow(""" SELECT taxpaid, steal_uses, steal_success, ubank FROM wallets_taxpaid WHERE user_id=$1 """, account_id) daccount.update(dict(wallet)) return response.json(daccount) return response.json(daccount)
async def reset(request, token): try: reset = db.session.query(PasswordReset).filter_by(UUID=token).first() if not reset: return response.json({"error": "Invalid reset token"}, 404) if not reset.isValid: return response.json({"error": "Reset token has already been used"}, 404) if pendulum.now("UTC") > pendulum.instance(reset.expireTime): return response.json({"error": "Reset token has expired."}, 400) # Invalidate all resets for this user # db.session.query(PasswordReset).filter_by(userId=reset.userId).update( # {"isValid": False} # ) db.session.commit() user = utils.get_account_by_id(reset.userId) userData = user.serialize() userData["jwt"] = user.gen_token(expire_hours=1) userData["message"] = "Valid token provided. Prompt user to change password" return response.json(userData, 200) except Exception as e: return utils.exeption_handler(e, "Password reset confirmation failed", 500)
async def put(self, request, id): try: user = utils.get_account_by_id(id) if not user: return response.json({"error": "User not found"}, 404) user.modifiedTime = pendulum.now("UTC") cleanData = utils.format_body_params(request.json) if not cleanData: return response.json( {"error": "No valid data provided for update"}, 400 ) if cleanData.get("password"): providedPass = cleanData.get("password") if len(providedPass) < request.app.config["MIN_PASS_LENGTH"]: return response.json( {"error": "New password does not meet length requirements"}, 400 ) user.password = utils.encrypt_pass(providedPass) if request.json.get("userRole"): user.userRole = cleanData.get("userRole").upper() if cleanData.get("emailAddress"): newEmail = cleanData.get("emailAddress") if ( utils.email_account_exists(newEmail) and utils.get_account_by_email(newEmail).id != user.id ): return response.json( {"error": "Email address associated with another account"}, 400 ) user.emailAddress = newEmail if cleanData.get("firstName"): user.firstName = cleanData.get("firstName") if cleanData.get("lastName"): user.lastName = cleanData.get("lastName") if cleanData.get("phoneNumber"): user.phoneNumber = cleanData.get("phoneNumber") if cleanData.get("isVerified"): user.isVerified = cleanData.get("isVerified") db.session.commit() res = user.serialize() res["success"] = "Account updated" return response.json(res, 200) except Exception as e: return utils.exeption_handler(e, "Account update failed", 400)
async def all_nodes(request): instance = request.app.config['LAZY_UMONGO'] req_data = await request.app.config['REQDATA_EXTRACTOR'](request) if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)): return _response.json({"error":"Missing authorization"}, status=403) node_list = instance.Node.find({}).to_list(app.config['MAX_LIST_LENGTH']) node_list = [ c.dump() for c in node_list ] return _response.json({'successful':True, 'node_list':node_list})
async def many_questions(request): instance = request.app.config['LAZY_UMONGO'] req_data = await request.app.config['REQDATA_EXTRACTOR'](request) if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)): return _response.json({"error":"Missing authorization"}, status=403) question_id_list = req_data.get('question_id_list', []) question_list = instance.Question.find({'_id': {'$in':question_id_list}}).to_list(app.config['MAX_LIST_LENGTH']) question_list = [ c.dump() for c in question_list ] return _response.json({'successful':True, 'question_list':question_list})
async def policy(request, name): l = [] if name == "hot": l = hot.get() elif name == "new": l = hot.new() if l: return json(l) else: return json({})
async def get(self, request): try: userId = utils.get_id_from_jwt(request) user = utils.get_account_by_id(userId) if not user: return response.json({"error": "User not found"}, 404) return response.json(user.serialize(), 200) except Exception as e: return utils.exeption_handler(e, "User not found", 400)
def get_years(request: Request) -> json: data, errors = Usercode().load(request.json) if not errors: if not data['usercode']: token = request.cookies.get('token') data['usercode'] = Config.current.tokens.find_one({'_id': token})['user_id'] user = get_user_info(data['usercode']) years = list(map(lambda x: x, user['content'])) return json(years) return json({'alert': parse_errors(errors)}, 403)
async def delete_account(request, account_id: int): try: await request.app.db.execute(""" DELETE FROM accounts WHERE account_id = $1 """, account_id) return response.json({'success': True}) except Exception as err: log.exception('error while deleting') return response.json({'success': False, 'err': repr(err)})
async def decorated_function(request, *args, **kwargs): userId = get_id_from_jwt(request) if not userId: return response.json({"error": "Not Authorized"}, 401) if requireAdmin == True: user = get_account_by_id(userId) if not user or user.userRole != "ADMIN": return response.json({"error": "Not Authorized"}, 401) return await f(request, *args, **kwargs)
def get_subjects(request: Request) -> json: data, errors = Usercode().load(request.json) if not errors: if not data['usercode']: token = request.cookies.get('token') data['usercode'] = Config.current.tokens.find_one({'_id': token})['user_id'] subjects = [] user = get_user_info(data['usercode']) for year in user['content']: subjects.extend(list(map(lambda x: list(x.keys())[0], user['content'][year]['scores']))) return json(subjects) return json({'alert': parse_errors(errors)}, 403)
async def get(self, request, id): try: user = User.get(User.id == id) return json({ '_message': 'User fetched successfully!', 'user': user }) except User.DoesNotExist: return json({ '_message': 'User does not exist', 'user': None })
async def question_info(request): instance = request.app.config['LAZY_UMONGO'] req_data = await request.app.config['REQDATA_EXTRACTOR'](request) if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)): return _response.json({"error":"Missing authorization"}, status=403) question_id = req_data.get('question_id', '') question = instance.question.find_one({'_id':question_id}) if question: return _response.json({'successful':True, 'question':question.dump()}) else: return _response.json({'error':"Some unexpected error occurred"}, status=400)
async def post(self, request): try: new_user = User.create(**loads(request.body)) return json({ '_message': 'User created successfully!', 'user': new_user, }) except IntegrityError as e: if "email" in str(e): return json({ '_message': 'Should fill out email field', 'user': None, })
def login(request: Request) -> json: data, errors = Login().load(request.json) if not errors: response = Config.current.users.find_one({'_id': data['usercode']}) or \ Config.current.admins.find_one({'_id': data['usercode']}) if not response: return json({'alert': ['User not registered']}, 403) if response['password'] != encrypt_password(data['password']): return json({'alert': ['Password does not match']}, 403) token = uuid.uuid4().hex Config.current.tokens.insert_one({'_id': token, 'created_at': datetime.utcnow(), 'user_id': data['usercode']}) return json({'token': token, 'username': response['username']}) return json({'alert': parse_errors(errors)}, 403)
async def kill_user(request): if os.getenv("ALLOW_PATCH_SUPER")!='yes': raise Exception("You are not super patch enabled") reqdata = get_reqdata(request) username = reqdata.get('username', None) if username is None: return response.json({'error':'Missing username'}, status=400) try: user = User.objects.get({'username':username}) user.delete() return response.json({}) except: return response.json({'warning':'Nobody died'}, status=210)
def get_faults(request: Request) -> json: data, errors = Usercode().load(request.json) if not errors: if not data['usercode']: token = request.cookies.get('token') data['usercode'] = Config.current.tokens.find_one({'_id': token})['user_id'] user = get_user_info(data['usercode']) data = [] years = list(map(lambda x: x, user['content'])) for year in years: data.append(user['content'][year]['faults']) response = {'name': 'Faults', 'labels': years, 'data': data, 'minimum_name': 'Media', 'minimum_data': list(map(lambda x: 120, data))} return json(response) return json({'alert': parse_errors(errors)}, 403)
async def user_info(request): instance = request.app.config['LAZY_UMONGO'] req_data = await request.app.config['REQDATA_EXTRACTOR'](request) if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)): return _response.json({"error":"Missing authorization"}, status=403) username = req_data.get('username', '') user = instance.User.find_one({'username':username}) if user: user_data = user.dump() del user_data['salt'] del user_data['password_hash'] return _response.json({'successful':True, 'user':user_data}) else: return _response.json({'error':"Some unexpected error occurred"}, status=400)
async def e500(request, exception): await handle_exception(request, exception) return json( status = exception.status_code, exception = "{}".format(exception) )
async def unlock_account(request): """UnLock an account from transfer operations.""" accounts = list(request.json['accounts']) for acc_id in accounts: request.app.account_locks[acc_id] = False return response.json({'status': True})
async def handle(request): coin = randint(0, 9) async with pool.acquire() as conn: async with conn.cursor() as cur: if coin < 6: await cur.execute("SELECT title, thumb, nc, nv FROM tst ORDER BY id DESC LIMIT 10") result = [] async for row in cur: result.append(dict(title=row[0], thumb=row[1], nc=row[2], nv=row[3])) resp = dict(list=result) elif coin < 8: title = randstr(140) thumb = randstr(140) nc = randint(0, 1000) nv = randint(0, 5000) await cur.execute("INSERT INTO tst(title, thumb, nc, nv) VALUES (%s, %s, %s, %s)", (title, thumb, nc, nv,)) resp = dict(action="insert", title=title, thumb=thumb, nc=nc, nv=nv) else: title = randstr(140) thumb = randstr(140) nc = randint(0, 1000) nv = randint(0, 5000) await cur.execute("UPDATE tst SET title=%s, thumb=%s, nc=%s, nv=%s " "WHERE id=(SELECT max(id) as m FROM tst LIMIT 1)", (title, thumb, nc, nv,)) resp = dict(action="update", title=title, thumb=thumb, nc=nc, nv=nv) return json(resp)
async def set_password(request): from auth import get_hash, get_random_base64, validate_hash instance = request.app.config['LAZY_UMONGO'] req_data = await request.app.config['REQDATA_EXTRACTOR'](request) if not (await request.app.config['HAS_AUTHORIZATION'](req_data, instance)): return _response.json({"error":"Missing authorization"}, status=403) username = req_data.get('username', '') old_password = req_data.get('old_password', '') new_password = req_data.get('new_password', '') user = await instance.User.find_one({'username':username}) if validate_hash(old_password, user.salt, user.password_hash): user.password_hash = get_hash(new_password, user.salt) await user.commit() return _response.json({'successful':True}) else: return _response.json({'error':"Old password do not match"}, status=400)
async def get_stats_handler(request): """Get stats about it all.""" gdp_data = await get_sums(request) res = { 'gdp': gdp_data['gdp'], } res.update(await get_counts(request)) res['user_money'] = gdp_data['user'] res['txb_money'] = gdp_data['taxbank'] steal_uses = await request.app.db.fetchrow(""" SELECT SUM(steal_uses) FROM wallets """) steal_uses = steal_uses['sum'] steal_success = await request.app.db.fetchrow(""" SELECT SUM(steal_success) FROM wallets; """) steal_success = steal_success['sum'] res['steals'] = steal_uses res['success'] = steal_success return response.json(res)
async def confirm_account(request, token): try: user = db.session.query(User).filter_by(UUID=token).first() if not user: return response.json({"error": "No user for given token"}, 400) user.isVerified = True db.session.commit() resp = user.serialize(jwt=True) resp["success"] = "User account confirmed" return response.json(resp, 200) except Exception as e: return utils.exeption_handler(e, "User confirmation failed", 500)
async def create_asset(request): """Creates a new Asset in state""" required_fields = ['name'] common.validate_fields(required_fields, request.json) signer = await common.get_signer(request) asset = _create_asset_dict(request.json, signer.get_public_key().as_hex()) batches, batch_id = transaction_creation.create_asset( txn_key=signer, batch_key=request.app.config.SIGNER, name=asset.get('name'), description=asset.get('description'), rules=asset.get('rules')) await messaging.send( request.app.config.VAL_CONN, request.app.config.TIMEOUT, batches) await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id) if asset.get('rules'): asset['rules'] = request.json['rules'] return response.json(asset)
async def bank_deposit(request, wallet_id): amount = decimal.Decimal(request.json['amount']) account = await request.app.db.fetchrow(""" SELECT account_id, account_type, amount FROM account_amount WHERE account_id = $1 """, wallet_id) if not account: raise AccountNotFoundError('Account not found') if account['account_type'] != AccountType.USER: raise ConditionError('Account is not taxbank') if account['amount'] < amount: raise ConditionError('Not enough funds') async with request.app.db.acquire() as conn, conn.transaction(): await conn.execute(""" UPDATE accounts SET amount = amount - $1 WHERE account_id = $2 """, str(amount), wallet_id) await conn.execute(""" UPDATE wallets SET ubank = ubank + $1 WHERE user_id = $2 """, str(amount), wallet_id) return response.json({ 'status': True, })
async def create_holding(request): """Creates a new Holding for the authorized Account""" required_fields = ['asset'] common.validate_fields(required_fields, request.json) holding = _create_holding_dict(request) signer = await common.get_signer(request) batches, batch_id = transaction_creation.create_holding( txn_key=signer, batch_key=request.app.config.SIGNER, identifier=holding['id'], label=holding.get('label'), description=holding.get('description'), asset=holding['asset'], quantity=holding['quantity']) await messaging.send( request.app.config.VAL_CONN, request.app.config.TIMEOUT, batches) await messaging.check_batch_status(request.app.config.VAL_CONN, batch_id) return response.json(holding)
async def pre_group(request): return json({"from": "bp1/pre-group"})
async def r3(request): return json({"from": "bp2/r3"})
async def age(request, age: int) -> json: return json({'hello': age})
if request.query_args[0][1] and request.query_args[0][1].isnumeric() \ else remaining cmd += ('-t', record_time, '-w') log.info(f'[{request.ip}] Record: [{record_time}]s {u7d_msg}') cmd += ('-i', request.ip) u7d = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE) try: await asyncio.wait_for(u7d.wait(), 0.5) msg = (await u7d.stdout.readline()).decode().rstrip() log.info(f'NOT_AVAILABLE: {msg} {u7d_msg}') await SESSION.get(f'{SANIC_EPG_URL}/reload_epg') return response.json( { 'status': 'NOT_AVAILABLE', 'msg': msg, 'cmd': u7d_msg }, 404) except asyncio.exceptions.TimeoutError: pass if record: return response.json({ 'status': 'OK', 'channel_id': channel_id, 'program_id': program_id, 'offset': offset, 'time': record_time }) log.info(f'[{request.ip}] Start: {u7d_msg}')
def spec(request, *args, **kwargs): return json(_spec)
async def get_all_web_servers(request, user): return json(web_servers)
async def health(request): return json({"message": "ok"})
def default_route(request): if request.headers.get("accepts") == "application/json": return json({"test": "value"}) else: return text("value")
async def bp3_r1(request): return json({"from": "bp3/r1"})
def get_resource_hander(request, resource_id): resource = {"resource_id": resource_id} return json(resource)
def list_resources_handler(request): resource = {} return json([resource])
async def get_handler(request): return json({"response": "OK"})
async def get(self, request): return json({"Experience"})
async def handle_channels(request): log.info(f'[{request.ip}] {request.method} {request.url}') if not os.path.exists(CHANNELS): return response.json({}, 404) return await response.file(CHANNELS)
async def get_contacts(request): call_data = request_json(request, ['user_id']) process_info = ContactsHandler.get_contacts(call_data['data']['user_id']) return json(process_info)
async def search(request): db = request.args.get('db', 'elasticsearch') search_term = request.args.get('search', 'dogs playing in the snow') text_features = encode_query(search_term) try: if db == 'elasticsearch': resp = await es.search( index=index_name, body={ "query": { "bool": { "should": [ { "script_score": { "query": { "match_all": {} }, "min_score": "1", "script": { "source": "cosineSimilarity(params.text_features, 'features')+1", "params": { "text_features": text_features }, }, }, }, ], } }, "_source": False }, size=18, request_timeout=100) return json(resp) elif db == 'opensearch': resp = await opensearch.search(index=index_name, body={ "query": { "knn": { "features": { "vector": text_features, "k": 18 } } }, "_source": { "excludes": ["features"] }, }, size=18, request_timeout=100) return json(resp) else: raise exceptions.InvalidUsage( f'Invalid db={db}, valid values are "elasticsearch" and "opensearch"' ) except TransportError as e: logger.error(e.info) raise e
def spec(request): return json(_spec)
async def index(request) -> json: return json({'hello': 'PyDO'})
async def health(request: Request): return response.json({"status": "ok"})
async def test(request): return response.json({"Redirected": True})
async def test(request, exception): return response.json({"exception": "{}".format(exception)}, status=exception.status_code)
async def test(request): return json({'hello': 'world'})
async def get_quotes(request): x = request.query_string.replace("stocks=", "") y = x.split(",") z = getQuotes(y) print(z) return json(z)
async def hentai_base_endpoint(request): tag = request.args.get('tag', None) if tag not in ALLOWED: tag = None url = Globals.file_manager.serve_random_file(endpoint="nsfw", area=tag) return response.json({'url': url})
async def handler(request): return json({"test": True})
async def hello(request, name: str) -> json: return json({'hello': name})
async def nlg(request): """Endpoint which processes the Core request for a bot response.""" nlg_call = request.json bot_response = await generate_response(nlg_call, domain) return response.json(bot_response)
async def handler_404(request, exception): return json({'error': 'Not Found'}, status=404)
async def bp2_r2(request): return json({"from": "bp2/r2"})
async def r1(request): return json({"from": "bp1/r1"})