From bb59eb8a5451097b131856433c0222ab94f5fe3a Mon Sep 17 00:00:00 2001 From: Alejandro Sirgo Rica Date: Thu, 4 Jul 2024 12:01:48 +0200 Subject: views: add auxiliar function is_valid_ip() Move ip validation logic to a separate function to make the code more expressive and reusable. --- ogcp/views.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/ogcp/views.py b/ogcp/views.py index 2dba569..097041f 100644 --- a/ogcp/views.py +++ b/ogcp/views.py @@ -116,6 +116,13 @@ def prettify_mac(mac): return mac return (':'.join(normalized_mac[i:i+2] for i in range(0, 12, 2))).lower() +def is_valid_ip(ip): + try: + ipaddress.ip_address(ip) + except: + return False + return True + def ogserver_down(view): flash(_('Cannot talk to ogserver. Is ogserver down?'), category='error') return redirect(url_for(view)) @@ -1310,9 +1317,7 @@ def action_client_update(): form = ClientDetailsForm(request.form) if request.method == 'POST': - try: - ipaddress.ip_address(form.ip.data) - except ValueError as e: + if not is_valid_ip(form.ip.data): flash(_('Invalid IP address'), category='error') return redirect(url_for("scopes")) @@ -1573,9 +1578,7 @@ def action_client_add(): flash(_('Invalid empty client name'), category='error') return redirect(url_for("scopes")) - try: - ipaddress.ip_address(form.ip.data) - except ValueError as e: + if not is_valid_ip(form.ip.data): flash(_('Invalid IP address'), category='error') return redirect(url_for("scopes")) @@ -1791,9 +1794,7 @@ def action_clients_import_post(): client_ip = client_values[2] - try: - ipaddress.ip_address(client_ip) - except ValueError as e: + if not is_valid_ip(client_ip): flash(_(f'Invalid IP address {client_ip}'), category='error') return redirect(url_for("scopes")) -- cgit v1.2.3-18-g5258