From 811255ba0b6f71868ac524ea54d360d88db37ef0 Mon Sep 17 00:00:00 2001 From: Aidaho Date: Wed, 19 Jun 2024 20:52:24 +0300 Subject: [PATCH] v7.3.1.0: Improve error handling and streamline data formatting This update reviews and adjusts multiple code segments across the project. The improvements are mainly focused on error handling with more informative exceptions and error messages. Additionally, data formatting and retrieval have been streamlined, mainly regarding JSON data preparation and use in several functions, which should expedite the data processing and enhance the code maintainability. Minor changes were also done on the front-end logic for error handling and improved user interaction. --- api/api_funct.py | 23 ++++++------ app/modules/config/config.py | 4 +-- app/modules/db/user.py | 12 +++---- app/modules/roxywi/common.py | 19 +++------- app/modules/roxywi/user.py | 35 ++++++++---------- app/modules/tools/alerting.py | 31 ++++++++-------- app/routes/channel/routes.py | 27 +++++++------- app/routes/portscanner/routes.py | 23 ++++++------ app/routes/server/routes.py | 22 ++++++------ app/routes/udp/routes.py | 8 ++--- app/routes/user/routes.py | 31 +++++++++++----- app/routes/waf/routes.py | 12 +++---- app/static/js/admin/user.js | 55 ++++++++++++++-------------- app/static/js/channel.js | 19 +++------- app/static/js/nettools.js | 17 +++++---- app/static/js/script.js | 15 ++++---- app/templates/ajax/channels.html | 4 +-- app/templates/portscanner.html | 61 +++++++++++++++----------------- app/templates/sections.html | 2 +- 19 files changed, 202 insertions(+), 218 deletions(-) diff --git a/api/api_funct.py b/api/api_funct.py index 118b3687..67e5b7fe 100644 --- a/api/api_funct.py +++ b/api/api_funct.py @@ -54,22 +54,21 @@ def get_token(): except Exception as e: return f'error getting group: {e}' try: - users = user_sql.select_users(user=login) + user = user_sql.get_user_id_by_username(login) password = roxy_wi_tools.Tools.get_hash(password_from_user) except Exception as e: return f'error one more: {e}' - for user in users: - if user.activeuser == 0: - return False - if login in user.username and password == user.password: - import uuid - user_token = str(uuid.uuid4()) - role_id = user_sql.get_role_id(user.user_id, group_id) - user_sql.write_api_token(user_token, group_id, role_id, user.username) - return user_token - else: - return False + if user.activeuser == 0: + return False + if login in user.username and password == user.password: + import uuid + user_token = str(uuid.uuid4()) + role_id = user_sql.get_role_id(user.user_id, group_id) + user_sql.write_api_token(user_token, group_id, role_id, user.username) + return user_token + else: + return False def check_login(required_service=0) -> bool: diff --git a/app/modules/config/config.py b/app/modules/config/config.py index 20642f5e..68bbbc1c 100644 --- a/app/modules/config/config.py +++ b/app/modules/config/config.py @@ -186,8 +186,8 @@ def _create_config_version(server_id: int, server_ip: str, service: str, config_ roxywi_common.logging('Roxy-WI server', f'error: Cannot create diff config version: {e}', roxywi=1) try: - user_id = roxywi_common.get_user_id(login=login) - config_sql.insert_config_version(server_id, user_id, service, cfg, config_path, diff) + user = user_sql.get_user_id_by_username(login=login) + config_sql.insert_config_version(server_id, user.user_id, service, cfg, config_path, diff) except Exception as e: roxywi_common.logging('Roxy-WI server', f'error: Cannot insert config version: {e}', roxywi=1) diff --git a/app/modules/db/user.py b/app/modules/db/user.py index f1bd7dad..0d68b7e6 100644 --- a/app/modules/db/user.py +++ b/app/modules/db/user.py @@ -100,8 +100,6 @@ def update_user_role(user_id: int, group_id: int, role_id: int) -> None: def select_users(**kwargs): if kwargs.get("user") is not None: query = User.select().where(User.username == kwargs.get("user")) - elif kwargs.get("id") is not None: - query = User.select().where(User.user_id == kwargs.get("id")) elif kwargs.get("group") is not None: get_date = roxy_wi_tools.GetDate(get_setting('time_zone')) cur_date = get_date.return_date('regular', timedelta_minutes_minus=15) @@ -225,13 +223,11 @@ def get_user_id_by_uuid(uuid): return user.user_id -def get_user_id_by_username(username: str): +def get_user_id_by_username(username: str) -> User: try: - query = User.get(User.username == username).user_id + return User.get(User.username == username) except Exception as e: out_error(e) - else: - return query def get_user_role_by_uuid(uuid, group_id): @@ -270,7 +266,7 @@ def write_user_uuid(login, user_uuid): cur_date = get_date.return_date('regular', timedelta=session_ttl) try: - UUID.insert(user_id=user_id, uuid=user_uuid, exp=cur_date).execute() + UUID.insert(user_id=user_id.user_id, uuid=user_uuid, exp=cur_date).execute() except Exception as e: out_error(e) @@ -405,7 +401,7 @@ def get_role_id(user_id: int, group_id: int) -> int: return int(role_id.user_role_id) -def get_user_id(user_id: int) -> int: +def get_user_id(user_id: int) -> User: try: return User.get(User.user_id == user_id) except Exception as e: diff --git a/app/modules/roxywi/common.py b/app/modules/roxywi/common.py index 4ecb0a74..0f0d08e6 100644 --- a/app/modules/roxywi/common.py +++ b/app/modules/roxywi/common.py @@ -56,18 +56,6 @@ def check_user_group_for_flask(**kwargs) -> bool: return False -def get_user_id(**kwargs): - if kwargs.get('login'): - return user_sql.get_user_id_by_username(kwargs.get('login')) - - user_uuid = request.cookies.get('uuid') - - if user_uuid is not None: - user_id = user_sql.get_user_id_by_uuid(user_uuid) - - return user_id - - def check_is_server_in_group(server_ip: str) -> bool: group_id = get_user_group(id=1) servers = server_sql.select_servers(server=server_ip) @@ -155,7 +143,8 @@ def logging(server_ip: str, action: str, **kwargs) -> None: def keep_action_history(service: str, action: str, server_ip: str, login: str, user_ip: str): if login != '': - user_id = user_sql.get_user_id_by_username(login) + user = user_sql.get_user_id_by_username(login) + user_id = user.user_id else: user_id = 0 if user_ip == '': @@ -319,6 +308,6 @@ def handle_exceptions(ex: Exception, server_ip: str, message: str, **kwargs: Any raise Exception(f'error: {message}: {ex}') -def handle_json_exceptions(ex: Exception, server_ip: str, message: str, **kwargs: Any) -> dict: - logging(server_ip, f'error: {message}: {ex}', roxywi=1, login=1, **kwargs) +def handle_json_exceptions(ex: Exception, message: str, server_ip='Roxy-WI server') -> dict: + logging(server_ip, f'error: {message}: {ex}', roxywi=1, login=1) return {'status': 'failed', 'error': f'{message}: {ex}'} diff --git a/app/modules/roxywi/user.py b/app/modules/roxywi/user.py index 728d5efc..77735034 100644 --- a/app/modules/roxywi/user.py +++ b/app/modules/roxywi/user.py @@ -39,13 +39,10 @@ def delete_user(user_id: int): count_super_admin_users = user_sql.get_super_admin_count() if count_super_admin_users < 2: raise Exception('error: you cannot delete a last user with superAdmin role') - user = user_sql.select_users(id=user_id) - username = '' - for u in user: - username = u.username + user = user_sql.get_user_id(user_id) if user_sql.delete_user(user_id): user_sql.delete_user_groups(user_id) - roxywi_common.logging(username, ' has been deleted user ', roxywi=1, login=1) + roxywi_common.logging(user.username, 'has been deleted user', roxywi=1, login=1) def update_user(email, new_user, user_id, enabled, group_id, role_id): @@ -57,19 +54,12 @@ def update_user(email, new_user, user_id, enabled, group_id, role_id): roxywi_common.logging(new_user, ' has been updated user ', roxywi=1, login=1) -def update_user_password(password, uuid, user_id_from_get): - username = '' - +def update_user_password(password: str, uuid: str, user_id: int): if uuid: user_id = user_sql.get_user_id_by_uuid(uuid) - else: - user_id = user_id_from_get - user = user_sql.select_users(id=user_id) - for u in user: - username = u.username + user = user_sql.get_user_id(user_id) user_sql.update_user_password(password, user_id) - roxywi_common.logging(f'user {username}', ' has changed password ', roxywi=1, login=1) - return 'ok' + roxywi_common.logging(f'user {user.username}', 'has changed password', roxywi=1, login=1) def get_user_services(user_id: int) -> str: @@ -162,22 +152,27 @@ def get_ldap_email(username) -> str: ldap_proto = 'ldap' if ldap_type == "0" else 'ldaps' - ldap_bind = ldap.initialize('{}://{}:{}/'.format(ldap_proto, server, port)) + try: + ldap_bind = ldap.initialize(f'{ldap_proto}://{server}:{port}/') + except Exception as e: + raise Exception(f'Cannot initialize connect to LDAP: {e}') try: ldap_bind.protocol_version = ldap.VERSION3 ldap_bind.set_option(ldap.OPT_REFERRALS, 0) - bind = ldap_bind.simple_bind_s(user, password) + _ = ldap_bind.simple_bind_s(user, password) - criteria = "(&(objectClass=" + ldap_class_search + ")(" + ldap_user_attribute + "=" + username + "))" + criteria = f"(&(objectClass={ldap_class_search})({ldap_user_attribute}={username}))" attributes = [ldap_search_field] result = ldap_bind.search_s(ldap_base, ldap.SCOPE_SUBTREE, criteria, attributes) results = [entry for dn, entry in result if isinstance(entry, dict)] try: - return '["' + results[0][ldap_search_field][0].decode("utf-8") + '","' + domain + '"]' + return f'["' + results[0][ldap_search_field][0].decode("utf-8") + '","' + domain + '"]' except Exception: - return 'error: user not found' + raise Exception('user not found') + except Exception as e: + raise Exception(e) finally: ldap_bind.unbind() diff --git a/app/modules/tools/alerting.py b/app/modules/tools/alerting.py index 6fa60ab9..ca544ccf 100644 --- a/app/modules/tools/alerting.py +++ b/app/modules/tools/alerting.py @@ -31,15 +31,18 @@ def send_message_to_rabbit(message: str, **kwargs) -> None: rabbit_queue = sql.get_setting('rabbitmq_queue') credentials = pika.PlainCredentials(rabbit_user, rabbit_password) - parameters = pika.ConnectionParameters( - rabbit_host, - rabbit_port, - rabbit_vhost, - credentials - ) + try: + parameters = pika.ConnectionParameters( + rabbit_host, + rabbit_port, + rabbit_vhost, + credentials + ) + connection = pika.BlockingConnection(parameters) + channel = connection.channel() + except Exception as e: + raise Exception(f'RabbitMQ connection error {e}') - connection = pika.BlockingConnection(parameters) - channel = connection.channel() channel.queue_declare(queue=rabbit_queue) channel.basic_publish(exchange='', routing_key=rabbit_queue, body=message) @@ -337,29 +340,27 @@ def check_rabbit_alert() -> None: json_for_sending = {"user_group": user_group_id, "message": 'info: Test message'} send_message_to_rabbit(json.dumps(json_for_sending)) except Exception as e: - raise Exception(e) + raise Exception(f'Cannot send message {e}') -def check_email_alert() -> str: +def check_email_alert() -> None: subject = 'test message' message = 'Test message from Roxy-WI' try: user_uuid = request.cookies.get('uuid') except Exception as e: - return f'error: Cannot send a message {e}' + raise Exception(f'Cannot send a message {e}') try: user_email = user_sql.select_user_email_by_uuid(user_uuid) except Exception as e: - return f'error: Cannot get a user email: {e}' + raise Exception(f'Cannot get a user email: {e}') try: send_email(user_email, subject, message) except Exception as e: - return f'error: Cannot send a message {e}' - - return 'ok' + raise Exception('Cannot send a message {e}') def add_telegram_channel(token: str, channel: str, group: str) -> str: diff --git a/app/routes/channel/routes.py b/app/routes/channel/routes.py index a8698c56..b8900815 100644 --- a/app/routes/channel/routes.py +++ b/app/routes/channel/routes.py @@ -40,21 +40,22 @@ def check_receiver(channel_id, receiver_name): alerting.check_receiver(channel_id, receiver_name) return jsonify({'status': 'success'}) except Exception as e: - roxywi_common.handle_json_exceptions(e, 'Roxy-WI', f'Cannot send message via {receiver_name}') + return roxywi_common.handle_json_exceptions(e, f'Cannot send message via {receiver_name}') -@bp.route('/check/rabbit') -def check_rabbit(): +@bp.post('/check') +def check_sender(): + json_data = request.get_json() + sender = json_data.get('sender') + send_function = { + 'email': alerting.check_email_alert, + 'web': alerting.check_rabbit_alert + } try: - alerting.check_rabbit_alert() + send_function[sender]() return jsonify({'status': 'success'}) except Exception as e: - roxywi_common.handle_json_exceptions(e, 'Roxy-WI', 'Cannot send message via Web panel') - - -@bp.route('/check/email') -def check_email(): - return alerting.check_email_alert() + return roxywi_common.handle_json_exceptions(e, f'Cannot send message via {sender.title()}') @bp.route('/receiver/', methods=['PUT', 'POST', 'DELETE']) @@ -70,7 +71,7 @@ def receiver(receiver_name): data = alerting.add_receiver_channel(receiver_name, token, channel, group) return jsonify({'status': 'updated', 'data': data}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI', f'Cannot create {receiver_name} channel') + return roxywi_common.handle_json_exceptions(e, f'Cannot create {receiver_name} channel') elif request.method == 'PUT': token = common.checkAjaxInput(json_data['receiver_token']) channel = common.checkAjaxInput(json_data['channel']) @@ -81,11 +82,11 @@ def receiver(receiver_name): alerting.update_receiver_channel(receiver_name, token, channel, group, user_id) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI', f'Cannot update {receiver_name} channel') + return roxywi_common.handle_json_exceptions(e, f'Cannot update {receiver_name} channel') elif request.method == 'DELETE': channel_id = int(json_data['channel_id']) try: alerting.delete_receiver_channel(channel_id, receiver_name) return jsonify({'status': 'deleted'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI', f'Cannot delete {receiver_name} channel') + return roxywi_common.handle_json_exceptions(e, f'Cannot delete {receiver_name} channel') diff --git a/app/routes/portscanner/routes.py b/app/routes/portscanner/routes.py index bedbf88a..7af65246 100644 --- a/app/routes/portscanner/routes.py +++ b/app/routes/portscanner/routes.py @@ -1,4 +1,4 @@ -from flask import render_template, request, g +from flask import render_template, request, g, jsonify from flask_login import login_required from app.routes.portscanner import bp @@ -78,17 +78,13 @@ def change_settings_portscanner(): return 'ok' -@bp.route('/scan/', defaults={'server_ip': None}) -@bp.route('/scan/', defaults={'server_id': None}) -def scan_port(server_id, server_ip): - if server_ip: - ip = server_ip +@bp.post('/scan') +def scan_port(): + json_data = request.get_json() + if 'id' in json_data: + ip = server_sql.select_server_ip_by_id(json_data['id']) else: - server = server_sql.select_servers(id=server_id) - ip = '' - - for s in server: - ip = s[2] + ip = json_data['ip'] cmd = f"sudo nmap -sS {ip} |grep -E '^[[:digit:]]'|sed 's/ */ /g'" cmd1 = f"sudo nmap -sS {ip} |head -5|tail -2" @@ -97,7 +93,8 @@ def scan_port(server_id, server_ip): stdout1, stderr1 = server_mod.subprocess_execute(cmd1) if stderr != '': - return f'error: {stderr}' + return jsonify({'error': stderr}) else: lang = roxywi_common.get_user_lang_for_flask() - return render_template('ajax/scan_ports.html', ports=stdout, info=stdout1, lang=lang) + temp = render_template('ajax/scan_ports.html', ports=stdout, info=stdout1, lang=lang) + return jsonify({'status': 'success', 'data': temp}) diff --git a/app/routes/server/routes.py b/app/routes/server/routes.py index 5769c1e4..fa885447 100644 --- a/app/routes/server/routes.py +++ b/app/routes/server/routes.py @@ -102,7 +102,7 @@ def create_server(): try: last_id = server_mod.create_server(hostname, ip, group, type_ip, enable, master, cred, port, desc, haproxy, nginx, apache, firewall) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot create server') + return roxywi_common.handle_json_exceptions(e, 'Cannot create server') try: user_subscription = roxywi_common.return_user_status() @@ -157,7 +157,7 @@ def create_server(): try: server_sql.update_server(hostname, group, type_ip, enable, master, serv_id, cred, port, desc, firewall, protected) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot update server') + return roxywi_common.handle_json_exceptions(e, 'Cannot update server') server_ip = server_sql.select_server_ip_by_id(serv_id) roxywi_common.logging(server_ip, f'The server {hostname} has been update', roxywi=1, login=1, keep_history=1, service='server') @@ -168,7 +168,7 @@ def create_server(): server_mod.delete_server(server_id) return jsonify({'status': 'deleted'}) except Exception as e: - roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot delete the server') + return roxywi_common.handle_json_exceptions(e, 'Cannot delete the server') elif request.method == 'PATCH': hostname = common.checkAjaxInput(json_data['name']) ip = common.is_ip_or_dns(json_data['ip']) @@ -177,7 +177,7 @@ def create_server(): server_mod.update_server_after_creating(hostname, ip, scan_server) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot scan the server') + return roxywi_common.handle_json_exceptions(e, 'Cannot scan the server') @bp.route('/group', methods=['POST', 'PUT', 'DELETE']) @@ -198,7 +198,7 @@ def create_group(): 'data': render_template('ajax/new_group.html', groups=group_sql.select_groups(group=name))} ) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot create a new group') + return roxywi_common.handle_json_exceptions(e, 'Cannot create a new group') elif request.method == 'PUT': name = json_data.get('name') desc = json_data.get('desc') @@ -207,14 +207,14 @@ def create_group(): group_mod.update_group(group_id, name, desc) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', f'Cannot update group {name}') + return roxywi_common.handle_json_exceptions(e, f'Cannot update group {name}') elif request.method == 'DELETE': group_id = json_data.get('group_id') try: group_mod.delete_group(group_id) return jsonify({'status': 'deleted'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', f'Cannot delete {group_id}') + return roxywi_common.handle_json_exceptions(e, f'Cannot delete {group_id}') @bp.route('/ssh', methods=['POST', 'PUT', 'DELETE', 'PATCH']) @@ -227,20 +227,20 @@ def create_ssh(): data = ssh_mod.create_ssh_cred(json_data) return jsonify({'status': 'created', 'id': data['id'], 'data': data['template']}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot create SSH') + return roxywi_common.handle_json_exceptions(e, 'Cannot create SSH') elif request.method == 'PUT': try: ssh_mod.update_ssh_key(json_data) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot update SSH') + return roxywi_common.handle_json_exceptions(e, 'Cannot update SSH') elif request.method == 'DELETE': ssh_id = int(json_data.get('id')) try: ssh_mod.delete_ssh_key(ssh_id) return jsonify({'status': 'deleted'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot delete SSH') + return roxywi_common.handle_json_exceptions(e, 'Cannot delete SSH') elif request.method == 'PATCH': user_group = roxywi_common.get_user_group() name = common.checkAjaxInput(json_data['name']) @@ -251,7 +251,7 @@ def create_ssh(): saved_path = ssh_mod.upload_ssh_key(name, user_group, key, passphrase) return jsonify({'status': 'uploaded', 'message': saved_path}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot upload ssh') + return roxywi_common.handle_json_exceptions(e, 'Cannot upload ssh') @bp.app_template_filter('string_to_dict') diff --git a/app/routes/udp/routes.py b/app/routes/udp/routes.py index 01bfc31d..3d3651ce 100644 --- a/app/routes/udp/routes.py +++ b/app/routes/udp/routes.py @@ -44,7 +44,7 @@ def listener_funct(service): roxywi_common.logging(listener_id, f'UDP listener {listener_name} has been created', roxywi=1, keep_history=1, login=1, service='UDP listener') return jsonify({'status': 'created', 'listener_id': listener_id}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server','Cannot create UDP listener') + return roxywi_common.handle_json_exceptions(e,'Cannot create UDP listener') elif request.method == 'PUT': json_data = request.get_json() json_data['group_id'] = g.user_params['group_id'] @@ -64,12 +64,12 @@ def listener_funct(service): service_mod.run_ansible(inv, server_ips, 'udp'), 201 roxywi_common.logging(listener_id, f'UDP listener has been deleted {listener_id}', roxywi=1, keep_history=1, login=1, service='UDP listener') except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server',f'Cannot create inventory for UDP listener deleting {listener_id}') + return roxywi_common.handle_json_exceptions(e,f'Cannot create inventory for UDP listener deleting {listener_id}') try: udp_sql.delete_listener(listener_id) return jsonify({'status': 'deleted'}), 201 except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server',f'Cannot delete UDP listener {listener_id}') + return roxywi_common.handle_json_exceptions(e,f'Cannot delete UDP listener {listener_id}') @bp.get('//listener/') @@ -109,4 +109,4 @@ def action_with_listener(service, listener_id, action): roxywi_common.logging(listener_id, f'UDP listener {listener_id} has been {action}ed', roxywi=1, keep_history=1, login=1, service='UDP listener') return jsonify({'status': 'done'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server',f'Cannot {action} listener') + return roxywi_common.handle_json_exceptions(e,f'Cannot {action} listener') diff --git a/app/routes/user/routes.py b/app/routes/user/routes.py index 9f3951e2..f361d4ad 100644 --- a/app/routes/user/routes.py +++ b/app/routes/user/routes.py @@ -43,7 +43,7 @@ def create_user(): try: user_id = roxywi_user.create_user(new_user, email, password, role, enabled, group_id) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot create a new user') + return roxywi_common.handle_json_exceptions(e, 'Cannot create a new user') else: return jsonify({'status': 'created', 'id': user_id, 'data': render_template( 'ajax/new_user.html', users=user_sql.select_users(user=new_user), groups=group_sql.select_groups(), @@ -58,7 +58,7 @@ def create_user(): try: user_sql.update_user_from_admin_area(user_name, email, user_id, enabled) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot update user') + return roxywi_common.handle_json_exceptions(e, 'Cannot update user') roxywi_common.logging(user_name, ' has been updated user ', roxywi=1, login=1) return jsonify({'status': 'updated'}) elif request.method == 'DELETE': @@ -68,7 +68,7 @@ def create_user(): roxywi_user.delete_user(user_id) return jsonify({'status': 'deleted'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', f'Cannot delete the user {user_id}') + return roxywi_common.handle_json_exceptions(e, f'Cannot delete the user {user_id}') else: abort(405) @@ -77,16 +77,29 @@ def create_user(): def get_ldap_email(username): roxywi_auth.page_for_admin(level=2) - return roxywi_user.get_ldap_email(username) + try: + user = roxywi_user.get_ldap_email(username) + return jsonify({'status': 'ldap', 'user': user}) + except Exception as e: + return roxywi_common.handle_json_exceptions(e, 'Cannot get LDAP email') @bp.post('/password') def update_password(): - password = request.form.get('updatepassowrd') - uuid = request.form.get('uuid') - user_id_from_get = request.form.get('id') + json_data = request.get_json() + password = json_data['password'] + uuid = '' + user_id = '' + if 'uuid' in json_data: + uuid = common.checkAjaxInput(json_data['uuid']) + else: + user_id = int(json_data['id']) - return roxywi_user.update_user_password(password, uuid, user_id_from_get) + try: + roxywi_user.update_user_password(password, uuid, user_id) + return jsonify({'status': 'updated'}) + except Exception as e: + return roxywi_common.handle_json_exceptions(e, 'Cannot update password') @bp.route('/services/', methods=['GET', 'POST']) @@ -101,7 +114,7 @@ def show_user_services(user_id): roxywi_user.change_user_services(user, user_id, user_services) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, 'Roxy-WI server', 'Cannot change user services') + return roxywi_common.handle_json_exceptions(e, 'Cannot change user services') @bp.route('/group', methods=['GET', 'PUT']) diff --git a/app/routes/waf/routes.py b/app/routes/waf/routes.py index 60d7caad..50883185 100644 --- a/app/routes/waf/routes.py +++ b/app/routes/waf/routes.py @@ -177,7 +177,7 @@ def enable_rule(server_ip, rule_id, enable): roxy_waf.switch_waf_rule(server_ip, enable, rule_id) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, server_ip, f'Cannot enable WAF rule {rule_id} on server {server_ip}') + return roxywi_common.handle_json_exceptions(e, f'Cannot enable WAF rule {rule_id}', server_ip) @bp.route('///rule/create', methods=['POST']) @@ -185,19 +185,19 @@ def create_rule(service, server_ip): server_ip = common.is_ip_or_dns(server_ip) json_data = request.get_json() if service not in ('haproxy', 'nginx'): - return roxywi_common.handle_json_exceptions('Wrong service', server_ip, '') + return roxywi_common.handle_json_exceptions('Wrong service', '', server_ip) try: last_id = roxy_waf.create_waf_rule(server_ip, service, json_data) return jsonify({'status': 'created', 'id': last_id}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, server_ip, 'Cannot create WAF rule') + return roxywi_common.handle_json_exceptions(e, 'Cannot create WAF rule', server_ip,) @bp.route('//mode//') def change_waf_mode(service, server_name, waf_mode): if service not in ('haproxy', 'nginx'): - return roxywi_common.handle_json_exceptions('Wrong service', server_name, '') + return roxywi_common.handle_json_exceptions('Wrong service', '', server_name) server_name = common.checkAjaxInput(server_name) waf_mode = common.checkAjaxInput(waf_mode) @@ -206,7 +206,7 @@ def change_waf_mode(service, server_name, waf_mode): roxy_waf.change_waf_mode(waf_mode, server_name, service) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, server_name, 'Cannot change WAF mode') + return roxywi_common.handle_json_exceptions(e, 'Cannot change WAF mode', server_name) @bp.route('/overview//') @@ -228,4 +228,4 @@ def enable_metric(enable, server_name): waf_sql.update_waf_metrics_enable(server_name, enable) return jsonify({'status': 'updated'}) except Exception as e: - return roxywi_common.handle_json_exceptions(e, server_name, 'Cannot enable WAF metrics') + return roxywi_common.handle_json_exceptions(e, 'Cannot enable WAF metrics', server_name) diff --git a/app/static/js/admin/user.js b/app/static/js/admin/user.js index 238ad066..0e367ea8 100644 --- a/app/static/js/admin/user.js +++ b/app/static/js/admin/user.js @@ -1,11 +1,11 @@ var cur_url = window.location.href.split('/app/').pop(); cur_url = cur_url.split('/'); $( function() { - $('#add-user-button').click(function() { + $('#add-user-button').click(function () { addUserDialog.dialog('open'); }); - let user_tabel_title = $( "#user-add-table-overview" ).attr('title'); - let addUserDialog = $( "#user-add-table" ).dialog({ + let user_tabel_title = $("#user-add-table-overview").attr('title'); + let addUserDialog = $("#user-add-table").dialog({ autoOpen: false, resizable: false, height: "auto", @@ -33,15 +33,15 @@ $( function() { } }] }); - $( "#ajax-users input" ).change(function() { + $("#ajax-users input").change(function () { let id = $(this).attr('id').split('-'); updateUser(id[1]) }); - $( "#ajax-users select" ).on('selectmenuchange',function() { + $("#ajax-users select").on('selectmenuchange', function () { let id = $(this).attr('id').split('-'); updateUser(id[1]) }); - $('#search_ldap_user').click(function() { + $('#search_ldap_user').click(function () { toastr.clear(); let username_div = $('#new-username') let valid = true; @@ -52,13 +52,12 @@ $( function() { if (valid) { $.ajax({ url: "/app/user/ldap/" + user, + contentType: "application/json; charset=utf-8", success: function (data) { - data = data.replace(/\s+/g, ' '); - if (data.indexOf('error:') != '-1') { - toastr.error(data); + if (data.status === 'failed') { + toastr.error(data.error); $('#new-email').val(''); username_div.attr('readonly', false); - username_div.val(''); } else { let json = $.parseJSON(data); toastr.clear(); @@ -76,22 +75,25 @@ $( function() { }); } ); function addUser(dialog_id) { - let valid = true; toastr.clear(); - let allFields = $([]).add($('#new-username')).add($('#new-password')).add($('#new-email')) + let valid = true; + let new_username_div = $('#new-username'); + let password_div = $('#new-password'); + let email_div = $('#new-email'); + let allFields = $([]).add(new_username_div).add(password_div).add(email_div) allFields.removeClass("ui-state-error"); - valid = valid && checkLength($('#new-username'), "user name", 1); - valid = valid && checkLength($('#new-password'), "password", 1); - valid = valid && checkLength($('#new-email'), "Email", 1); + valid = valid && checkLength(new_username_div, "user name", 1); + valid = valid && checkLength(password_div, "password", 1); + valid = valid && checkLength(email_div, "Email", 1); let enabled = 0; if ($('#activeuser').is(':checked')) { enabled = '1'; } if (valid) { let jsonData = { - "username": $('#new-username').val(), - "password": $('#new-password').val(), - "email": $('#new-email').val(), + "username": new_username_div.val(), + "password": password_div.val(), + "email": email_div.val(), "role": $('#new-role').val(), "enabled": enabled, "user_group": $('#new-group').val(), @@ -231,17 +233,18 @@ function changeUserPassword(id, d) { } else { $('#missmatchpass').hide(); toastr.clear(); + let jsonData = { + "password": pass, + "id": id + } $.ajax({ url: "/app/user/password", - data: { - updatepassowrd: pass, - id: id - }, + data: JSON.stringify(jsonData), + contentType: "application/json; charset=utf-8", type: "POST", success: function (data) { - data = data.replace(/\s+/g, ' '); - if (data.indexOf('error:') != '-1') { - toastr.error(data); + if (data.status === 'failed') { + toastr.error(data.error); } else { toastr.clear(); $("#user-" + id).addClass("update", 1000); @@ -310,7 +313,7 @@ function changeUserServices(user_id) { type: "POST", success: function( data ) { if (data.status === 'failed') { - toastr.error(data); + toastr.error(data.error); } else { $("#user-" + user_id).addClass("update", 1000); setTimeout(function () { diff --git a/app/static/js/channel.js b/app/static/js/channel.js index 17dc8063..0ff70db6 100644 --- a/app/static/js/channel.js +++ b/app/static/js/channel.js @@ -292,9 +292,11 @@ function removeReceiver(receiver_name, receiver_id) { } }); } -function checkWebPanel() { +function sendCheckMessage(sender) { $.ajax({ - url: "/app/channel/check/rabbit", + url: "/app/channel/check", + data: JSON.stringify({'sender': sender}), + type: "POST", contentType: "application/json; charset=utf-8", success: function (data) { if (data.status === 'failed') { @@ -305,16 +307,3 @@ function checkWebPanel() { } }); } -function checkEmail() { - $.ajax({ - url: "/app/channel/check/email", - success: function (data) { - data = data.replace(/\s+/g, ' '); - if (data.indexOf('error:') != '-1' || data.indexOf('error_code') != '-1') { - toastr.error(data); - } else { - toastr.success('Test message has been sent'); - } - } - }); -} diff --git a/app/static/js/nettools.js b/app/static/js/nettools.js index 7691edc7..7a8e5f78 100644 --- a/app/static/js/nettools.js +++ b/app/static/js/nettools.js @@ -109,26 +109,29 @@ $( function() { event.preventDefault(); }); $("#nettools_portscanner_form").on("click", ":submit", function (e) { + let port_server = $('#nettools_portscanner_server').val(); $('#ajax-nettools').html(''); - if ($('#nettools_portscanner_server').val() == '') { + if (port_server == '') { toastr.warning('Enter an address'); return false; } $.ajax({ - url: "/app/portscanner/scan/" + $('#nettools_portscanner_server').val(), + url: "/app/portscanner/scan", + data: JSON.stringify({'ip': port_server}), + type: "POST", + contentType: "application/json; charset=utf-8", success: function (data) { - data = data.replace(/\s+/g, ' '); - if (data.indexOf('danger') != '-1' || data.indexOf('unique') != '-1' || data.indexOf('error:') != '-1') { - toastr.error(data); + if (data.status === 'failed') { + toastr.error(data.error); } else { toastr.clear(); - $("#show_scans_ports_body").html(data); + $("#show_scans_ports_body").html(data.data); $("#show_scans_ports").dialog({ resizable: false, height: "auto", width: 360, modal: true, - title: "{{lang.words.opened|title()}} {{lang.words.ports}}", + title: "Opened ports", buttons: [{ text: close_word, click: function () { diff --git a/app/static/js/script.js b/app/static/js/script.js index 7af4cd23..fc35f294 100644 --- a/app/static/js/script.js +++ b/app/static/js/script.js @@ -1328,17 +1328,18 @@ function changeUserPasswordItOwn(d) { } else { $('#missmatchpass').hide(); toastr.clear(); + let jsonData = { + "password": pass, + "uuid": Cookies.get('uuid') + } $.ajax({ url: "/app/user/password", - data: { - updatepassowrd: pass, - uuid: Cookies.get('uuid'), - }, + data: JSON.stringify(jsonData), + contentType: "application/json; charset=utf-8", type: "POST", success: function (data) { - data = data.replace(/\s+/g, ' '); - if (data.indexOf('error:') != '-1') { - toastr.error(data); + if (data.status === 'failed') { + toastr.error(data.error); } else { toastr.clear(); d.dialog("close"); diff --git a/app/templates/ajax/channels.html b/app/templates/ajax/channels.html index 13962fbb..66b0e06b 100644 --- a/app/templates/ajax/channels.html +++ b/app/templates/ajax/channels.html @@ -219,10 +219,10 @@ - + - + diff --git a/app/templates/portscanner.html b/app/templates/portscanner.html index d8bfc81d..cf8c1cb2 100644 --- a/app/templates/portscanner.html +++ b/app/templates/portscanner.html @@ -148,36 +148,34 @@