v8.0: Refactor admin views and JS scripts

Simplified imports and cleaned up unused functionalities in `admin/views.py`. Switched `var` to `let` in `script.js` for better scope management. Adjusted `showOverviewWaf` function for consistency. Removed `check_services` decorator from `ServiceActionView`. Enhanced `Checker` class model and improved error handling in `CheckerView`. Added `update_checker_setting_for_server` method in `checker.py`.
pull/399/head
Aidaho 4 months ago
parent 075d2b935b
commit 41764ad4ca

@ -37,6 +37,17 @@ def insert_new_checker_setting_for_server(server_ip: str) -> None:
).on_conflict_ignore().execute() ).on_conflict_ignore().execute()
def update_checker_setting_for_server(service_id: int, server_id: int, **kwargs) -> None:
try:
query = (CheckerSetting.update(**kwargs).where(
(CheckerSetting.service_id == service_id) & (CheckerSetting.server_id == server_id)
))
print(query)
query.execute()
except Exception as e:
out_error(e)
def update_haproxy_checker_settings( def update_haproxy_checker_settings(
email: int, telegram_id: int, slack_id: int, pd_id: int, mm_id: int, service_alert: int, backend_alert: int, email: int, telegram_id: int, slack_id: int, pd_id: int, mm_id: int, service_alert: int, backend_alert: int,
maxconn_alert: int, setting_id: int maxconn_alert: int, setting_id: int

@ -216,11 +216,9 @@ class ServiceInstall(BaseModel):
class Checker(BaseModel): class Checker(BaseModel):
server_id: int
checker: Optional[bool] = 0 checker: Optional[bool] = 0
metrics: Optional[bool] = 0 metrics: Optional[bool] = 0
auto_start: Optional[bool] = 0 auto_start: Optional[bool] = 0
service: Optional[bool] = 1
telegram_id: Optional[int] = 0 telegram_id: Optional[int] = 0
slack_id: Optional[int] = 0 slack_id: Optional[int] = 0
pd_id: Optional[int] = 0 pd_id: Optional[int] = 0

@ -318,11 +318,10 @@ def service_actions_after_install(server_ips: str, service: str, json_data) -> N
update_functions[service](server_ip) update_functions[service](server_ip)
except Exception as e: except Exception as e:
roxywi_common.handle_exceptions(e, 'Roxy-WI server', f'Cannot activate {service} on server {server_ip}', roxywi=1) roxywi_common.handle_exceptions(e, 'Roxy-WI server', f'Cannot activate {service} on server {server_ip}', roxywi=1)
if service != 'keepalived': if service != 'keepalived':
is_docker = json_data['services'][service]['docker'] is_docker = json_data['services'][service]['docker']
if is_docker == '1' and service != 'keepalived': if is_docker and service != 'keepalived':
service_sql.insert_or_update_service_setting(server_id, service, 'dockerized', '1') service_sql.insert_or_update_service_setting(server_id, service, 'dockerized', '1')
service_sql.insert_or_update_service_setting(server_id, service, 'restart', '1') service_sql.insert_or_update_service_setting(server_id, service, 'restart', '1')

@ -1,6 +1,5 @@
var cur_url = window.location.href.split('/').pop(); var cur_url = window.location.href.split('/').pop();
cur_url = cur_url.split('/'); cur_url = cur_url.split('/');
var intervalId;
function validateEmail(email) { function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email); return re.test(email);
@ -174,11 +173,11 @@ function openSection() {
win.focus(); win.focus();
} }
function showLog() { function showLog() {
var waf = cur_url[2]; let waf = cur_url[0].split('?')[0];
var file = $('#log_files').val(); let file = $('#log_files').val();
var serv = $("#serv").val(); let serv = $("#serv").val();
if ((file === undefined || file === null) && (waf == '' || waf === undefined)) { if ((file === undefined || file === null) && (waf === '' || waf === undefined)) {
var file_from_get = findGetParameter('file'); let file_from_get = findGetParameter('file');
if (file_from_get === undefined || file_from_get === null) { if (file_from_get === undefined || file_from_get === null) {
toastr.warning('Select a log file first') toastr.warning('Select a log file first')
return false; return false;
@ -186,22 +185,21 @@ function showLog() {
file = file_from_get; file = file_from_get;
} }
} }
var rows = $('#rows').val(); let rows = $('#rows').val();
var grep = $('#grep').val(); let grep = $('#grep').val();
var exgrep = $('#exgrep').val(); let exgrep = $('#exgrep').val();
var hour = $('#time_range_out_hour').val(); let hour = $('#time_range_out_hour').val();
var minute = $('#time_range_out_minut').val(); let minute = $('#time_range_out_minut').val();
var hour1 = $('#time_range_out_hour1').val(); let hour1 = $('#time_range_out_hour1').val();
var minute1 = $('#time_range_out_minut1').val(); let minute1 = $('#time_range_out_minut1').val();
var service = $('#service').val(); let service = $('#service').val();
if (service == 'None') { let url = "/logs/" + service + "/" + serv + "/" + rows;
if (service === 'None') {
service = 'haproxy'; service = 'haproxy';
} }
if (waf) { if (waf) {
var url = "/logs/" + service + "/waf/" + serv + "/" + rows; url = "/logs/" + service + "/waf/" + serv + "/" + rows;
waf = 1; waf = 1;
} else {
var url = "/logs/" + service + "/" + serv + "/" + rows;
} }
$.ajax( { $.ajax( {
url: url, url: url,

@ -1,6 +1,6 @@
function showOverviewWaf(serv, hostname) { function showOverviewWaf(serv, hostname) {
let service = cur_url[0]; let service = cur_url[0];
if (service == 'haproxy') { if (service === 'haproxy') {
$.getScript('/static/js/chart.min-4.3.0.js'); $.getScript('/static/js/chart.min-4.3.0.js');
showWafMetrics(); showWafMetrics();
} }
@ -97,10 +97,11 @@ $( function() {
}); });
function waf_rules_en(id) { function waf_rules_en(id) {
let enable = 0; let enable = 0;
let cur_url = window.location.href.split('/');
let serv = cur_url[5];
if ($('#rule_id-' + id).is(':checked')) { if ($('#rule_id-' + id).is(':checked')) {
enable = '1'; enable = '1';
} }
let serv = cur_url[2];
$.ajax({ $.ajax({
url: "/waf/" + serv + "/rule/" + id + "/" + enable, url: "/waf/" + serv + "/rule/" + id + "/" + enable,
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",

@ -2,22 +2,16 @@ from typing import Optional
from flask.views import MethodView from flask.views import MethodView
from flask_pydantic import validate from flask_pydantic import validate
from flask import render_template, jsonify, request, g from flask import jsonify
from playhouse.shortcuts import model_to_dict from playhouse.shortcuts import model_to_dict
from flask_jwt_extended import jwt_required from flask_jwt_extended import jwt_required
import app.modules.db.sql as sql import app.modules.db.sql as sql
import app.modules.db.cred as cred_sql
import app.modules.db.group as group_sql
import app.modules.db.server as server_sql
import app.modules.roxywi.group as group_mod
import app.modules.roxywi.common as roxywi_common import app.modules.roxywi.common as roxywi_common
import app.modules.server.ssh as ssh_mod
import app.modules.tools.smon as smon_mod import app.modules.tools.smon as smon_mod
from app.middleware import get_user_params, page_for_admin, check_group from app.middleware import get_user_params, page_for_admin, check_group
from app.modules.roxywi.exception import RoxywiGroupMismatch, RoxywiResourceNotFound
from app.modules.roxywi.class_models import ( from app.modules.roxywi.class_models import (
BaseResponse, IdResponse, IdDataResponse, ServerRequest, GroupQuery, SettingsRequest BaseResponse, GroupQuery, SettingsRequest
) )
from app.modules.common.common_classes import SupportClass from app.modules.common.common_classes import SupportClass

@ -151,7 +151,7 @@ class ServiceView(MethodView):
class ServiceActionView(MethodView): class ServiceActionView(MethodView):
methods = ['GET'] methods = ['GET']
decorators = [jwt_required(), get_user_params(), check_services, page_for_admin(level=3), check_group()] decorators = [jwt_required(), get_user_params(), page_for_admin(level=3), check_group()]
@staticmethod @staticmethod
def get(service: str, server_id: Union[int, str], action: str): def get(service: str, server_id: Union[int, str], action: str):

@ -12,15 +12,17 @@ import app.modules.db.service as service_sql
import app.modules.db.checker as checker_sql import app.modules.db.checker as checker_sql
import app.modules.roxywi.common as roxywi_common import app.modules.roxywi.common as roxywi_common
from app.middleware import get_user_params, page_for_admin, check_group, check_services from app.middleware import get_user_params, page_for_admin, check_group, check_services
from app.modules.roxywi.class_models import Checker from app.modules.roxywi.class_models import Checker, BaseResponse
from app.modules.db.db_model import CheckerSetting from app.modules.db.db_model import CheckerSetting
from app.modules.common.common_classes import SupportClass
class CheckerView(MethodView): class CheckerView(MethodView):
methods = ["GET", "POST"] methods = ["GET", "POST"]
decorators = [jwt_required(), get_user_params(), check_services, page_for_admin(level=3), check_group()] decorators = [jwt_required(), get_user_params(), check_services, page_for_admin(level=3), check_group()]
def get(self, service: Literal['haproxy', 'nginx', 'apache', 'keepalived'], server_id: Union[int, str]): @staticmethod
def get(service: Literal['haproxy', 'nginx', 'apache', 'keepalived'], server_id: Union[int, str]):
""" """
Retrieves the status of specific checker services. Retrieves the status of specific checker services.
--- ---
@ -84,6 +86,11 @@ class CheckerView(MethodView):
""" """
service_id = service_sql.select_service_id_by_slug(service) service_id = service_sql.select_service_id_by_slug(service)
try:
server_id = SupportClass().return_server_ip_or_id(server_id)
except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, '')
try: try:
server = server_sql.get_server_by_id(server_id) server = server_sql.get_server_by_id(server_id)
except Exception as e: except Exception as e:
@ -107,4 +114,92 @@ class CheckerView(MethodView):
@validate(body=Checker) @validate(body=Checker)
def post(self, service: Literal['haproxy', 'nginx', 'apache', 'keepalived'], server_id: Union[int, str], body: Checker): def post(self, service: Literal['haproxy', 'nginx', 'apache', 'keepalived'], server_id: Union[int, str], body: Checker):
... """
Update the Tools settings of specific service.
---
tags:
- Service Tools
parameters:
- in: path
name: service
type: string
required: true
description: The type of service (haproxy, nginx, apache, keepalived)
- in: path
name: server_id
type: string
required: true
description: The ID or IP of the server
- in: body
required: true
name: body
description: The settings of the checker service
schema:
type: object
properties:
auto_start:
type: 'integer'
description: 'Sets if Auto start tools is enabled for this service'
backend_alert:
type: 'integer'
description: 'Sets the Alert status for backends. Only for HAProxy and Keepalived services'
checker:
type: 'integer'
description: 'Sets if Checker tools is enabled for this service'
email:
type: 'integer'
description: 'Sets the status flag for email notifications'
maxconn_alert:
type: 'integer'
description: 'Sets the Alert status for max connections. Only for HAProxy service'
metrics:
type: 'integer'
description: 'Sets if Metrics tools is enabled for this service'
mm_id:
type: 'integer'
description: 'Sets the Identifier for Mattermost notifications'
pd_id:
type: 'integer'
description: 'Sets the Identifier for PagerDuty notifications'
service_alert:
type: 'integer'
description: 'Sets the Alert status for services'
slack_id:
type: 'integer'
description: 'Sets the Identifier for Slack notifications'
telegram_id:
type: 'integer'
description: 'Sets the Identifier for Telegram notifications'
responses:
201:
description: Successful operation, settings updated
default:
description: Unexpected error
"""
service_id = service_sql.select_service_id_by_slug(service)
try:
server_id = SupportClass().return_server_ip_or_id(server_id)
except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, '')
try:
server = server_sql.get_server_by_id(server_id)
except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot find server')
try:
roxywi_common.is_user_has_access_to_group(g.user_params['user_id'], server.group_id)
except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, '')
kwargs = body.model_dump(mode='json', exclude={'metrics', 'auto_start', 'checker'})
try:
checker_sql.update_checker_setting_for_server(service_id, server_id, **kwargs)
except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot update Checker settings')
try:
service_sql.update_hapwi_server(server_id, body.checker, body.metrics, body.auto_start, service)
except Exception as e:
return roxywi_common.handler_exceptions_for_json_data(e, 'Cannot update Service settings')
return BaseResponse().model_dump(), 201

Loading…
Cancel
Save