Browse Source

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
commit
41764ad4ca
  1. 11
      app/modules/db/checker.py
  2. 2
      app/modules/roxywi/class_models.py
  3. 3
      app/modules/service/installation.py
  4. 34
      app/static/js/script.js
  5. 5
      app/static/js/waf.js
  6. 10
      app/views/admin/views.py
  7. 2
      app/views/service/views.py
  8. 101
      app/views/tools/views.py

11
app/modules/db/checker.py

@ -37,6 +37,17 @@ def insert_new_checker_setting_for_server(server_ip: str) -> None:
).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(
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

2
app/modules/roxywi/class_models.py

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

3
app/modules/service/installation.py

@ -318,11 +318,10 @@ def service_actions_after_install(server_ips: str, service: str, json_data) -> N
update_functions[service](server_ip)
except Exception as e:
roxywi_common.handle_exceptions(e, 'Roxy-WI server', f'Cannot activate {service} on server {server_ip}', roxywi=1)
if service != 'keepalived':
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, 'restart', '1')

34
app/static/js/script.js

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

5
app/static/js/waf.js

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

10
app/views/admin/views.py

@ -2,22 +2,16 @@ from typing import Optional
from flask.views import MethodView
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 flask_jwt_extended import jwt_required
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.server.ssh as ssh_mod
import app.modules.tools.smon as smon_mod
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 (
BaseResponse, IdResponse, IdDataResponse, ServerRequest, GroupQuery, SettingsRequest
BaseResponse, GroupQuery, SettingsRequest
)
from app.modules.common.common_classes import SupportClass

2
app/views/service/views.py

@ -151,7 +151,7 @@ class ServiceView(MethodView):
class ServiceActionView(MethodView):
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
def get(service: str, server_id: Union[int, str], action: str):

101
app/views/tools/views.py

@ -12,15 +12,17 @@ import app.modules.db.service as service_sql
import app.modules.db.checker as checker_sql
import app.modules.roxywi.common as roxywi_common
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.common.common_classes import SupportClass
class CheckerView(MethodView):
methods = ["GET", "POST"]
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.
---
@ -84,6 +86,11 @@ class CheckerView(MethodView):
"""
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:
@ -107,4 +114,92 @@ class CheckerView(MethodView):
@validate(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