def decorated(*args, **kwargs): config = current_app.config # TODO: Replace this with actual auth testbed in tests if config.get('TESTING'): assert config.get('DEPLOY_ENV') == 'test' token = get_token_auth_header() if token.startswith('test-valid|'): test_jwt = TEST_JWT.copy() test_jwt['sub'] = token request._get_current_object().jwt = test_jwt else: raise AuthError( { "code": "token_test_invalid", "description": "test token is invalid" }, 401) return f(*args, **kwargs) token = get_token_auth_header() rsa_key = get_jwk(token) if rsa_key: try: payload = jwt.decode(token, rsa_key, algorithms=ALGORITHMS, audience=config['AUTH0_API_AUDIENCE'], issuer="https://" + AUTH0_DOMAIN + "/") except jwt.ExpiredSignatureError: raise AuthError( { "code": "token_expired", "description": "token is expired" }, 401) except jwt.JWTClaimsError: raise AuthError( { "code": "invalid_claims", "description": "incorrect claims," "please check the audience and issuer" }, 401) except Exception: raise AuthError( { "code": "invalid_header", "description": "Unable to parse authentication" " token." }, 401) request._get_current_object().jwt = payload return f(*args, **kwargs) raise AuthError( { "code": "invalid_header", "description": "Unable to find appropriate key" }, 401)
def close_session(exception=None): ctx = request._get_current_object() if hasattr(ctx, '_current_session'): s = ctx._current_session if exception is not None: s.rollback() s.close()
def run_socketio(path): real_request = request._get_current_object() real_app = current_app._get_current_object() socketio_manage( real_request.environ, {"/lobbies": LobbiesNamespace, "/lobby": LobbyNamespace}, request=(real_app, real_request) ) return Response()
def wrapper(*args, **kwargs): req = request._get_current_object() result = handler(req, *args, **kwargs) if isinstance(result, Effect): return sync_perform(dispatcher, result) else: return result
def get_session(): Session = apps.get_model('osf.Session') user_session = sessions.get(request._get_current_object()) if not user_session: user_session = Session() set_session(user_session) return user_session
def process_response(self, response): real_request = request._get_current_object() if real_request not in self.debug_toolbars: return response # Intercept http redirect codes and display an html page with a # link to the target. if self._application._config.get("web", "debug-toolbar", "intercept_redirects", "True") == "True": if (response.status_code in self._redirect_codes and not real_request.is_xhr): redirect_to = response.location redirect_code = response.status_code if redirect_to: content = self.render('redirect.html', { 'redirect_to': redirect_to, 'redirect_code': redirect_code }) response.content_length = len(content) response.location = None response.response = [content] response.status_code = 200 # If the http response code is 200 then we process to add the # toolbar to the returned html response. if not (response.status_code == 200 and response.is_sequence and response.headers['content-type'].startswith('text/html')): return response response_html = response.data.decode(response.charset) no_case = response_html.lower() body_end = no_case.rfind('</body>') if body_end >= 0: before = response_html[:body_end] after = response_html[body_end:] elif no_case.startswith('<!doctype html>'): before = response_html after = '' else: log.warning( 'Нет возможности использовать Debug Toolbar, ответ сервера не является валидным HTML' ) return response toolbar = self.debug_toolbars[real_request] for panel in toolbar.panels: panel.process_response(real_request, response) toolbar_html = toolbar.render_toolbar() content = ''.join((before, toolbar_html, after)) content = content.encode(response.charset) response.response = [content] response.content_length = len(content) return response
def _process_request(self): real_request = request._get_current_object() meta_data_as_dict = parse_meta_info_from_req(real_request) meta_data_as_dict['request_action'] = "_BEFORE_REQUEST_" if self.does_route_allowed(real_request.path): self.store_meta_fields(meta_data_as_dict, level="INFO")
def process_response(self, response): real_request = request._get_current_object() if real_request not in self.debug_toolbars: return response # Intercept http redirect codes and display an html page with a # link to the target. if current_app.config["DEBUG_TB_INTERCEPT_REDIRECTS"]: if response.status_code in self._redirect_codes and not real_request.is_xhr: redirect_to = response.location redirect_code = response.status_code if redirect_to: content = self.render("redirect.html", {"redirect_to": redirect_to, "redirect_code": redirect_code}) response.content_length = len(content) response.location = None response.response = [content] response.status_code = 200 # If the http response code is 200 then we process to add the # toolbar to the returned html response. if response.status_code == 200 and response.headers["content-type"].startswith("text/html"): for panel in self.debug_toolbars[real_request].panels: panel.process_response(real_request, response) if response.is_sequence: response_html = response.data.decode(response.charset) toolbar_html = self.debug_toolbars[real_request].render_toolbar() content = replace_insensitive(response_html, "</body>", toolbar_html + "</body>") content = content.encode(response.charset) response.response = [content] response.content_length = len(content) return response
def push_stream(rest): try: real_request = request._get_current_object() socketio_manage(request.environ, {'/chat': ChatNamespace}, request=real_request) except: app.logger.error('Exception while handling sockcketio connection', exc_info=True) return Response()
def is_browser(): """Is the current request from a browser?""" # all subrequests are not from browsers if hasattr(request._get_current_object(), 'is_subrequest') and request.is_subrequest: return False best_match = request.accept_mimetypes.best_match(_mime_types) return best_match == 'text/html'
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): if extra is None: extra = {} if 'requestid' not in extra: # Not all logging will be done from within a request # (eg, initial logging at start up). We need to be able to cope # with that. requestid = 'None' try: # "request" is a proxy object that passes along operations # to the real object. _get_current_object gives us the true # Request object, whose id is actually what we want. # Without this we end up with the id of the proxy object, which # is static for the life of the application. # TODO: this doesn't seem to be 100% unique. # Sometimes requests that happen around the same time will # end up with the same value here. Possibly only when the # query strings are the same, or srcip? requestid = id(request._get_current_object()) # RuntimeError will be raised if there's no active request. except RuntimeError: pass extra['requestid'] = requestid if six.PY2: # pragma: no cover return logging.Logger.makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra) return logging.Logger.makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra, sinfo) # pragma: no cover
def __fake_request_url_rule(self, method: str, url_path: str): """Tries to force-set the request URL rule. This is required by Eve (since 0.70) to be able to construct a Location HTTP header that points to the resource item. See post_internal, put_internal and patch_internal. """ import werkzeug.exceptions as wz_exceptions with self.test_request_context(method=method, path=url_path) as ctx: try: rule, _ = ctx.url_adapter.match(url_path, method=method, return_rule=True) except (wz_exceptions.MethodNotAllowed, wz_exceptions.NotFound): # We're POSTing things that we haven't told Eve are POSTable. Try again using the # GET method. rule, _ = ctx.url_adapter.match(url_path, method='GET', return_rule=True) current_request = request._get_current_object() current_request.url_rule = rule yield ctx
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None): if extra is None: extra = {} if 'requestid' not in extra: # Not all logging will be done from within a request # (eg, initial logging at start up). We need to be able to cope # with that. requestid = 'None' try: # "request" is a proxy object that passes along operations # to the real object. _get_current_object gives us the true # Request object, whose id is actually what we want. # Without this we end up with the id of the proxy object, which # is static for the life of the application. requestid = id(request._get_current_object()) # RuntimeError will be raised if there's no active request. except RuntimeError: pass extra['requestid'] = requestid return Logger.makeRecord(self, name, level, fn, lno, msg, args, exc_info, func, extra)
def process_response(self, response): real_request = request._get_current_object() if real_request not in self.debug_toolbars: return response # Intercept http redirect codes and display an html page with a # link to the target. if current_app.config["DEBUG_TB_INTERCEPT_REDIRECTS"]: if response.status_code in self._redirect_codes and not real_request.is_xhr: redirect_to = response.location redirect_code = response.status_code if redirect_to: content = self.render( "redirect.html", { "redirect_to": redirect_to, "redirect_code": redirect_code }, ) response.content_length = len(content) response.location = None response.response = [content] response.status_code = 200 # If the http response code is 200 then we process to add the # toolbar to the returned html response. if not (response.status_code == 200 and response.is_sequence and response.headers["content-type"].startswith("text/html")): return response response_html = response.data.decode(response.charset) no_case = response_html.lower() body_end = no_case.rfind("</body>") if body_end >= 0: before = response_html[:body_end] after = response_html[body_end:] elif no_case.startswith("<!doctype html>"): before = response_html after = "" else: warnings.warn("Could not insert debug toolbar." " </body> tag not found in response.") return response toolbar = self.debug_toolbars[real_request] for panel in toolbar.panels: panel.process_response(real_request, response) toolbar_html = toolbar.render_toolbar() content = "".join((before, toolbar_html, after)) content = content.encode(response.charset) response.response = [content] response.content_length = len(content) return response
def get_record_from_context(**kwargs): """Get the cached record object from kwargs or the request context.""" if 'record' in kwargs: return kwargs['record'] else: if request and \ hasattr(request._get_current_object(), 'current_file_record'): return request.current_file_record
def session() -> Session: ctx = request._get_current_object() try: session = ctx._current_session except AttributeError: session = app.create_session() ctx._current_session = session return session
def socketio(remaining): real_request = request._get_current_object() # add redis connection real_request._conn = get_connection() real_request._data_root = current_app.config.get("DATA_ROOT") real_request._signer = itsdangerous.Signer(current_app.secret_key) socketio_manage(request.environ, {"/status": StatusNamespace, "/build": BuildNamespace}, request=real_request) return Response()
def get_session(self): ctx = request._get_current_object() try: session = ctx._current_session except AttributeError: return None else: return session
def process_response(self, response): real_request = request._get_current_object() if real_request not in self.debug_toolbars: return response # Intercept http redirect codes and display an html page with a # link to the target. if current_app.config['DEBUG_TB_INTERCEPT_REDIRECTS']: if (response.status_code in self._redirect_codes and not real_request.is_xhr): redirect_to = response.location redirect_code = response.status_code if redirect_to: content = self.render('redirect.html', { 'redirect_to': redirect_to, 'redirect_code': redirect_code }) response.content_length = len(content) response.location = None response.response = [content] response.status_code = 200 # If the http response code is 200 then we process to add the # toolbar to the returned html response. if not (response.status_code == 200 and response.is_sequence and response.headers['content-type'].startswith('text/html')): return response response_html = response.data.decode(response.charset) no_case = response_html.lower() body_end = no_case.rfind('</body>') if body_end >= 0: before = response_html[:body_end] after = response_html[body_end:] elif no_case.startswith('<!doctype html>'): before = response_html after = '' else: warnings.warn('Could not insert debug toolbar.' ' </body> tag not found in response.') return response toolbar = self.debug_toolbars[real_request] for panel in toolbar.panels: panel.process_response(real_request, response) toolbar_html = toolbar.render_toolbar() content = ''.join((before, toolbar_html, after)) content = content.encode(response.charset) response.response = [content] response.content_length = len(content) return response
def get_flask_key(): """Get the current Flask request; if not working in request context, return the dummy request. """ try: return request._get_current_object() except RuntimeError: return dummy_request
def socketio(remaining): try: real_request = request._get_current_object() real_request.flask_session = session._get_current_object() socketio_manage(request.environ, {'/game': GameNamespace}, request=real_request) except: app.logger.error("Exception while handling socketio connect", exc_info=True) return Response()
def execute_search(): o = request._get_current_object() if len(o.data) is 0: return AbstractSchema(many=True).jsonify([]) content = json.loads(o.data) search = Search.from_dict(content["query"], max_results=content["limit"]) for entry in search.results: entry["_id"] = str(entry["_id"]) return AbstractSchema(many=True).jsonify(search.results)
def test_view_gets_decoded_instance(self): person = self.person_cls("Bob", "Smith") with self.test_client as c: res = c.post("/person", data=encode.dumper(person), content_type="application/json") self.assertIsInstance(request._get_current_object(), JsonWebRequest) self.assertIsInstance(request.json, self.person_cls) self.assertEqual(res.status_code, 200)
def initialize_request(self): """strong request""" new_request = Request(request._get_current_object(), authenticators=self.get_authenticators()) top = _request_ctx_stack.top if top is None: raise RuntimeError(_request_ctx_err_msg) top.request = new_request return new_request
def _teardown_request(self, exc_msg): if exc_msg: real_request = request._get_current_object() meta_data_as_dict = parse_meta_info_from_req(real_request) meta_data_as_dict['exception_message'] = exc_msg meta_data_as_dict['request_action'] = "_EXCEPTION_" if self.does_route_allowed(real_request.path): self.store_meta_fields(meta_data_as_dict, level="ERROR") return exc_msg
def validator(): req_path = request._get_current_object().path accept_path = "supernode" if current_app.config["IS_SUPERNODE"] else "node" if accept_path in req_path.split("/"): current_app.logger.debug("--- good path ---") else: current_app.logger.debug("--- bad path ---") abort(418, description="I'm not your guy")
def getMessages(): if request.method == 'GET': x = request._get_current_object() x = str(x) uid = x.replace("' [GET]>", "") uid = uid.partition("fromID=")[2] if uid == "": return jsonify(perrySummer.getMessages()) else: return perrySummer.getMessagebyID(uid)
def session(): if not has_request_context(): return Session() ctx = request._get_current_object() try: session_ = ctx._current_session except AttributeError: session_ = Session() ctx._current_session = session_ return session_
def write_session(): if has_request_context(): ctx = request._get_current_object() else: ctx = debug_context try: session_ = ctx._current_write_session except AttributeError: session_ = current_app.db.write_session() ctx._current_write_session = session_ return session_
def process_view(self, app, view_func, view_kwargs): """ This method is called just before the flask view is called. This is done by the dispatch_request method. """ real_request = request._get_current_object() if real_request in self.debug_toolbars: for panel in self.debug_toolbars[real_request].panels: new_view = panel.process_view(real_request, view_func, view_kwargs) if new_view: view_func = new_view return view_func
def next_page(): if not session.get("user",""): o = request._get_current_object() return redirect(url_for("login", next=request.path)) nextp = _get_next_page() if nextp: c,p =nextp return redirect(url_for("show_page", chapter=c, page=p)) else: return redirect(url_for("fertig"))
def _process_response(self, response): real_request = request._get_current_object() meta_data_as_dict = parse_meta_info_from_req(real_request) meta_resp_as_dict = parse_meta_info_from_response(response) meta_data_as_dict.update(meta_resp_as_dict) meta_data_as_dict['request_action'] = "_AFTER_RESPONSE_" if self.does_route_allowed(real_request.path): self.store_meta_fields(meta_data_as_dict, level="INFO") return response
def process_request(self): g.debug_toolbar = self if not self._show_toolbar(): return real_request = request._get_current_object() self.debug_toolbars[real_request] = DebugToolbar(real_request, self.jinja_env) for panel in self.debug_toolbars[real_request].panels: panel.process_request(real_request)
def session() -> Sess: ctx = request._get_current_object() try: session = ctx._current_session except AttributeError: test_connection = current_config.cached_property( current_config.CONN_CACHE_KEY) ctx._current_session = session = Session( bind=test_connection or create_engine(current_config)) finally: return session
def socketio(remaining): real_request = request._get_current_object() # add redis connection real_request._conn = get_connection() real_request._data_root = current_app.config.get('DATA_ROOT') real_request._signer = itsdangerous.Signer(current_app.secret_key) socketio_manage(request.environ, { '/status': StatusNamespace, '/build': BuildNamespace, }, request=real_request) return Response()
def socket_io(path): namespaces = { '/board': IONamespace, } try: _real_request = request._get_current_object() _real_request._app = app socketio_manage(request.environ, namespaces, _real_request) except: app.logger.error("Exception while handling socketio connection", exc_info=True) return Response()
def session() -> Session: if has_request_context(): ctx = request._get_current_object() app_config = current_app.config['APP_CONFIG'] try: session = ctx._current_session except AttributeError: bind = getattr(app_config, '_test_fx_connection', None) session = app_config.create_session(bind) ctx._current_session = session finally: return session
def run_socketio(path): real_request = request._get_current_object() try: socketio_manage( request.environ, {'/chat': ChatNamespace}, request=real_request ) except ValueError: app.logger.error("Exception while handling socketio connecdtion", exc_info=True) return Response()
def process_view(self, app, view_func, view_kwargs): """ This method is called just before the flask view is called. # FIXME/XXX: This method is currently not called!! """ real_request = request._get_current_object() if real_request in self.debug_toolbars: for panel in self.debug_toolbars[real_request].panels: new_view = panel.process_view(real_request, view_func, view_kwargs) if new_view: view_func = new_view return view_func
def run_socketio(path): real_request = request._get_current_object() real_app = current_app._get_current_object() socketio_manage(real_request.environ, { '/lobbies': LobbiesNamespace, '/lobby': LobbyNamespace, '/chat': ChatNamespace, }, request=(real_app, real_request)) current_app.logger.debug('Player: %s opened socket' % (g.player.id if g.player else 'Anonymous')) return Response()
def run_socketio(path): real_request = request._get_current_object() app = current_app._get_current_object() socketio_manage( real_request.environ, {'/search': MediasearchNamespace}, request=(real_request, app), ) return Response()
def get_cache_key(): """ Fetch a request key from either a Django or Flask request. Fall back on a process-global dummy object if we are not in either type of request """ # TODO: This is ugly use of exceptions; is there a better way to track whether in a given type of request? try: return request._get_current_object() except RuntimeError: # Not in a flask request context if getattr(api_globals, 'request', None) is not None: return api_globals.request else: # Not in a Django request return dummy_request
def test_open_session_with_cookie(self): sessint = self.session_interface sid = sessint.generate_sid() key = self.prefix + sid val = pickle.dumps(dict(a='a1', b='b1')) ten_seconds = 10 self.redis.setex(key, ten_seconds, val) with self.app.test_request_context('/'): current_request = request._get_current_object() cookie_name = self.app.session_cookie_name current_request.cookies = {cookie_name: sid} sess = sessint.open_session(self.app, current_request) self.assertIn('a', sess) self.assertIn('b', sess)
def process_response(self, response): real_request = request._get_current_object() if real_request not in self.debug_toolbars: return response # Intercept http redirect codes and display an html page with a # link to the target. if self.debug_toolbars[real_request].config['DEBUG_TB_INTERCEPT_REDIRECTS']: if response.status_code in self._redirect_codes: redirect_to = response.location redirect_code = response.status_code if redirect_to: content = self.render('redirect.html', { 'redirect_to': redirect_to, 'redirect_code': redirect_code }) response.content_length = len(content) response.location = None response.response = [content] response.status_code = 200 # If the http response code is 200 then we process to add the # toolbar to the returned html response. if response.status_code == 200: if response.headers['content-type'].startswith('text/html'): for panel in self.debug_toolbars[real_request].panels: panel.process_response(real_request, response) if response.is_sequence: response_html = response.data.decode(response.charset) toolbar_html = self.debug_toolbars[real_request].render_toolbar() content = replace_insensitive( response_html, '</body>', toolbar_html + '</body>') content = content.encode(response.charset) response.response = [content] response.content_length = len(content) elif response.headers['content-type'].startswith('application/json'): res_json = json.loads(response.data.decode(response.charset)) res_json['_debug_toolbar'] = {} for panel in self.debug_toolbars[real_request].panels: res_json['_debug_toolbar'][panel.name] = getattr(panel, 'debug_info', None) content = json.dumps(res_json) content = content.encode(response.charset) response.response = [content] response.content_length = len(content) return response
def determine_user_agent_facing_host(): """ Determines the host for the active request as seen by the User-Agent (client), assuming proxies along the way have been being truthful. """ # Request is a proxy object, and cannot be weakly-referenced; instead, # get a reference to true object. true_request = request._get_current_object() if true_request in HOST_CACHE: return HOST_CACHE[true_request] else: host = calculate_user_agent_facing_host() HOST_CACHE[true_request] = host return host
def process_view(self, app, view_func, view_kwargs): """ This method is called just before the flask view is called. This is done by the dispatch_request method. """ real_request = request._get_current_object() try: toolbar = self.toolbars[real_request] except KeyError: return view_func for panel in toolbar.panels: new_view = panel.process_view(real_request, view_func, view_kwargs) if new_view: view_func = new_view return view_func
def process_response(self, response): real_request = request._get_current_object() # If the http response code is 200 then we process to add the # toolbar to the returned html response. if '__trace__' in real_request.args: for panel in self.debug_toolbars[real_request].panels: panel.process_response(real_request, response) if response.is_sequence: toolbar_html = self.debug_toolbars[real_request].render_toolbar() response.headers['content-type'] = 'text/html' response.response = [toolbar_html] response.content_length = len(toolbar_html) return response