Compare commits
34 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
18103e3d38 | ||
![]() |
cb96c878bf | ||
![]() |
266b3e3b5c | ||
![]() |
6ea8ada989 | ||
![]() |
901a66bafa | ||
![]() |
c9cb8c6542 | ||
![]() |
34f9e891b6 | ||
![]() |
fb9dfa4674 | ||
![]() |
bbb7214cee | ||
![]() |
52e92d50d1 | ||
![]() |
816793b888 | ||
![]() |
e774e1b26b | ||
![]() |
42009cf3f4 | ||
![]() |
f4afa20ac2 | ||
![]() |
7fd3109b52 | ||
![]() |
dfb8af23b3 | ||
![]() |
b423647ad5 | ||
![]() |
423491302d | ||
![]() |
fa27fd3b68 | ||
![]() |
88b27685c1 | ||
![]() |
2bade4d6c9 | ||
![]() |
a06c9f17d6 | ||
![]() |
3654f4d88b | ||
![]() |
38aca38d4d | ||
![]() |
a57d737261 | ||
![]() |
84f56da523 | ||
![]() |
f73a00e73c | ||
![]() |
a84ad47de4 | ||
![]() |
303612eed9 | ||
![]() |
dcb1f4d13c | ||
![]() |
44ddc8c3a8 | ||
![]() |
70f6f8a471 | ||
![]() |
2a45df71cd | ||
![]() |
eabeb705c4 |
11
README.md
11
README.md
@@ -1,12 +1,12 @@
|
||||
<p align="center">
|
||||
<img alt="logo" src="https://oscimg.oschina.net/oscnet/up-d3d0a9303e11d522a06cd263f3079027715.png">
|
||||
</p>
|
||||
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">RuoYi-Vue3-FastAPI v1.0.2</h1>
|
||||
<h1 align="center" style="margin: 30px 0 30px; font-weight: bold;">RuoYi-Vue3-FastAPI v1.1.3</h1>
|
||||
<h4 align="center">基于RuoYi-Vue3+FastAPI前后端分离的快速开发框架</h4>
|
||||
<p align="center">
|
||||
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI/stargazers"><img src="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI/badge/star.svg?theme=dark"></a>
|
||||
<a href="https://github.com/insistence/RuoYi-Vue3-FastAPI"><img src="https://img.shields.io/github/stars/insistence/RuoYi-Vue3-FastAPI?style=social"></a>
|
||||
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI"><img src="https://img.shields.io/badge/RuoYiVue3FastAPI-v1.0.2-brightgreen.svg"></a>
|
||||
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI"><img src="https://img.shields.io/badge/RuoYiVue3FastAPI-v1.1.3-brightgreen.svg"></a>
|
||||
<a href="https://gitee.com/insistence2022/RuoYi-Vue3-FastAPI/blob/master/LICENSE"><img src="https://img.shields.io/github/license/mashape/apistatus.svg"></a>
|
||||
<img src="https://img.shields.io/badge/python-≥3.8-blue">
|
||||
<img src="https://img.shields.io/badge/MySQL-≥5.7-blue">
|
||||
@@ -14,9 +14,14 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## 平台简介
|
||||
|
||||
RuoYi-Vue-FastAPI是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
|
||||
RuoYi-Vue3-FastAPI是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
|
||||
|
||||
* 前端采用Vue、Element Plus,基于<u>[RuoYi-Vue3](https://github.com/yangzongzhuan/RuoYi-Vue3)</u>前端项目修改。
|
||||
* 后端采用FastAPI、sqlalchemy、MySQL、Redis、OAuth2 & Jwt。
|
||||
|
@@ -2,7 +2,7 @@
|
||||
# 应用运行环境
|
||||
APP_ENV = 'dev'
|
||||
# 应用名称
|
||||
APP_NAME = 'RuoYi-FasAPI'
|
||||
APP_NAME = 'RuoYi-FastAPI'
|
||||
# 应用代理路径
|
||||
APP_ROOT_PATH = '/dev-api'
|
||||
# 应用主机
|
||||
@@ -10,9 +10,13 @@ APP_HOST = '0.0.0.0'
|
||||
# 应用端口
|
||||
APP_PORT = 9099
|
||||
# 应用版本
|
||||
APP_VERSION= '1.0.2'
|
||||
APP_VERSION= '1.1.3'
|
||||
# 应用是否开启热重载
|
||||
APP_RELOAD = true
|
||||
# 应用是否开启IP归属区域查询
|
||||
APP_IP_LOCATION_QUERY = true
|
||||
# 应用是否允许账号同时登录
|
||||
APP_SAME_TIME_LOGIN = true
|
||||
|
||||
# -------- Jwt配置 --------
|
||||
# Jwt秘钥
|
||||
@@ -36,6 +40,16 @@ DB_USERNAME = 'root'
|
||||
DB_PASSWORD = 'mysqlroot'
|
||||
# 数据库名称
|
||||
DB_DATABASE = 'ruoyi-fastapi'
|
||||
# 是否开启sqlalchemy日志
|
||||
DB_ECHO = true
|
||||
# 允许溢出连接池大小的最大连接数
|
||||
DB_MAX_OVERFLOW = 10
|
||||
# 连接池大小,0表示连接数无限制
|
||||
DB_POOL_SIZE = 50
|
||||
# 连接回收时间(单位:秒)
|
||||
DB_POOL_RECYCLE = 3600
|
||||
# 连接池中没有线程可用时,最多等待的时间(单位:秒)
|
||||
DB_POOL_TIMEOUT = 30
|
||||
|
||||
# -------- Redis配置 --------
|
||||
# Redis主机
|
||||
|
@@ -2,7 +2,7 @@
|
||||
# 应用运行环境
|
||||
APP_ENV = 'prod'
|
||||
# 应用名称
|
||||
APP_NAME = 'RuoYi-FasAPI'
|
||||
APP_NAME = 'RuoYi-FastAPI'
|
||||
# 应用代理路径
|
||||
APP_ROOT_PATH = '/prod-api'
|
||||
# 应用主机
|
||||
@@ -10,9 +10,13 @@ APP_HOST = '0.0.0.0'
|
||||
# 应用端口
|
||||
APP_PORT = 9099
|
||||
# 应用版本
|
||||
APP_VERSION= '1.0.2'
|
||||
APP_VERSION= '1.1.3'
|
||||
# 应用是否开启热重载
|
||||
APP_RELOAD = false
|
||||
# 应用是否开启IP归属区域查询
|
||||
APP_IP_LOCATION_QUERY = true
|
||||
# 应用是否允许账号同时登录
|
||||
APP_SAMETIME_LOGIN = true
|
||||
|
||||
# -------- Jwt配置 --------
|
||||
# Jwt秘钥
|
||||
@@ -36,6 +40,16 @@ DB_USERNAME = 'root'
|
||||
DB_PASSWORD = 'root'
|
||||
# 数据库名称
|
||||
DB_DATABASE = 'ruoyi-fastapi'
|
||||
# 是否开启sqlalchemy日志
|
||||
DB_ECHO = true
|
||||
# 允许溢出连接池大小的最大连接数
|
||||
DB_MAX_OVERFLOW = 10
|
||||
# 连接池大小,0表示连接数无限制
|
||||
DB_POOL_SIZE = 50
|
||||
# 连接回收时间(单位:秒)
|
||||
DB_POOL_RECYCLE = 3600
|
||||
# 连接池中没有线程可用时,最多等待的时间(单位:秒)
|
||||
DB_POOL_TIMEOUT = 30
|
||||
|
||||
# -------- Redis配置 --------
|
||||
# Redis主机
|
||||
|
@@ -8,7 +8,12 @@ SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{DataBaseConfig.db_username}:{quote_
|
||||
f"{DataBaseConfig.db_host}:{DataBaseConfig.db_port}/{DataBaseConfig.db_database}"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, echo=True
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
echo=DataBaseConfig.db_echo,
|
||||
max_overflow=DataBaseConfig.db_max_overflow,
|
||||
pool_size=DataBaseConfig.db_pool_size,
|
||||
pool_recycle=DataBaseConfig.db_pool_recycle,
|
||||
pool_timeout=DataBaseConfig.db_pool_timeout
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
|
@@ -17,6 +17,8 @@ class AppSettings(BaseSettings):
|
||||
app_port: int = 9099
|
||||
app_version: str = '1.0.0'
|
||||
app_reload: bool = True
|
||||
app_ip_location_query: bool = True
|
||||
app_same_time_login: bool = True
|
||||
|
||||
|
||||
class JwtSettings(BaseSettings):
|
||||
@@ -38,6 +40,11 @@ class DataBaseSettings(BaseSettings):
|
||||
db_username: str = 'root'
|
||||
db_password: str = 'mysqlroot'
|
||||
db_database: str = 'ruoyi-fastapi'
|
||||
db_echo: bool = True
|
||||
db_max_overflow: int = 10
|
||||
db_pool_size: int = 50
|
||||
db_pool_recycle: int = 3600
|
||||
db_pool_timeout: int = 30
|
||||
|
||||
|
||||
class RedisSettings(BaseSettings):
|
||||
|
@@ -26,3 +26,13 @@ class PermissionException(Exception):
|
||||
def __init__(self, data: str = None, message: str = None):
|
||||
self.data = data
|
||||
self.message = message
|
||||
|
||||
|
||||
class ModelValidatorException(Exception):
|
||||
"""
|
||||
自定义模型校验异常ModelValidatorException
|
||||
"""
|
||||
|
||||
def __init__(self, data: str = None, message: str = None):
|
||||
self.data = data
|
||||
self.message = message
|
||||
|
@@ -1,6 +1,6 @@
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import HTTPException
|
||||
from exceptions.exception import AuthException, PermissionException
|
||||
from exceptions.exception import AuthException, PermissionException, ModelValidatorException
|
||||
from utils.response_util import ResponseUtil, JSONResponse, jsonable_encoder
|
||||
|
||||
|
||||
@@ -18,6 +18,11 @@ def handle_exception(app: FastAPI):
|
||||
async def permission_exception_handler(request: Request, exc: PermissionException):
|
||||
return ResponseUtil.forbidden(data=exc.data, msg=exc.message)
|
||||
|
||||
# 自定义模型检验异常
|
||||
@app.exception_handler(ModelValidatorException)
|
||||
async def model_validator_exception_handler(request: Request, exc: ModelValidatorException):
|
||||
return ResponseUtil.failure(data=exc.data, msg=exc.message)
|
||||
|
||||
# 处理其他http请求异常
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_exception_handler(request: Request, exc: HTTPException):
|
||||
|
@@ -1,4 +1,4 @@
|
||||
from functools import wraps
|
||||
from functools import wraps, lru_cache
|
||||
from fastapi import Request
|
||||
from fastapi.responses import JSONResponse, ORJSONResponse, UJSONResponse
|
||||
import inspect
|
||||
@@ -12,6 +12,7 @@ from typing import Optional
|
||||
from module_admin.service.login_service import LoginService
|
||||
from module_admin.service.log_service import OperationLogService, LoginLogService
|
||||
from module_admin.entity.vo.log_vo import OperLogModel, LogininforModel
|
||||
from config.env import AppConfig
|
||||
|
||||
|
||||
def log_decorator(title: str, business_type: int, log_type: Optional[str] = 'operation'):
|
||||
@@ -50,123 +51,136 @@ def log_decorator(title: str, business_type: int, log_type: Optional[str] = 'ope
|
||||
# 获取请求的ip及ip归属区域
|
||||
oper_ip = request.headers.get("X-Forwarded-For")
|
||||
oper_location = '内网IP'
|
||||
try:
|
||||
if oper_ip != '127.0.0.1' and oper_ip != 'localhost':
|
||||
ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
|
||||
if ip_result.status_code == 200:
|
||||
prov = ip_result.json().get('data').get('prov')
|
||||
city = ip_result.json().get('data').get('city')
|
||||
if prov or city:
|
||||
oper_location = f'{prov}-{city}'
|
||||
else:
|
||||
oper_location = '未知'
|
||||
else:
|
||||
oper_location = '未知'
|
||||
except Exception as e:
|
||||
oper_location = '未知'
|
||||
print(e)
|
||||
finally:
|
||||
# 根据不同的请求类型使用不同的方法获取请求参数
|
||||
content_type = request.headers.get("Content-Type")
|
||||
if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type):
|
||||
payload = await request.form()
|
||||
oper_param = "\n".join([f"{key}: {value}" for key, value in payload.items()])
|
||||
else:
|
||||
payload = await request.body()
|
||||
# 通过 request.path_params 直接访问路径参数
|
||||
path_params = request.path_params
|
||||
oper_param = {}
|
||||
if payload:
|
||||
oper_param.update(json.loads(str(payload, 'utf-8')))
|
||||
if path_params:
|
||||
oper_param.update(path_params)
|
||||
oper_param = json.dumps(oper_param, ensure_ascii=False)
|
||||
# 日志表请求参数字段长度最大为2000,因此在此处判断长度
|
||||
if len(oper_param) > 2000:
|
||||
oper_param = '请求参数过长'
|
||||
if AppConfig.app_ip_location_query:
|
||||
oper_location = get_ip_location(oper_ip)
|
||||
# 根据不同的请求类型使用不同的方法获取请求参数
|
||||
content_type = request.headers.get("Content-Type")
|
||||
if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type):
|
||||
payload = await request.form()
|
||||
oper_param = "\n".join([f"{key}: {value}" for key, value in payload.items()])
|
||||
else:
|
||||
payload = await request.body()
|
||||
# 通过 request.path_params 直接访问路径参数
|
||||
path_params = request.path_params
|
||||
oper_param = {}
|
||||
if payload:
|
||||
oper_param.update(json.loads(str(payload, 'utf-8')))
|
||||
if path_params:
|
||||
oper_param.update(path_params)
|
||||
oper_param = json.dumps(oper_param, ensure_ascii=False)
|
||||
# 日志表请求参数字段长度最大为2000,因此在此处判断长度
|
||||
if len(oper_param) > 2000:
|
||||
oper_param = '请求参数过长'
|
||||
|
||||
# 获取操作时间
|
||||
oper_time = datetime.now()
|
||||
# 此处在登录之前向原始函数传递一些登录信息,用于监测在线用户的相关信息
|
||||
login_log = {}
|
||||
if log_type == 'login':
|
||||
user_agent_info = parse(user_agent)
|
||||
browser = f'{user_agent_info.browser.family} {user_agent_info.browser.version[0]}'
|
||||
system_os = f'{user_agent_info.os.family} {user_agent_info.os.version[0]}'
|
||||
login_log = dict(
|
||||
ipaddr=oper_ip,
|
||||
loginLocation=oper_location,
|
||||
browser=browser,
|
||||
os=system_os,
|
||||
loginTime=oper_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||
)
|
||||
kwargs['form_data'].login_info = login_log
|
||||
# 调用原始函数
|
||||
result = await func(*args, **kwargs)
|
||||
# 获取请求耗时
|
||||
cost_time = float(time.time() - start_time) * 100
|
||||
# 判断请求是否来自api文档
|
||||
request_from_swagger = request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False
|
||||
request_from_redoc = request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False
|
||||
# 根据响应结果的类型使用不同的方法获取响应结果参数
|
||||
if isinstance(result, JSONResponse) or isinstance(result, ORJSONResponse) or isinstance(result, UJSONResponse):
|
||||
result_dict = json.loads(str(result.body, 'utf-8'))
|
||||
# 获取操作时间
|
||||
oper_time = datetime.now()
|
||||
# 此处在登录之前向原始函数传递一些登录信息,用于监测在线用户的相关信息
|
||||
login_log = {}
|
||||
if log_type == 'login':
|
||||
user_agent_info = parse(user_agent)
|
||||
browser = f'{user_agent_info.browser.family}'
|
||||
system_os = f'{user_agent_info.os.family}'
|
||||
if user_agent_info.browser.version != ():
|
||||
browser += f' {user_agent_info.browser.version[0]}'
|
||||
if user_agent_info.os.version != ():
|
||||
system_os += f' {user_agent_info.os.version[0]}'
|
||||
login_log = dict(
|
||||
ipaddr=oper_ip,
|
||||
loginLocation=oper_location,
|
||||
browser=browser,
|
||||
os=system_os,
|
||||
loginTime=oper_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||
)
|
||||
kwargs['form_data'].login_info = login_log
|
||||
# 调用原始函数
|
||||
result = await func(*args, **kwargs)
|
||||
# 获取请求耗时
|
||||
cost_time = float(time.time() - start_time) * 100
|
||||
# 判断请求是否来自api文档
|
||||
request_from_swagger = request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False
|
||||
request_from_redoc = request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False
|
||||
# 根据响应结果的类型使用不同的方法获取响应结果参数
|
||||
if isinstance(result, JSONResponse) or isinstance(result, ORJSONResponse) or isinstance(result, UJSONResponse):
|
||||
result_dict = json.loads(str(result.body, 'utf-8'))
|
||||
else:
|
||||
if request_from_swagger or request_from_redoc:
|
||||
result_dict = {}
|
||||
else:
|
||||
if request_from_swagger or request_from_redoc:
|
||||
result_dict = {}
|
||||
if result.status_code == 200:
|
||||
result_dict = {'code': result.status_code, 'message': '获取成功'}
|
||||
else:
|
||||
if result.status_code == 200:
|
||||
result_dict = {'code': result.status_code, 'message': '获取成功'}
|
||||
else:
|
||||
result_dict = {'code': result.status_code, 'message': '获取失败'}
|
||||
json_result = json.dumps(result_dict, ensure_ascii=False)
|
||||
# 根据响应结果获取响应状态及异常信息
|
||||
status = 1
|
||||
error_msg = ''
|
||||
if result_dict.get('code') == 200:
|
||||
status = 0
|
||||
result_dict = {'code': result.status_code, 'message': '获取失败'}
|
||||
json_result = json.dumps(result_dict, ensure_ascii=False)
|
||||
# 根据响应结果获取响应状态及异常信息
|
||||
status = 1
|
||||
error_msg = ''
|
||||
if result_dict.get('code') == 200:
|
||||
status = 0
|
||||
else:
|
||||
error_msg = result_dict.get('msg')
|
||||
# 根据日志类型向对应的日志表插入数据
|
||||
if log_type == 'login':
|
||||
# 登录请求来自于api文档时不记录登录日志,其余情况则记录
|
||||
if request_from_swagger or request_from_redoc:
|
||||
pass
|
||||
else:
|
||||
error_msg = result_dict.get('msg')
|
||||
# 根据日志类型向对应的日志表插入数据
|
||||
if log_type == 'login':
|
||||
# 登录请求来自于api文档时不记录登录日志,其余情况则记录
|
||||
if request_from_swagger or request_from_redoc:
|
||||
pass
|
||||
else:
|
||||
user = kwargs.get('form_data')
|
||||
user_name = user.username
|
||||
login_log['loginTime'] = oper_time
|
||||
login_log['userName'] = user_name
|
||||
login_log['status'] = str(status)
|
||||
login_log['msg'] = result_dict.get('msg')
|
||||
user = kwargs.get('form_data')
|
||||
user_name = user.username
|
||||
login_log['loginTime'] = oper_time
|
||||
login_log['userName'] = user_name
|
||||
login_log['status'] = str(status)
|
||||
login_log['msg'] = result_dict.get('msg')
|
||||
|
||||
LoginLogService.add_login_log_services(query_db, LogininforModel(**login_log))
|
||||
else:
|
||||
current_user = await LoginService.get_current_user(request, token, query_db)
|
||||
oper_name = current_user.user.user_name
|
||||
dept_name = current_user.user.dept.dept_name if current_user.user.dept else None
|
||||
operation_log = OperLogModel(
|
||||
title=title,
|
||||
businessType=business_type,
|
||||
method=func_path,
|
||||
requestMethod=request_method,
|
||||
operatorType=operator_type,
|
||||
operName=oper_name,
|
||||
deptName=dept_name,
|
||||
operUrl=oper_url,
|
||||
operIp=oper_ip,
|
||||
operLocation=oper_location,
|
||||
operParam=oper_param,
|
||||
jsonResult=json_result,
|
||||
status=status,
|
||||
errorMsg=error_msg,
|
||||
operTime=oper_time,
|
||||
costTime=int(cost_time)
|
||||
)
|
||||
OperationLogService.add_operation_log_services(query_db, operation_log)
|
||||
LoginLogService.add_login_log_services(query_db, LogininforModel(**login_log))
|
||||
else:
|
||||
current_user = await LoginService.get_current_user(request, token, query_db)
|
||||
oper_name = current_user.user.user_name
|
||||
dept_name = current_user.user.dept.dept_name if current_user.user.dept else None
|
||||
operation_log = OperLogModel(
|
||||
title=title,
|
||||
businessType=business_type,
|
||||
method=func_path,
|
||||
requestMethod=request_method,
|
||||
operatorType=operator_type,
|
||||
operName=oper_name,
|
||||
deptName=dept_name,
|
||||
operUrl=oper_url,
|
||||
operIp=oper_ip,
|
||||
operLocation=oper_location,
|
||||
operParam=oper_param,
|
||||
jsonResult=json_result,
|
||||
status=status,
|
||||
errorMsg=error_msg,
|
||||
operTime=oper_time,
|
||||
costTime=int(cost_time)
|
||||
)
|
||||
OperationLogService.add_operation_log_services(query_db, operation_log)
|
||||
|
||||
return result
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_ip_location(oper_ip: str):
|
||||
"""
|
||||
查询ip归属区域
|
||||
:param oper_ip: 需要查询的ip
|
||||
:return: ip归属区域
|
||||
"""
|
||||
oper_location = '内网IP'
|
||||
try:
|
||||
if oper_ip != '127.0.0.1' and oper_ip != 'localhost':
|
||||
oper_location = '未知'
|
||||
ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}')
|
||||
if ip_result.status_code == 200:
|
||||
prov = ip_result.json().get('data').get('prov')
|
||||
city = ip_result.json().get('data').get('city')
|
||||
if prov or city:
|
||||
oper_location = f'{prov}-{city}'
|
||||
except Exception as e:
|
||||
oper_location = '未知'
|
||||
print(e)
|
||||
return oper_location
|
||||
|
@@ -41,11 +41,13 @@ async def login(request: Request, form_data: CustomOAuth2PasswordRequestForm = D
|
||||
},
|
||||
expires_delta=access_token_expires
|
||||
)
|
||||
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}", access_token,
|
||||
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
# 此方法可实现同一账号同一时间只能登录一次
|
||||
# await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{result[0].user_id}", access_token,
|
||||
# ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
if AppConfig.app_same_time_login:
|
||||
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}", access_token,
|
||||
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
else:
|
||||
# 此方法可实现同一账号同一时间只能登录一次
|
||||
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{result[0].user_id}", access_token,
|
||||
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
UserService.edit_user_services(query_db, EditUserModel(userId=result[0].user_id, loginDate=datetime.now(), type='status'))
|
||||
logger.info('登录成功')
|
||||
# 判断请求是否来自于api文档,如果是返回指定格式的结果,用于修复api文档认证成功后token显示undefined的bug
|
||||
@@ -131,7 +133,7 @@ async def register_user(request: Request, user_register: UserRegister, query_db:
|
||||
@loginController.post("/logout")
|
||||
async def logout(request: Request, token: Optional[str] = Depends(oauth2_scheme)):
|
||||
try:
|
||||
payload = jwt.decode(token, JwtConfig.jwt_secret_key, algorithms=[JwtConfig.jwt_algorithm])
|
||||
payload = jwt.decode(token, JwtConfig.jwt_secret_key, algorithms=[JwtConfig.jwt_algorithm], options={'verify_exp': False})
|
||||
session_id: str = payload.get("session_id")
|
||||
await LoginService.logout_services(request, session_id)
|
||||
logger.info('退出成功')
|
||||
|
@@ -198,11 +198,20 @@ async def change_system_user_profile_avatar(request: Request, avatarfile: bytes
|
||||
@log_decorator(title='个人信息', business_type=2)
|
||||
async def change_system_user_profile_info(request: Request, user_info: UserInfoModel, query_db: Session = Depends(get_db), current_user: CurrentUserModel = Depends(LoginService.get_current_user)):
|
||||
try:
|
||||
edit_user = EditUserModel(**user_info.model_dump(by_alias=True, exclude={'role_ids', 'post_ids'}), roleIds=user_info.role_ids.split(','), postIds=user_info.post_ids.split(','))
|
||||
edit_user.user_id = current_user.user.user_id
|
||||
edit_user.update_by = current_user.user.user_name
|
||||
edit_user.update_time = datetime.now()
|
||||
print(edit_user.model_dump())
|
||||
edit_user = EditUserModel(
|
||||
**user_info.model_dump(
|
||||
exclude_unset=True,
|
||||
by_alias=True,
|
||||
exclude={'role_ids', 'post_ids'}
|
||||
),
|
||||
userId=current_user.user.user_id,
|
||||
userName=current_user.user.user_name,
|
||||
updateBy=current_user.user.user_name,
|
||||
updateTime=datetime.now(),
|
||||
roleIds=current_user.user.role_ids.split(',') if current_user.user.role_ids else [],
|
||||
postIds=current_user.user.post_ids.split(',') if current_user.user.post_ids else [],
|
||||
role=current_user.user.role
|
||||
)
|
||||
edit_user_result = UserService.edit_user_services(query_db, edit_user)
|
||||
if edit_user_result.is_success:
|
||||
logger.info(edit_user_result.message)
|
||||
@@ -217,12 +226,12 @@ async def change_system_user_profile_info(request: Request, user_info: UserInfoM
|
||||
|
||||
@userController.put("/profile/updatePwd")
|
||||
@log_decorator(title='个人信息', business_type=2)
|
||||
async def reset_system_user_password(request: Request, old_password: str = Query(alias='oldPassword'), new_password: str = Query(alias='newPassword'), query_db: Session = Depends(get_db), current_user: CurrentUserModel = Depends(LoginService.get_current_user)):
|
||||
async def reset_system_user_password(request: Request, reset_password: ResetPasswordModel = Depends(ResetPasswordModel.as_query), query_db: Session = Depends(get_db), current_user: CurrentUserModel = Depends(LoginService.get_current_user)):
|
||||
try:
|
||||
reset_user = ResetUserModel(
|
||||
userId=current_user.user.user_id,
|
||||
oldPassword=old_password,
|
||||
password=PwdUtil.get_password_hash(new_password),
|
||||
oldPassword=reset_password.old_password,
|
||||
password=PwdUtil.get_password_hash(reset_password.new_password),
|
||||
updateBy=current_user.user.user_name,
|
||||
updateTime=datetime.now()
|
||||
)
|
||||
|
@@ -51,7 +51,7 @@ class NoticeDao:
|
||||
"""
|
||||
query = db.query(SysNotice) \
|
||||
.filter(SysNotice.notice_title.like(f'%{query_object.notice_title}%') if query_object.notice_title else True,
|
||||
SysNotice.update_by.like(f'%{query_object.update_by}%') if query_object.update_by else True,
|
||||
SysNotice.create_by.like(f'%{query_object.create_by}%') if query_object.create_by else True,
|
||||
SysNotice.notice_type == query_object.notice_type if query_object.notice_type else True,
|
||||
SysNotice.create_time.between(
|
||||
datetime.combine(datetime.strptime(query_object.begin_time, '%Y-%m-%d'), time(00, 00, 00)),
|
||||
|
@@ -1,6 +1,8 @@
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
import re
|
||||
from pydantic import BaseModel, ConfigDict, model_validator
|
||||
from pydantic.alias_generators import to_camel
|
||||
from typing import Optional
|
||||
from exceptions.exception import ModelValidatorException
|
||||
|
||||
|
||||
class UserLogin(BaseModel):
|
||||
@@ -23,6 +25,14 @@ class UserRegister(BaseModel):
|
||||
code: Optional[str] = None
|
||||
uuid: Optional[str] = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def check_password(self) -> 'UserRegister':
|
||||
pattern = r'''^[^<>"'|\\]+$'''
|
||||
if self.password is None or re.match(pattern, self.password):
|
||||
return self
|
||||
else:
|
||||
raise ModelValidatorException(message="密码不能包含非法字符:< > \" ' \\ |")
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
|
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
from pydantic import BaseModel, ConfigDict, model_validator
|
||||
from pydantic.alias_generators import to_camel
|
||||
from typing import Union, Optional, List
|
||||
@@ -6,6 +7,7 @@ from module_admin.entity.vo.role_vo import RoleModel
|
||||
from module_admin.entity.vo.dept_vo import DeptModel
|
||||
from module_admin.entity.vo.post_vo import PostModel
|
||||
from module_admin.annotation.pydantic_annotation import as_query, as_form
|
||||
from exceptions.exception import ModelValidatorException
|
||||
|
||||
|
||||
class TokenData(BaseModel):
|
||||
@@ -42,6 +44,14 @@ class UserModel(BaseModel):
|
||||
remark: Optional[str] = None
|
||||
admin: Optional[bool] = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def check_password(self) -> 'UserModel':
|
||||
pattern = r'''^[^<>"'|\\]+$'''
|
||||
if self.password is None or re.match(pattern, self.password):
|
||||
return self
|
||||
else:
|
||||
raise ModelValidatorException(message="密码不能包含非法字符:< > \" ' \\ |")
|
||||
|
||||
@model_validator(mode='after')
|
||||
def check_admin(self) -> 'UserModel':
|
||||
if self.user_id == 1:
|
||||
@@ -144,6 +154,25 @@ class EditUserModel(AddUserModel):
|
||||
role: Optional[List] = []
|
||||
|
||||
|
||||
@as_query
|
||||
class ResetPasswordModel(BaseModel):
|
||||
"""
|
||||
重置密码模型
|
||||
"""
|
||||
model_config = ConfigDict(alias_generator=to_camel)
|
||||
|
||||
old_password: Optional[str] = None
|
||||
new_password: Optional[str] = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def check_new_password(self) -> 'ResetPasswordModel':
|
||||
pattern = r'''^[^<>"'|\\]+$'''
|
||||
if self.new_password is None or re.match(pattern, self.new_password):
|
||||
return self
|
||||
else:
|
||||
raise ModelValidatorException(message="密码不能包含非法字符:< > \" ' \\ |")
|
||||
|
||||
|
||||
class ResetUserModel(UserModel):
|
||||
"""
|
||||
重置用户密码模型
|
||||
|
@@ -72,6 +72,7 @@ class JobService:
|
||||
if query_job:
|
||||
SchedulerUtil.remove_scheduler_job(job_id=edit_job.get('job_id'))
|
||||
if edit_job.get('status') == '0':
|
||||
job_info = cls.job_detail_services(query_db, edit_job.get('job_id'))
|
||||
SchedulerUtil.add_scheduler_job(job_info=job_info)
|
||||
query_db.commit()
|
||||
result = dict(is_success=True, message='更新成功')
|
||||
|
@@ -56,6 +56,7 @@ class LoginService:
|
||||
:param login_user: 登录用户对象
|
||||
:return: 校验结果
|
||||
"""
|
||||
await cls.__check_login_ip(request)
|
||||
account_lock = await request.app.state.redis.get(
|
||||
f"{RedisInitKeyConfig.ACCOUNT_LOCK.get('key')}:{login_user.user_name}")
|
||||
if login_user.user_name == account_lock:
|
||||
@@ -100,6 +101,21 @@ class LoginService:
|
||||
f"{RedisInitKeyConfig.PASSWORD_ERROR_COUNT.get('key')}:{login_user.user_name}")
|
||||
return user
|
||||
|
||||
@classmethod
|
||||
async def __check_login_ip(cls, request: Request):
|
||||
"""
|
||||
校验用户登录ip是否在黑名单内
|
||||
:param request: Request对象
|
||||
:return: 校验结果
|
||||
"""
|
||||
black_ip_value = await request.app.state.redis.get(
|
||||
f"{RedisInitKeyConfig.SYS_CONFIG.get('key')}:sys.login.blackIPList")
|
||||
black_ip_list = black_ip_value.split(',') if black_ip_value else []
|
||||
if request.headers.get('X-Forwarded-For') in black_ip_list:
|
||||
logger.warning("当前IP禁止登录")
|
||||
raise LoginException(data="", message="当前IP禁止登录")
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
async def __check_login_captcha(cls, request: Request, login_user: UserLogin):
|
||||
"""
|
||||
@@ -166,14 +182,18 @@ class LoginService:
|
||||
if query_user.get('user_basic_info') is None:
|
||||
logger.warning("用户token不合法")
|
||||
raise AuthException(data="", message="用户token不合法")
|
||||
redis_token = await request.app.state.redis.get(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}")
|
||||
# 此方法可实现同一账号同一时间只能登录一次
|
||||
# redis_token = await request.app.state.redis.get(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{user.user_basic_info.user_id}")
|
||||
if AppConfig.app_same_time_login:
|
||||
redis_token = await request.app.state.redis.get(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}")
|
||||
else:
|
||||
# 此方法可实现同一账号同一时间只能登录一次
|
||||
redis_token = await request.app.state.redis.get(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{query_user.get('user_basic_info').user_id}")
|
||||
if token == redis_token:
|
||||
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}", redis_token,
|
||||
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
# await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{user.user_basic_info.user_id}", redis_token,
|
||||
# ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
if AppConfig.app_same_time_login:
|
||||
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{session_id}", redis_token,
|
||||
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
else:
|
||||
await request.app.state.redis.set(f"{RedisInitKeyConfig.ACCESS_TOKEN.get('key')}:{query_user.get('user_basic_info').user_id}", redis_token,
|
||||
ex=timedelta(minutes=JwtConfig.jwt_redis_expire_minutes))
|
||||
|
||||
role_id_list = [item.role_id for item in query_user.get('user_role_info')]
|
||||
if 1 in role_id_list:
|
||||
@@ -209,7 +229,7 @@ class LoginService:
|
||||
:return: 当前用户路由信息对象
|
||||
"""
|
||||
query_user = UserDao.get_user_by_id(query_db, user_id=user_id)
|
||||
user_router_menu = [row for row in query_user.get('user_menu_info') if row.menu_type in ['M', 'C']]
|
||||
user_router_menu = sorted([row for row in query_user.get('user_menu_info') if row.menu_type in ['M', 'C']], key=lambda x: x.order_num)
|
||||
user_router = cls.__generate_user_router_menu(0, user_router_menu)
|
||||
return user_router
|
||||
|
||||
@@ -229,14 +249,16 @@ class LoginService:
|
||||
if permission.menu_type == 'M':
|
||||
router_list_data['name'] = permission.path.capitalize()
|
||||
router_list_data['hidden'] = False if permission.visible == '0' else True
|
||||
if permission.is_frame == 1:
|
||||
router_list_data['redirect'] = 'noRedirect'
|
||||
if permission.parent_id == 0:
|
||||
router_list_data['component'] = 'Layout'
|
||||
router_list_data['path'] = f'/{permission.path}'
|
||||
else:
|
||||
router_list_data['component'] = 'ParentView'
|
||||
router_list_data['path'] = permission.path
|
||||
if permission.is_frame == 1:
|
||||
router_list_data['redirect'] = 'noRedirect'
|
||||
else:
|
||||
router_list_data['path'] = permission.path
|
||||
if children:
|
||||
router_list_data['alwaysShow'] = True
|
||||
router_list_data['children'] = children
|
||||
@@ -249,6 +271,7 @@ class LoginService:
|
||||
elif permission.menu_type == 'C':
|
||||
router_list_data['name'] = permission.path.capitalize()
|
||||
router_list_data['path'] = permission.path
|
||||
router_list_data['query'] = permission.query
|
||||
router_list_data['hidden'] = False if permission.visible == '0' else True
|
||||
router_list_data['component'] = permission.component
|
||||
router_list_data['meta'] = {
|
||||
|
@@ -131,7 +131,7 @@ class RoleService:
|
||||
:param page_object: 角色数据权限对象
|
||||
:return: 分配角色数据权限结果
|
||||
"""
|
||||
edit_role = page_object.model_dump(exclude_unset=True)
|
||||
edit_role = page_object.model_dump(exclude_unset=True, exclude={'admin'})
|
||||
del edit_role['dept_ids']
|
||||
role_info = cls.role_detail_services(query_db, edit_role.get('role_id'))
|
||||
if role_info:
|
||||
|
@@ -206,7 +206,7 @@ class UserService:
|
||||
:param page_object: 重置用户对象
|
||||
:return: 重置用户校验结果
|
||||
"""
|
||||
reset_user = page_object.model_dump(exclude_unset=True)
|
||||
reset_user = page_object.model_dump(exclude_unset=True, exclude={'admin'})
|
||||
if page_object.old_password:
|
||||
user = UserDao.get_user_detail_by_id(query_db, user_id=page_object.user_id).get('user_basic_info')
|
||||
if not PwdUtil.verify_password(page_object.old_password, user.password):
|
||||
|
@@ -4,5 +4,5 @@ VITE_APP_TITLE = vfadmin管理系统
|
||||
# 开发环境配置
|
||||
VITE_APP_ENV = 'development'
|
||||
|
||||
# 若依管理系统/开发环境
|
||||
# vfadmin管理系统/开发环境
|
||||
VITE_APP_BASE_API = '/dev-api'
|
||||
|
@@ -4,7 +4,7 @@ VITE_APP_TITLE = vfadmin管理系统
|
||||
# 生产环境配置
|
||||
VITE_APP_ENV = 'production'
|
||||
|
||||
# 若依管理系统/生产环境
|
||||
# vfadmin管理系统/生产环境
|
||||
VITE_APP_BASE_API = '/prod-api'
|
||||
|
||||
# 是否在打包时开启压缩,支持 gzip 和 brotli
|
||||
|
@@ -1,10 +1,10 @@
|
||||
# 页面标题
|
||||
VITE_APP_TITLE = 若依管理系统
|
||||
VITE_APP_TITLE = vfadmin管理系统
|
||||
|
||||
# 生产环境配置
|
||||
VITE_APP_ENV = 'staging'
|
||||
|
||||
# 若依管理系统/生产环境
|
||||
# vfadmin管理系统/生产环境
|
||||
VITE_APP_BASE_API = '/stage-api'
|
||||
|
||||
# 是否在打包时开启压缩,支持 gzip 和 brotli
|
||||
|
@@ -7,7 +7,7 @@
|
||||
<meta name="renderer" content="webkit">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||
<link rel="icon" href="/favicon.ico">
|
||||
<title>若依管理系统</title>
|
||||
<title>vfadmin管理系统</title>
|
||||
<!--[if lt IE 11]><script>window.location.href='/html/ie.html';</script><![endif]-->
|
||||
<style>
|
||||
html,
|
||||
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "vfadmin",
|
||||
"version": "1.0.2",
|
||||
"version": "1.1.3",
|
||||
"description": "vfadmin管理系统",
|
||||
"author": "insistence",
|
||||
"license": "MIT",
|
||||
|
@@ -105,7 +105,8 @@ const registerRules = {
|
||||
],
|
||||
password: [
|
||||
{ required: true, trigger: "blur", message: "请输入您的密码" },
|
||||
{ min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }
|
||||
{ min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
|
||||
{ pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符:< > \" ' \\\ |", trigger: "blur" }
|
||||
],
|
||||
confirmPassword: [
|
||||
{ required: true, trigger: "blur", message: "请再次输入您的密码" },
|
||||
|
@@ -152,8 +152,8 @@
|
||||
</span>
|
||||
</template>
|
||||
<el-radio-group v-model="form.isFrame">
|
||||
<el-radio label="0">是</el-radio>
|
||||
<el-radio label="1">否</el-radio>
|
||||
<el-radio :label="0">是</el-radio>
|
||||
<el-radio :label="1">否</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
@@ -220,8 +220,8 @@
|
||||
</span>
|
||||
</template>
|
||||
<el-radio-group v-model="form.isCache">
|
||||
<el-radio label="0">缓存</el-radio>
|
||||
<el-radio label="1">不缓存</el-radio>
|
||||
<el-radio :label="0">缓存</el-radio>
|
||||
<el-radio :label="1">不缓存</el-radio>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
@@ -339,8 +339,8 @@ function reset() {
|
||||
icon: undefined,
|
||||
menuType: "M",
|
||||
orderNum: undefined,
|
||||
isFrame: "1",
|
||||
isCache: "0",
|
||||
isFrame: 1,
|
||||
isCache: 0,
|
||||
visible: "0",
|
||||
status: "0"
|
||||
};
|
||||
|
@@ -391,7 +391,7 @@ const data = reactive({
|
||||
rules: {
|
||||
userName: [{ required: true, message: "用户名称不能为空", trigger: "blur" }, { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" }],
|
||||
nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
|
||||
password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }],
|
||||
password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }, { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" }, { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符:< > \" ' \\\ |", trigger: "blur" }],
|
||||
email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
|
||||
phonenumber: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
|
||||
}
|
||||
@@ -494,6 +494,11 @@ function handleResetPwd(row) {
|
||||
closeOnClickModal: false,
|
||||
inputPattern: /^.{5,20}$/,
|
||||
inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
|
||||
inputValidator: (value) => {
|
||||
if (/<|>|"|'|\||\\/.test(value)) {
|
||||
return "不能包含非法字符:< > \" ' \\\ |"
|
||||
}
|
||||
},
|
||||
}).then(({ value }) => {
|
||||
resetUserPwd(row.userId, value).then(response => {
|
||||
proxy.$modal.msgSuccess("修改成功,新密码是:" + value);
|
||||
|
@@ -36,7 +36,7 @@ const equalToPassword = (rule, value, callback) => {
|
||||
};
|
||||
const rules = ref({
|
||||
oldPassword: [{ required: true, message: "旧密码不能为空", trigger: "blur" }],
|
||||
newPassword: [{ required: true, message: "新密码不能为空", trigger: "blur" }, { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }],
|
||||
newPassword: [{ required: true, message: "新密码不能为空", trigger: "blur" }, { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }, { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符:< > \" ' \\\ |", trigger: "blur" }],
|
||||
confirmPassword: [{ required: true, message: "确认密码不能为空", trigger: "blur" }, { required: true, validator: equalToPassword, trigger: "blur" }]
|
||||
});
|
||||
|
||||
|
Reference in New Issue
Block a user