From 82ab7face2543145cfab2a3e9f6a5a367a8de9de Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Fri, 30 Sep 2022 03:10:37 +0200 Subject: [PATCH] A more robust logic to detect the webserver local bind address --- platypush/backend/http/app/utils.py | 91 +++++++++++++++++++---------- 1 file changed, 60 insertions(+), 31 deletions(-) diff --git a/platypush/backend/http/app/utils.py b/platypush/backend/http/app/utils.py index 17c2a49164..70113b4567 100644 --- a/platypush/backend/http/app/utils.py +++ b/platypush/backend/http/app/utils.py @@ -35,13 +35,15 @@ def logger(): 'format': '%(asctime)-15s|%(levelname)5s|%(name)s|%(message)s', } - level = (Config.get('backend.http') or {}).get('logging') or \ - (Config.get('logging') or {}).get('level') + level = (Config.get('backend.http') or {}).get('logging') or ( + Config.get('logging') or {} + ).get('level') filename = (Config.get('backend.http') or {}).get('filename') if level: - log_args['level'] = getattr(logging, level.upper()) \ - if isinstance(level, str) else level + log_args['level'] = ( + getattr(logging, level.upper()) if isinstance(level, str) else level + ) if filename: log_args['filename'] = filename @@ -65,6 +67,7 @@ def get_message_response(msg): # noinspection PyProtectedMember def get_http_port(): from platypush.backend.http import HttpBackend + http_conf = Config.get('backend.http') return http_conf.get('port', HttpBackend._DEFAULT_HTTP_PORT) @@ -72,6 +75,7 @@ def get_http_port(): # noinspection PyProtectedMember def get_websocket_port(): from platypush.backend.http import HttpBackend + http_conf = Config.get('backend.http') return http_conf.get('websocket_port', HttpBackend._DEFAULT_WEBSOCKET_PORT) @@ -89,17 +93,13 @@ def send_message(msg, wait_for_response=True): if isinstance(msg, Request) and wait_for_response: response = get_message_response(msg) - logger().debug('Processing response on the HTTP backend: {}'. - format(response)) + logger().debug('Processing response on the HTTP backend: {}'.format(response)) return response def send_request(action, wait_for_response=True, **kwargs): - msg = { - 'type': 'request', - 'action': action - } + msg = {'type': 'request', 'action': action} if kwargs: msg['args'] = kwargs @@ -113,8 +113,10 @@ def _authenticate_token(): if 'X-Token' in request.headers: user_token = request.headers['X-Token'] - elif 'Authorization' in request.headers and request.headers['Authorization'].startswith('Bearer '): - user_token = request.headers['Authorization'][len('Bearer '):] + elif 'Authorization' in request.headers and request.headers[ + 'Authorization' + ].startswith('Bearer '): + user_token = request.headers['Authorization'][7:] elif 'token' in request.args: user_token = request.args.get('token') else: @@ -176,7 +178,10 @@ def _authenticate_csrf_token(): if user is None: return False - return session.csrf_token is None or request.form.get('csrf_token') == session.csrf_token + return ( + session.csrf_token is None + or request.form.get('csrf_token') == session.csrf_token + ) def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=False): @@ -208,7 +213,9 @@ def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=Fals if session_auth_ok: return f(*args, **kwargs) - return redirect('/login?redirect=' + (redirect_page or request.url), 307) + return redirect( + '/login?redirect=' + (redirect_page or request.url), 307 + ) # CSRF token check if check_csrf_token: @@ -217,15 +224,22 @@ def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=Fals return abort(403, 'Invalid or missing csrf_token') if n_users == 0 and 'session' not in skip_methods: - return redirect('/register?redirect=' + (redirect_page or request.url), 307) + return redirect( + '/register?redirect=' + (redirect_page or request.url), 307 + ) - if ('http' not in skip_methods and http_auth_ok) or \ - ('token' not in skip_methods and token_auth_ok) or \ - ('session' not in skip_methods and session_auth_ok): + if ( + ('http' not in skip_methods and http_auth_ok) + or ('token' not in skip_methods and token_auth_ok) + or ('session' not in skip_methods and session_auth_ok) + ): return f(*args, **kwargs) - return Response('Authentication required', 401, - {'WWW-Authenticate': 'Basic realm="Login required"'}) + return Response( + 'Authentication required', + 401, + {'WWW-Authenticate': 'Basic realm="Login required"'}, + ) return wrapper @@ -233,42 +247,57 @@ def authenticate(redirect_page='', skip_auth_methods=None, check_csrf_token=Fals def get_routes(): - routes_dir = os.path.join( - os.path.dirname(os.path.abspath(__file__)), 'routes') + routes_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'routes') routes = [] base_module = '.'.join(__name__.split('.')[:-1]) - for path, dirs, files in os.walk(routes_dir): + for path, _, files in os.walk(routes_dir): for f in files: if f.endswith('.py'): mod_name = '.'.join( - (base_module + '.' + os.path.join(path, f).replace( - os.path.dirname(__file__), '')[1:].replace(os.sep, '.')).split('.') - [:(-2 if f == '__init__.py' else -1)]) + ( + base_module + + '.' + + os.path.join(path, f) + .replace(os.path.dirname(__file__), '')[1:] + .replace(os.sep, '.') + ).split('.')[: (-2 if f == '__init__.py' else -1)] + ) try: mod = importlib.import_module(mod_name) if hasattr(mod, '__routes__'): routes.extend(mod.__routes__) except Exception as e: - logger().warning('Could not import routes from {}/{}: {}: {}'. - format(path, f, type(e), str(e))) + logger().warning( + 'Could not import routes from {}/{}: {}: {}'.format( + path, f, type(e), str(e) + ) + ) return routes def get_local_base_url(): http_conf = Config.get('backend.http') or {} - return '{proto}://localhost:{port}'.format( + bind_address = http_conf.get('bind_address') + if not bind_address or bind_address == '0.0.0.0': + bind_address = 'localhost' + + return '{proto}://{host}:{port}'.format( proto=('https' if http_conf.get('ssl_cert') else 'http'), - port=get_http_port()) + host=bind_address, + port=get_http_port(), + ) def get_remote_base_url(): http_conf = Config.get('backend.http') or {} return '{proto}://{host}:{port}'.format( proto=('https' if http_conf.get('ssl_cert') else 'http'), - host=get_ip_or_hostname(), port=get_http_port()) + host=get_ip_or_hostname(), + port=get_http_port(), + ) # vim:sw=4:ts=4:et: