174 lines
6.0 KiB
Python

# -*- coding: utf-8 -*-
"""系统信息"""
import datetime
import json
import logging
import re
import time
from sqlalchemy import text
from website import consts
from website import errors
from website import settings
from website.db_mysql import to_json_list
from website.handler import APIHandler, authenticated
from website.util import sysinfo, rsa_oaep
class VersionHandler(APIHandler):
@authenticated
# @permission([100014, 100016])
def post(self):
self.finish()
class IdentifycodeHandler(APIHandler):
"""系统识别码"""
# @authenticated
# @permission([100014, 100015])
# @operation_log("资产管理中心", "系统激活", "查询", "查询本地识别码", "查询本地识别码")
def post(self):
code = sysinfo.get_identify_code()
self.finish({"result": code})
class LicenseUploadHandler(APIHandler):
@authenticated
# @permission([100014, 100015])
# @operation_log("资产管理中心", "系统激活", "导入", "上传license文件", "上传license文件")
def post(self):
file_metas = self.request.files.get('file', None)
if not file_metas:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "请上传文件")
file = file_metas[0]
filename = file.filename
# punctuation = """!"#$%&'()*+,/:;<=>?@[\]^`{|}~ """
# punctuation = """!"#$%&'()*+,/:;<=>?@[\\]^`{|}~ """
punctuation = r"""!"#$%&'()*+,/:;<=>?@[\]^`{|}~ """
regex = re.compile('[%s]' % re.escape(punctuation))
filename = regex.sub("", filename.replace('..', ''))
file_size = len(file.body)
if file_size > 10 * 1024 * 1024:
raise errors.HTTPAPIError(errors.ERROR_METHOD_NOT_ALLOWED, 'Exceed 10M size limit')
filepath = settings.rsa_license_file
try:
body = file['body']
plaintext = rsa_oaep.decrypt_message_pri(
open(settings.rsa_private_file).read().strip('\n').encode('utf-8'), body)
plaintext_json = json.loads(self.tostr(plaintext))
syscode = plaintext_json["sys_code"]
expireat = plaintext_json["expire_at"]
current_syscode = sysinfo.get_idntify_code_v2()
if syscode != current_syscode:
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "license激活失败请重新激活")
with self.app_mysql.connect() as conn:
conn.execute(text(
"update sys_license set syscode=:syscode, expireat=:expireat, status=:status",
{
"syscode": syscode,
"expireat": expireat,
"status": consts.system_status_activated
}
))
conn.commit()
self.r_app.set("system:license", json.dumps({"syscode": syscode, "expireat": expireat}))
with open(filepath, 'wb') as f:
f.write(file['body'])
except Exception as e:
logging.info(e)
raise errors.HTTPAPIError(errors.ERROR_BAD_REQUEST, "license激活失败请重新激活")
self.finish()
class ActivateInfoHandler(APIHandler):
@authenticated
# @permission([100014, 100015])
# @operation_log("资产管理中心", "系统激活", "查询", "查询系统激活信息", "查询系统激活信息")
def post(self):
license_str = ""
activate_at = ""
expire_at = ""
date_remain = 0
row = self.db_app.get(
"select create_time, expireat from license limit 1"
)
if row:
license_str = open(settings.rsa_license_file, 'r').read()
activate_at = str(row["create_time"])
expire_at = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(row["expireat"])))
now = datetime.datetime.now()
delta = (datetime.datetime.fromtimestamp(int(row["expireat"])).date() - now.date()).days
date_remain = delta if delta > 0 else 0
data = {
# "system": settings.system_info[settings.system_type]["name"],
# "license": license_str,
# "activate_at": activate_at,
# "expire_at": expire_at,
# "date_remain": date_remain
}
self.finish(data)
class InfoHandler(APIHandler):
def post(self):
self.finish()
class LogHandler(APIHandler):
@authenticated
def post(self):
user = self.get_escaped_argument("user", "")
start = self.get_escaped_argument("startDate", "")
end = self.get_escaped_argument("endDate", "")
pageNo = self.get_int_argument("pageNo", 1)
pageSize = self.get_int_argument("pageSize", 20)
user_list = user.split(",") if user else []
with self.app_mysql.connect() as conn:
sql = "select user, ip, content, op_type, content, create_time from sys_log where 1=1"
sql_count = "select count(*) from sys_log where 1=1"
p = {}
if user_list:
sql += " and user in :users"
sql_count += " and user in :users"
p["users"] = user_list
if start:
sql += " and date_format(create_time, '%Y-%m-%d') >= :start"
sql_count += " and date_format(create_time, '%Y-%m-%d') >= :start"
p["start"] = start
if end:
sql += " and date_format(create_time, '%Y-%m-%d') <= :end"
sql_count += " and date_format(create_time, '%Y-%m-%d') <= :end"
p["end"] = end
count = conn.scalar(text(sql_count), p)
sql += " order by create_time desc limit :pageNo, :pageSize"
p["pageNo"] = (pageNo - 1) * pageSize
p["pageSize"] = pageSize
res = conn.execute(text(sql), p)
data = to_json_list(res)
for item in data:
item["create_time"] = str(item["create_time"])
self.finish({"count": count, "data": data})