def exception_handling(e: Exception): """ Handles any uncaught exceptions and shows an applicable error page :param e: The caught exception :return: The response to the exception """ if isinstance(e, HTTPException): error = e if e.code == 401: flash( config.STRINGS["401_message"], AlertSeverity.DANGER.value ) return redirect(url_for("user_management.login")) app.logger.warning("Caught HTTP exception: {}".format(e)) else: error = HTTPException(config.STRINGS["500_message"]) error.code = 500 trace = "".join(traceback.format_exception(*sys.exc_info())) app.logger.error("Caught exception: {}\n{}".format(e, trace)) sentry_sdk.capture_exception(e) return render_template( config.REQUIRED_TEMPLATES["error_page"], error=error )
def test_handle_error_401_sends_challege_default_realm(self, api): exception = HTTPException() exception.code = 401 exception.data = {"foo": "bar"} resp = api.handle_error(exception) assert resp.status_code == 401 assert resp.headers["WWW-Authenticate"] == 'Basic realm="flask-restx"'
def test_handle_request_error(): #handle_request_error(error=None,request=None,level='info') with app.app_context(): from shotglass2.takeabeltof.utils import handle_request_error error = HTTPException() error.code=404 result = handle_request_error(error,None) assert "Request status: 404" in result
def abort(response, status_code=None): if isinstance(response, basestring): response = make_response(response) if status_code: response.status_code = status_code e = HTTPException(response=response) e.code = getattr(response, 'status_code', 0) raise e
def abort(response, status_code=None): if isinstance(response, basestring): response = make_response(response) if status_code: response.status_code = status_code e = HTTPException(response=response) e.code = getattr(response, 'status_code', 0) raise e
def test_handle_error_401_sends_challege_default_realm(self, api): exception = HTTPException() exception.code = 401 exception.data = {'foo': 'bar'} resp = api.handle_error(exception) assert resp.status_code == 401 assert resp.headers['WWW-Authenticate'] == 'Basic realm="flask-restplus"'
def test_handle_http_error_pass(app): """Assert that the RoutingException is passed through the handler.""" with app.app_context(): err = HTTPException(description='description') err.code = 200 response = errorhandlers.handle_http_error(err) assert response.status_code == 200
def get(self, exception, code): if 'HTTPException' in exception: e = HTTPException() elif 'CustomException' in exception: e = CustomException() else: raise AssertionError('Unexpected exception received: %s' % exception) e.code = code raise e
def test_when_generic_http_error_is_raised(self): expected_status_code = 400 expected_message = ["generic http error"] exception = HTTPException("generic http error") exception.code = 400 response = handle_error(exception) self.assertResponse(response, expected_status_code, expected_message)
def handle_http_error(error: HTTPException) -> Tuple[Response, int]: error.code = error.code or 500 if error.code >= 500: current_app.logger.exception(error) return jsonify({ 'status': 'error', 'message': str(error), 'code': error.code, 'errors': [error.description] }), error.code
def test_handle_error_401_sends_challege_default_realm(self): exception = HTTPException() exception.code = 401 exception.data = {'foo': 'bar'} with self.app_401.test_request_context('/foo'): resp = self.api_401.handle_error(exception) self.assertEquals(resp.status_code, 401) self.assertEquals(resp.headers['WWW-Authenticate'], 'Basic realm="flask-restful"')
def test_handle_error_401_sends_challege_default_realm(self): api = restplus.Api(self.app, serve_challenge_on_401=True) exception = HTTPException() exception.code = 401 exception.data = {'foo': 'bar'} with self.app.test_request_context('/foo'): resp = api.handle_error(exception) self.assertEqual(resp.status_code, 401) self.assertEqual(resp.headers['WWW-Authenticate'], 'Basic realm="flask-restful"')
def test_handle_error_401_sends_challege_default_realm(self): api = restplus.Api(self.app, serve_challenge_on_401=True) exception = HTTPException() exception.code = 401 exception.data = {'foo': 'bar'} with self.app.test_request_context('/foo'): resp = api.handle_error(exception) self.assertEqual(resp.status_code, 401) self.assertEqual(resp.headers['WWW-Authenticate'], 'Basic realm="flask-restful"')
def test_when_flask_restful_error_is_raised(self): expected_status_code = 400 expected_message = ["Input Error - field: missing"] exception = HTTPException() exception.data = {'message': {'field': 'missing'}} exception.code = 400 response = handle_error(exception) self.assertResponse(response, expected_status_code, expected_message)
def _abort(status_code, data_object, description, headers): # Add CORS headers to all errors options_resp = current_app.make_default_options_response() headers["Access-Control-Allow-Methods"] = options_resp.headers["allow"] headers["Access-Control-Max-Age"] = str(21600) headers["Access-Control-Allow-Headers"] = ["Authorization", "Content-Type"] resp = make_response(json.dumps(data_object), status_code, headers) # Report the abort to the user. # Raising HTTPException as workaround for https://github.com/pallets/werkzeug/issues/1098 new_exception = HTTPException(response=resp, description=description) new_exception.code = status_code raise new_exception
def user_loader_error_loader(identity): e = HTTPException(description='Error loading the user %r' % identity) e.code = HTTPStatus.UNAUTHORIZED return response_error(e)
def abort(self, response): e = HTTPException(response=response) e.code = getattr(response, 'status_code', 0) raise e
def _400(desc): # pragma: no cover exc = HTTPException() exc.code = 400 exc.description = desc return error_handling(exc)
def revoked_token_loader(): e = HTTPException(description='Token has been revoked') e.code = HTTPStatus.UNAUTHORIZED return response_error(e)
def raise_exception(message, message_dict, error_code=http.UNPROCESSABLE_REQUEST.code): e = HTTPException(message) e.data = message_dict e.code = error_code raise e
TypeError("test exception"), ValueError("test exception"), AttributeError("test exception") ]) def basic_exception(request): return request.param @pytest.fixture( params=[exception("test exception") for exception in LOWBALL_EXCEPTIONS]) def lowball_exception(request): return request.param http_exception1 = HTTPException("test exception") http_exception1.code = 400 http_exception2 = HTTPException("test exception") http_exception2.code = 401 http_exception3 = HTTPException("test exception") http_exception3.code = 404 @pytest.fixture(params=[http_exception1, http_exception2, http_exception3]) def http_exception_lt_500(request): return request.param http_exception4 = HTTPException("test exception") http_exception4.code = 500 http_exception5 = HTTPException("test exception") http_exception5.code = 501
def http_ensure(case, msg, code=400): "if not case, raise a client error exception (by default)" if not case: ex = HTTPException(msg) ex.code = code raise ex
def error(error_code): exception = HTTPException() exception.description = errors[error_code] exception.code = error_code return exception
def unauthorized_loader(message): e = HTTPException(description=message) e.code = HTTPStatus.UNAUTHORIZED return response_error(e)
def needs_fresh_token_loader(): e = HTTPException(description='Fresh token required') e.code = HTTPStatus.UNAUTHORIZED return response_error(e)
# def validate_schema(): "validates the api schema" path = join(conf.PROJECT_DIR, 'schema', 'api.yaml') spec = flex.load(path) validate(spec) return True def http_ensure(case, msg, code=400): "if not case, raise a client error exception (by default)" if not case: ex = HTTPException(msg) ex.code = code raise ex def listfiles(path, ext_list=None): "returns a pair of (basename_list, absolute_path_list) for given dir, optionally filtered by extension" path_list = lmap(lambda fname: os.path.abspath(join(path, fname)), os.listdir(path)) if ext_list: path_list = lfilter(lambda path: os.path.splitext(path)[1] in ext_list, path_list) path_list = sorted(filter(os.path.isfile, path_list)) return lmap(os.path.basename, path_list) #
ticket = { "name": username, "pass": False, "info": user.get("info") } addCache(user_key, json.dumps(ticket)) else: ticket = json.loads(ticket) if not ticket.get("pass"): if ticket.get("info") == "NO_USER_EXISTS": raise Forbidden(ticket.get("info")) elif ticket.get("info") == "INPUT_ERROR": raise Unauthorized(ticket.get("info")) else: hTTPException = HTTPException(ticket.get("info")) hTTPException.code = 402 raise hTTPException return ticket def internal_verify(username, remote_addr): user_key = username + remote_addr try: ticket = user_cache.get(user_key) if not ticket: user_config = db.overloads_config.find_one({"USERNAME": username}) if user_config == None: user_config = {} ticket = { "name": username,
def verify(username, password, remote_addr): ''' 用户验证 Parameters ---------- username : 用户名 password : 密码 remote_addr : 远程地址 Returns ------- CHECKIN_URL 通过portal验证的URL portal返回: '{"rcmsid":"2922","result":"SUCCESS","info":"","whitelist":[],"isSub":false,"parent":""}' user_cache redis存储的临时数据,在 2 库 db mongodb overloads_config URL_OVERLOAD_PER_HOUR = 10000 DIR_OVERLOAD_PER_HOUR = 100 ''' # if username: # username = username.lower() user_key = username + password + remote_addr ticket = user_cache.get(user_key) if not ticket: try: user = json.loads( urllib.request.urlopen( CHECKIN_URL % urllib.parse.urlencode({ "username": username, "pwd": password, "ignoreCase": False })).read()) except Exception: logger.error('verify [error]: %s' % (traceback.format_exc())) logger.debug(CHECKIN_URL % urllib.parse.urlencode({ "username": username, "pwd": password })) logger.debug( urllib.request.urlopen(CHECKIN_URL % urllib.parse.urlencode({ "username": username, "pwd": password })).read()) if user.get('result') == 'SUCCESS': user_config = db.overloads_config.find_one({"USERNAME": username}) if user_config == None: user_config = {} ticket = { "name": username, "parent": user.get('parent') if user.get('isSub') else username, "isSub": user.get('isSub'), "pass": True, "URL_OVERLOAD_PER_HOUR": user_config.get("URL", URL_OVERLOAD_PER_HOUR), "DIR_OVERLOAD_PER_HOUR": user_config.get("DIR", DIR_OVERLOAD_PER_HOUR), "PRELOAD_URL_OVERLOAD_PER_HOUR": user_config.get("PRELOAD_URL", PRELOAD_URL_OVERLOAD_PER_HOUR) } if user.get('whitelist'): if remote_addr not in user.get('whitelist'): ticket = { "name": username, "pass": False, "info": "%s not in whitelist" % remote_addr } else: ticket = { "name": username, "pass": False, "info": user.get("info") } addCache(user_key, json.dumps(ticket)) else: ticket = json.loads(ticket) if not ticket.get("pass"): if ticket.get("info") == "NO_USER_EXISTS": raise Forbidden(ticket.get("info")) elif ticket.get("info") == "INPUT_ERROR": raise Unauthorized(ticket.get("info")) else: hTTPException = HTTPException(ticket.get("info")) hTTPException.code = 402 raise hTTPException return ticket
def handle_500(e): app.logger.error(e) e = HTTPException(description='Internal server error') e.code = HTTPStatus.INTERNAL_SERVER_ERROR return response_error(e)
def claims_verification_failed_loader(): e = HTTPException(description='User claims verification failed') e.code = HTTPStatus.UNAUTHORIZED return response_error(e)
def expired_token_loader(expired_token): e = HTTPException(description='Token has expired') e.code = HTTPStatus.UNAUTHORIZED return response_error(e)
def _400(desc): exc = HTTPException() exc.code = 400 exc.description = desc return error_handling(exc)
def invalid_token_loader(message): e = HTTPException(description=message) e.code = HTTPStatus.BAD_REQUEST return response_error(e)