Browse Source

v6.2.3.0

Changelog: https://roxy-wi.org/changelog#6_2_3
pull/355/head
Pavel Loginov 2 years ago
parent
commit
82700a2ce3
  1. 54
      api/api_funct.py
  2. 14
      app/funct.py
  3. 11
      app/login.py
  4. 44
      app/modules/roxy_wi_tools.py
  5. 17
      app/sql.py

54
api/api_funct.py

@ -15,14 +15,14 @@ def get_token():
try:
user_status, user_plan = funct.return_user_status()
except Exception as e:
funct.logging('API', 'Cannot get a user plan: ' + str(e), haproxywi=1)
funct.logging('API', f'Cannot get a user plan: {e}', roxywi=1)
return False
if user_status == 0:
funct.logging('API', 'You are not subscribed. Please subscribe to have access to this feature.', haproxywi=1)
funct.logging('API', 'You are not subscribed. Please subscribe to have access to this feature.', roxywi=1)
return False
elif user_plan == 'user':
funct.logging('API', 'This feature is not available for your plan.', haproxywi=1)
funct.logging('API', 'This feature is not available for your plan.', roxywi=1)
return False
try:
@ -31,17 +31,17 @@ def get_token():
login = login_pass['login']
password_from_user = login_pass['password']
except Exception as e:
return 'error getting credentials: ' + str(e)
return f'error getting credentials: {e}'
try:
group_name = login_pass['group']
group_id = sql.get_group_id_by_name(group_name)
except Exception as e:
return 'error getting group: ' + str(e)
return f'error getting group: {e}'
try:
users = sql.select_users(user=login)
password = funct.get_hash(password_from_user)
password = roxy_wi_tools.Tools.get_hash(password_from_user)
except Exception as e:
return 'error one more: ' + str(e)
return f'error one more: {e}'
for user in users:
if user.activeuser == 0:
@ -59,14 +59,14 @@ def check_login(required_service=0) -> bool:
try:
user_status, user_plan = funct.return_user_status()
except Exception as e:
funct.logging('API', 'Cannot get a user plan: ' + str(e), haproxywi=1)
funct.logging('API', f'Cannot get a user plan: {e}', roxywi=1)
return False
if user_status == 0:
funct.logging('API', 'You are not subscribed. Please subscribe to have access to this feature.', haproxywi=1)
funct.logging('API', 'You are not subscribed. Please subscribe to have access to this feature.', roxywi=1)
return False
elif user_plan == 'user':
funct.logging('API', 'This feature is not available for your plan.', haproxywi=1)
funct.logging('API', 'This feature is not available for your plan.', roxywi=1)
return False
token = request.headers.get('token')
@ -349,25 +349,27 @@ def edit_section(server_id):
for s in servers:
ip = s[2]
cfg = '/tmp/' + ip + '.cfg'
cfg = f'/tmp/{ip}.cfg'
out = funct.get_config(ip, cfg)
start_line, end_line, config_read = funct.get_section_from_config(cfg, section_name)
returned_config = funct.rewrite_section(start_line, end_line, cfg, body)
time_zone = sql.get_setting('time_zone')
get_date = roxy_wi_tools.GetDate(time_zone)
cur_date = get_date.return_date('config')
try:
cfg_for_save = hap_configs_dir + ip + "-" + funct.get_data('config') + ".cfg"
cfg_for_save = f'{hap_configs_dir}{ip}-{cur_date}.cfg'
try:
with open(cfg, "w") as conf:
conf.write(returned_config)
return_mess = 'section has been updated'
os.system("/bin/cp %s %s" % (cfg, cfg_for_save))
os.system(f"/bin/cp {cfg} {cfg_for_save}")
out = funct.master_slave_upload_and_restart(ip, cfg, save, login=login)
funct.logging('localhost', " section " + section_name + " has been edited via API", login=login)
funct.logging('localhost', f" section {section_name} has been edited via API", login=login)
funct.logging(
ip, 'Section ' + section_name + ' has been edited via API', haproxywi=1,
ip, f'Section {section_name} has been edited via API', roxywi=1,
login=login, keep_history=1, service='haproxy'
)
@ -420,8 +422,11 @@ def upload_config(server_id, **kwargs):
for s in servers:
ip = s[2]
cfg = '/tmp/' + ip + '.cfg'
cfg_for_save = configs_dir + ip + "-" + funct.get_data('config') + ".cfg"
cfg = f'/tmp/{ip}.cfg'
time_zone = sql.get_setting('time_zone')
get_date = roxy_wi_tools.GetDate(time_zone)
cur_date = get_date.return_date('config')
cfg_for_save = f'{configs_dir}{ip}-{cur_date}.cfg'
try:
with open(cfg, "w") as conf:
@ -438,13 +443,13 @@ def upload_config(server_id, **kwargs):
funct.logging('localhost', " config has been uploaded via API", login=login)
funct.logging(
ip, 'Config has been uploaded via API', haproxywi=1, login=login, keep_history=1, service=service_name
ip, 'Config has been uploaded via API', roxywi=1, login=login, keep_history=1, service=service_name
)
if out:
return_mess = out
except IOError as e:
return_mess = "cannot upload config" + str(e)
return_mess = f"cannot upload config {e}"
data = {server_id: return_mess}
except Exception as e:
@ -461,6 +466,8 @@ def add_to_config(server_id):
hap_configs_dir = get_config_var.get_config_var('configs', 'haproxy_save_configs_dir')
token = request.headers.get('token')
login, group_id = sql.get_username_groupid_from_api_token(token)
time_zone = sql.get_setting('time_zone')
get_date = roxy_wi_tools.GetDate(time_zone)
if save == '':
save = 'save'
@ -472,15 +479,16 @@ def add_to_config(server_id):
for s in servers:
ip = s[2]
cfg = '/tmp/' + ip + '.cfg'
cfg_for_save = hap_configs_dir + ip + "-" + funct.get_data('config') + ".cfg"
cfg = f'/tmp/{ip}.cfg'
cur_date = get_date.return_date('config')
cfg_for_save = f'{hap_configs_dir}{ip}-{cur_date}.cfg'
out = funct.get_config(ip, cfg)
try:
with open(cfg, "a") as conf:
conf.write('\n' + body + '\n')
return_mess = 'section has been added to the config'
os.system("/bin/cp %s %s" % (cfg, cfg_for_save))
os.system(f"/bin/cp {cfg} {cfg_for_save}")
funct.logging('localhost', " section has been added via REST API", login=login)
out = funct.upload_and_restart(ip, cfg, just_save=save)

14
app/funct.py

@ -14,6 +14,7 @@ time_zone = sql.get_setting('time_zone')
get_date = roxy_wi_tools.GetDate(time_zone)
get_config_var = roxy_wi_tools.GetConfigVar()
def is_ip_or_dns(server_from_request: str) -> str:
ip_regex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
dns_regex = "^(?!-)[A-Za-z0-9-]+([\\-\\.]{1}[a-z0-9]+)*\\.[A-Za-z]{2,6}$"
@ -112,7 +113,7 @@ def logging(server_ip: str, action: str, **kwargs) -> None:
except Exception:
pass
if kwargs.get('haproxywi') == 1 or kwargs.get('roxywi') == 1:
if kwargs.get('roxywi') == 1:
if kwargs.get('login'):
mess = f"{cur_date_in_log} from {ip} user: {login}, group: {user_group}, {action} on: {server_ip}\n"
if kwargs.get('keep_history'):
@ -1425,20 +1426,11 @@ def versions():
except Exception as e:
new_ver = "Cannot get a new version"
new_ver_without_dots = 0
logging('Roxy-WI server', ' ' + str(e), roxywi=1)
logging('Roxy-WI server', f' {e}', roxywi=1)
return current_ver, new_ver, current_ver_without_dots, new_ver_without_dots
def get_hash(value):
if value is None:
return value
import hashlib
h = hashlib.md5(value.encode('utf-8'))
p = h.hexdigest()
return p
def get_users_params(**kwargs):
cookie = http.cookies.SimpleCookie(os.environ.get("HTTP_COOKIE"))

11
app/login.py

@ -10,6 +10,7 @@ import distro
import sql
import funct
import modules.roxy_wi_tools as roxy_wi_tools
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates/'), autoescape=True)
@ -182,7 +183,6 @@ try:
session_ttl = sql.get_setting('session_ttl')
except Exception as e:
error = f'error: {e}'
pass
try:
role = sql.get_user_role_by_uuid(user_id.value)
@ -214,7 +214,7 @@ if login is not None and password is not None:
if login in users.username:
check_in_ldap(login, password)
else:
passwordHashed = funct.get_hash(password)
passwordHashed = roxy_wi_tools.Tools.get_hash(password)
if login in users.username and passwordHashed == users.password:
send_cookie(login)
break
@ -227,8 +227,7 @@ if login is not None and password is not None:
if login is None:
print("Content-type: text/html\n")
output_from_parsed_template = template.render(
h2=0, title="Login page", role=role, user=user, error_log=error_log, error=error, ref=ref,
versions=funct.versions()
parsed_template = template.render(
h2=0, title="Login page", role=role, user=user, error_log=error_log, error=error, ref=ref
)
print(output_from_parsed_template)
print(parsed_template)

44
app/modules/roxy_wi_tools.py

@ -27,34 +27,21 @@ class GetDate:
self.fmt = "%Y-%m-%d.%H:%M:%S"
def return_date(self, log_type, **kwargs):
try:
cur_time_zone = timezone(self.time_zone)
except Exception:
cur_time_zone = timezone('UTC')
if kwargs.get('timedelta'):
try:
now_utc = datetime.now(timezone(self.time_zone)) + timedelta(days=kwargs.get('timedelta'))
except Exception:
now_utc = datetime.now(timezone('UTC')) + timedelta(days=kwargs.get('timedelta'))
now_utc = datetime.now(cur_time_zone) + timedelta(days=kwargs.get('timedelta'))
elif kwargs.get('timedelta_minus'):
try:
now_utc = datetime.now(timezone(self.time_zone)) - timedelta(
days=kwargs.get('timedelta_minus'))
except Exception:
now_utc = datetime.now(timezone('UTC')) - timedelta(days=kwargs.get('timedelta_minus'))
now_utc = datetime.now(cur_time_zone) - timedelta(days=kwargs.get('timedelta_minus'))
elif kwargs.get('timedelta_minutes'):
try:
now_utc = datetime.now(timezone(self.time_zone)) + timedelta(
minutes=kwargs.get('timedelta_minutes'))
except Exception:
now_utc = datetime.now(timezone('UTC')) + timedelta(minutes=kwargs.get('timedelta_minutes'))
now_utc = datetime.now(cur_time_zone) + timedelta(minutes=kwargs.get('timedelta_minutes'))
elif kwargs.get('timedelta_minutes_minus'):
try:
now_utc = datetime.now(timezone(self.time_zone)) - timedelta(
minutes=kwargs.get('timedelta_minutes_minus'))
except Exception:
now_utc = datetime.now(timezone('UTC')) - timedelta(minutes=kwargs.get('timedelta_minutes_minus'))
now_utc = datetime.now(cur_time_zone) - timedelta(minutes=kwargs.get('timedelta_minutes_minus'))
else:
try:
now_utc = datetime.now(timezone(self.time_zone))
except Exception:
now_utc = datetime.now(timezone('UTC'))
now_utc = datetime.now(cur_time_zone)
if log_type == 'config':
self.fmt = "%Y-%m-%d.%H:%M:%S"
@ -66,3 +53,14 @@ class GetDate:
self.fmt = "%Y-%m-%d %H:%M:%S"
return now_utc.strftime(self.fmt)
class Tools:
@staticmethod
def get_hash(need_hashed):
if need_hashed is None:
return need_hashed
import hashlib
h = hashlib.md5(need_hashed.encode('utf-8'))
p = h.hexdigest()
return p

17
app/sql.py

@ -7,6 +7,7 @@ import os
from modules.db_model import *
import modules.roxy_wi_tools as roxy_wi_tools
def get_setting(param, **kwargs):
import funct
try:
@ -45,6 +46,7 @@ def get_setting(param, **kwargs):
time_zone = get_setting('time_zone')
get_date = roxy_wi_tools.GetDate(time_zone)
def out_error(error):
error = str(error)
exc_type, exc_obj, exc_tb = sys.exc_info()
@ -56,12 +58,11 @@ def out_error(error):
def add_user(user, email, password, role, activeuser, group):
import funct
if password != 'aduser':
try:
hashed_pass = roxy_wi_tools.Tools.get_hash(password)
User.insert(
username=user, email=email, password=funct.get_hash(password), role=role, activeuser=activeuser,
groups=group
username=user, email=email, password=hashed_pass, role=role, activeuser=activeuser, groups=group
).execute()
except Exception as e:
out_error(e)
@ -120,9 +121,9 @@ def update_user_current_groups(groups, user_uuid):
def update_user_password(password, user_id):
import funct
try:
user_update = User.update(password=funct.get_hash(password)).where(User.user_id == user_id)
hashed_pass = roxy_wi_tools.Tools.get_hash(password)
user_update = User.update(password=hashed_pass).where(User.user_id == user_id)
user_update.execute()
except Exception as e:
out_error(e)
@ -1999,7 +2000,7 @@ def select_service_table_metrics(service):
group_id = funct.get_user_group(id=1)
if service in ('nginx', 'apache'):
metrics_table = '{}_metrics'.format(service)
metrics_table = f'{service}_metrics'
if funct.check_user_group():
if group_id == 1:
@ -2424,9 +2425,9 @@ def select_smon(user_group, **kwargs):
user_group = ''
else:
if kwargs.get('ip'):
user_group = "and user_group = '%s'" % user_group
user_group = f"and user_group = '{user_group}'"
else:
user_group = "where user_group='%s'" % user_group
user_group = f"where user_group = '{user_group}'"
if kwargs.get('ip'):
try:

Loading…
Cancel
Save