async def logout() -> "Response": del session["user_id"] del session["username"] return redirect(url_for(".login"))
async def wrapper(*args, **kwargs): if current_app.user_handler.get_user().is_real: return await function(*args, **kwargs) else: return redirect(url_for("home.login"))
async def send(): if current_user.verified: await flash("You are already verified.") abort(400) await send_mail(current_user, make_random_str(6)) return redirect(url_for('login.verify'))
async def trash(id): task = Todo.query.get(int(id)) db.session.delete(task) db.session.commit() return redirect(url_for("main.home"))
async def redir(self): return redirect(url_for("QuotesView.get", id=2))
async def yobot_login(): qqid = request.args.get('qqid') key = request.args.get('key') callback_page = request.args.get('callback', url_for('yobot_user')) now = int(time.time()) login_failure_reason = '登录失败' login_failure_advice = '请私聊机器人“{}登录”重新获取地址'.format( self.setting['preffix_string'] if self. setting['preffix_on'] else '') if qqid is not None and key is not None: user = User.get_or_none(User.qqid == qqid) if user is None or user.login_code != key: # 登录码错误 login_failure_reason = '无效的登录地址' login_failure_advice = '请检查登录地址是否完整' else: if user.login_code_expire_time < now: # 登录码正确但超时 login_failure_reason = '这个登录地址已过期' if not user.login_code_available: # 登录码正确但已被使用 login_failure_reason = '这个登录地址已被使用' else: # 登录码有效 new_key = _rand_string(32) session['yobot_user'] = qqid session['csrf_token'] = _rand_string(16) user.login_code_available = False user.last_login_time = now user.last_login_ipaddr = request.headers.get( 'X-Real-IP', request.remote_addr) user.auth_cookie = sha256( (new_key + user.salt).encode()).hexdigest() user.auth_cookie_expire_time = now + 604800 # 7 days user.save() new_cookie = f'{qqid}:{new_key}' res = await make_response(redirect(callback_page)) res.set_cookie('yobot_login', new_cookie, max_age=604800) return res # 未提供登录码 & 登录码错误 if 'yobot_user' in session: # 会话未过期 return redirect(callback_page) # 会话已过期 auth_cookie = request.cookies.get('yobot_login') if auth_cookie is not None: # 有cookie s = auth_cookie.split(':') if len(s) == 2: qqid, auth = s user = User.get_or_none(User.qqid == qqid) if user is None: login_failure_reason = '用户不存在' login_failure_advice = '请先加入一个公会' else: auth = sha256((auth + user.salt).encode()).hexdigest() if user.auth_cookie == auth: if user.auth_cookie_expire_time > now: # cookie有效 session['yobot_user'] = qqid session['csrf_token'] = _rand_string(16) user.last_login_time = now user.last_login_ipaddr = request.remote_addr user.save() return redirect(callback_page) else: # cookie正确但过期 login_failure_reason = '登录已过期' # 无cookie & cookie错误 return await render_template( 'login-failure.html', reason=login_failure_reason, advice=login_failure_advice, )
async def poll_query(query_id): """ Get the status of a previously submitted query. --- get: parameters: - in: path name: query_id required: true schema: type: string responses: '202': content: application/json: schema: properties: msg: type: string status: enum: - executing - queued type: string type: object description: Request accepted. '303': description: Data ready. headers: Location: description: URL to download data schema: format: url type: string '401': description: Unauthorized. '403': content: application/json: schema: type: object description: Token does not grant poll access to this query or spatial aggregation unit. '404': description: Unknown ID '500': description: Server error. summary: Get the status of a query """ await current_user.can_poll_by_query_id(query_id=query_id) request.socket.send_json({ "request_id": request.request_id, "action": "poll_query", "params": { "query_id": query_id }, }) reply = await request.socket.recv_json() if reply["status"] == "error": return jsonify({"status": "error", "msg": reply[""]}), 500 else: assert reply["status"] == "success" query_state = reply["payload"]["query_state"] if query_state == "completed": return ( jsonify({}), 303, { "Location": url_for(f"query.get_query_result", query_id=query_id) }, ) elif query_state in ("executing", "queued"): return jsonify({"status": query_state, "msg": reply["msg"]}), 202 elif query_state in ("errored", "cancelled"): return jsonify({"status": query_state, "msg": reply["msg"]}), 500 else: # TODO: would be good to have an explicit query state for this, too! return jsonify({"status": query_state, "msg": reply["msg"]}), 404
def welcome(): ip = request.remote_addr things = sessions[ip] if request.method == 'POST': return redirect(url_for('me'))
async def create(): form = await request.form blogs.insert_one() return redirect(url_for('posts'))
async def redirect_unauthorized(e): return redirect(url_for("login"))
def swagger_static(filename): return url_for('restplus_doc.static', filename=filename)
async def logout(): user = await discord.fetch_user() info(f"{user} just logged out") discord.revoke() return redirect(url_for("home"))
async def basket_clear(): if 'basket' in session: session['basket'].clear() return redirect(url_for('basket'))
async def profile_edit() -> Union[str, "Response"]: error: str = "" csrf_token: uuid.UUID = uuid.uuid4() # grab the user's details conn = current_app.dbc profile_user = await get_user_by_username(conn, session["username"]) if request.method == "GET": session["csrf_token"] = str(csrf_token) if request.method == "POST": form: dict = await request.form form_username = form.get("username", "") if not form_username: error = "Please enter username" if (session.get("csrf_token") != form.get("csrf_token") and not current_app.testing): error = "Invalid POST contents" # check if the username exists if username changed if not error and session["username"] != form_username: user = await get_user_by_username(conn, form_username) if user and user["id"]: error = "Username already exists" # image upload (skip if testing) changed_image: bool = False if not current_app.testing: files = await request.files profile_image = files.get("profile_image") # if no filename, no file was uploaded if profile_image.filename: filename = (str(uuid.uuid4()) + "-" + secure_filename(profile_image.filename)) file_path = os.path.join(UPLOAD_FOLDER, filename) profile_image.save(file_path) image_uid = thumbnail_process(file_path, "user", str(profile_user["id"])) changed_image = True # edit the profile if not error: if not current_app.testing: del session["csrf_token"] profile_user["username"] = form_username if changed_image: profile_user["image"] = image_uid # delete the profile image_urls before updating del profile_user["image_url_raw"] del profile_user["image_url_xlg"] del profile_user["image_url_lg"] del profile_user["image_url_sm"] user_update = user_table.update( user_table.c.id == profile_user["id"]).values(profile_user) await conn.execute(query=user_update) # update session with new username session["username"] = form_username # update session await flash("Profile edited") return redirect( url_for(".profile", username=profile_user["username"])) else: session["csrf_token"] = str(csrf_token) return await render_template( "user/profile_edit.html", error=error, profile_user=profile_user, csrf_token=csrf_token, )
async def index(): return 'This is the index page. Try the following to <a href="' + url_for( 'start_work') + '">start some test work</a> with a progress indicator.'
async def test_pint_blueprint_openapi(app: Pint, req_ctx) -> None: blueprint = PintBlueprint('blueprint', __name__, url_prefix='/blueprint') app.register_blueprint(blueprint) async with req_ctx(app, '/', method='GET'): assert '/openapi.json' == url_for('openapi')
def lnurl(self) -> str: url = url_for("lnurlp.api_lnurl_response", link_id=self.id, _external=True) return lnurl_encode(url)
async def yobot_login(): prefix = self.setting['preffix_string'] if self.setting[ 'preffix_on'] else '' if request.method == "POST": form = await request.form def get_params(k: str) -> str: return request.args.get(k) \ if request.method == "GET" \ else (form and k in form and form[k]) try: qqid = get_params('qqid') key = get_params('key') pwd = get_params('pwd') callback_page = get_params('callback') or url_for('yobot_user') auth_cookie = request.cookies.get(LOGIN_AUTH_COOKIE_NAME) if not qqid and not auth_cookie: # 普通登录 return await render_template( 'login.html', advice=f'请私聊机器人“{self._get_prefix()}登录”获取登录地址 ', prefix=self._get_prefix()) key_failure = None if qqid: user = User.get_or_none(User.qqid == qqid) if key: try: self._check_key(user, key) except ExceptionWithAdvice as e: if auth_cookie: qqid = None key_failure = e else: raise e from e if pwd: self._check_pwd(user, pwd) if auth_cookie and not qqid: # 可能用于用cookie寻回session if 'yobot_user' in session: # 会话未过期 return redirect(callback_page) try: user = self._recall_from_cookie(auth_cookie) except ExceptionWithAdvice as e: if key_failure is not None: raise key_failure else: raise e from e self._set_auth_info(user) if user.must_change_password: callback_page = url_for('yobot_reset_pwd') return redirect(callback_page) if not key and not pwd: raise ExceptionWithAdvice("无效的登录地址", "请检查登录地址是否完整") if user.must_change_password: callback_page = url_for('yobot_reset_pwd') res = await make_response(redirect(callback_page)) self._set_auth_info(user, res, save_user=False) user.login_code_available = False user.save() return res except ExceptionWithAdvice as e: return await render_template( 'login.html', reason=e.reason, advice=e.advice or f'请私聊机器人“{self._get_prefix()}登录”获取登录地址 ', prefix=prefix)
async def run_query(): """ Run a query. --- post: requestBody: content: application/json: schema: $ref: '#/components/schemas/FlowmachineQuerySchema' required: true responses: '202': description: Request accepted. headers: Location: description: URL to poll for status schema: format: url type: string '401': description: Unauthorized. '403': content: application/json: schema: type: object description: Token does not grant run access to this query or spatial aggregation unit. '400': content: application/json: schema: type: object description: Query spec could not be run.. '500': description: Server error. summary: Run a query """ json_data = await request.json current_user.can_run(query_json=json_data) request.socket.send_json({ "request_id": request.request_id, "action": "run_query", "params": json_data }) reply = await request.socket.recv_json() current_app.flowapi_logger.debug(f"Received reply {reply}", request_id=request.request_id) if reply["status"] == "error": # TODO: currently the reply msg is empty; we should either pass on the message payload (which contains # further information about the error) or add a non-empty human-readable error message. # If we pass on the payload we should also deconstruct it to make it more human-readable # because it will contain marshmallow validation errors (and/or any other possible errors?) return ( jsonify({ "status": "Error", "msg": reply["msg"], "payload": reply["payload"] }), 400, ) elif reply["status"] == "success": assert "query_id" in reply["payload"] d = { "Location": url_for(f"query.poll_query", query_id=reply["payload"]["query_id"]) } return jsonify({}), 202, d else: return ( jsonify({ "status": "Error", "msg": f"Unexpected reply status: {reply['status']}", }), 500, )
async def yobot_logout(): session.clear() res = await make_response(redirect(url_for('yobot_login'))) res.delete_cookie(LOGIN_AUTH_COOKIE_NAME) return res
async def redirect_unauthorized(e): session['login_original_path'] = request.full_path return redirect(url_for("login"))
async def start_minigame(): app.overlord.api.started = True app.overlord.started = True return redirect(url_for('home'))
async def check(id): task = Todo.query.get(int(id)) task.is_completed = True db.session.commit() return redirect(url_for("main.home"))
async def load_streamlabs_token(): streamlabs_token = request.args.getlist('access_token') await save_token(token=streamlabs_token, token_name='streamlabs_key', length=40) return redirect(url_for('token_settings'))
async def logout(): discord.revoke() return redirect(url_for(".index"))
async def logout(): # it just pops the user from session if("user" in session): session.pop("user") # then we go back to index return redirect(url_for('index'))
async def api_payments_create_invoice(): if "description_hash" in g.data: description_hash = unhexlify(g.data["description_hash"]) memo = "" else: description_hash = b"" memo = g.data["memo"] async with db.connect() as conn: try: payment_hash, payment_request = await create_invoice( wallet_id=g.wallet.id, amount=g.data["amount"], memo=memo, description_hash=description_hash, extra=g.data.get("extra"), webhook=g.data.get("webhook"), conn=conn, ) except InvoiceFailure as e: return jsonify({"message": str(e)}), 520 except Exception as exc: raise exc invoice = bolt11.decode(payment_request) lnurl_response: Union[None, bool, str] = None if g.data.get("lnurl_callback"): if "lnurl_balance_check" in g.data: save_balance_check(g.wallet.id, g.data["lnurl_balance_check"]) async with httpx.AsyncClient() as client: try: r = await client.get( g.data["lnurl_callback"], params={ "pr": payment_request, "balanceNotify": url_for( "core.lnurl_balance_notify", service=urlparse(g.data["lnurl_callback"]).netloc, wal=g.wallet.id, _external=True, ), }, timeout=10, ) if r.is_error: lnurl_response = r.text else: resp = json.loads(r.text) if resp["status"] != "OK": lnurl_response = resp["reason"] else: lnurl_response = True except (httpx.ConnectError, httpx.RequestError): lnurl_response = False return ( jsonify( { "payment_hash": invoice.payment_hash, "payment_request": payment_request, # maintain backwards compatibility with API clients: "checking_id": invoice.payment_hash, "lnurl_response": lnurl_response, } ), HTTPStatus.CREATED, )
async def root(): login_url_keycloak = url_for(openid_keycloak.endpoint_name_login) return f"""
async def get_template(template): tpl = await db.get_template(template) copy = tpl.copy() copy['name'] = template copy['pdf'] = url_for('get_template_pdf', template=template) return jsonify(copy)
async def edit_circle(id_: str) -> typing.Union[str, quart.Response]: async with client.authenticated_session() as session: try: circle = await client.get_group_by_id( id_, session=session, ) except aiohttp.ClientResponseError as exc: if exc.status == 404: await flash( _("No such circle exists"), "alert", ) return redirect(url_for(".circles")) raise users = sorted(await client.list_users(), key=lambda x: x.localpart) circle_members = [ user for user in users if user.localpart in circle.members ] form = EditCircleForm() form.user_to_add.choices = [(user.localpart, user.localpart) for user in users if user.localpart not in circle.members] valid_users = [x[0] for x in form.user_to_add.choices] invite_form = InvitePost() await invite_form.init_choices() invite_form.circles.data = [id_] if request.method != "POST": form.name.data = circle.name if form.validate_on_submit(): if form.action_save.data: await client.update_group( id_, new_name=form.name.data, ) await flash( _("Circle data updated"), "success", ) elif form.action_delete.data: await client.delete_group(id_) await flash( _("Circle deleted"), "success", ) return redirect(url_for(".circles")) elif form.action_add_user.data: if form.user_to_add.data in valid_users: await client.add_group_member( id_, form.user_to_add.data, ) await flash( _("User added to circle"), "success", ) elif form.action_remove_user.data: await client.remove_group_member( id_, form.action_remove_user.data, ) await flash( _("User removed from circle"), "success", ) return redirect(url_for(".edit_circle", id_=id_)) else: print(form.errors) return await render_template( "admin_edit_circle.html", target_circle=circle, form=form, circle_members=circle_members, invite_form=invite_form, )