diff --git a/README.md b/README.md index f65dead3d4a71999e53d029255c9dd84a950edcd..f012002fd0780d8f36ebbda61b3f581cad329a8b 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@
-
+
@@ -15,9 +15,10 @@
+
## 平台简介
-RuoYi-Vue-FastAPI是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
+RuoYi-Vue3-FastAPI是一套全部开源的快速开发平台,毫无保留给个人及企业免费使用。
* 前端采用Vue、Element Plus,基于[RuoYi-Vue3](https://github.com/yangzongzhuan/RuoYi-Vue3)前端项目修改。
* 后端采用FastAPI、sqlalchemy、MySQL、Redis、OAuth2 & Jwt。
diff --git a/ruoyi-fastapi-backend/.env.dev b/ruoyi-fastapi-backend/.env.dev
index cbfee4e7c136e396cc79721284dc3bf511490a1e..27c0e220e58dbb59f97d03c3585bb815ced518a5 100644
--- a/ruoyi-fastapi-backend/.env.dev
+++ b/ruoyi-fastapi-backend/.env.dev
@@ -10,9 +10,13 @@ APP_HOST = '0.0.0.0'
# 应用端口
APP_PORT = 9099
# 应用版本
-APP_VERSION= '1.0.3'
+APP_VERSION= '1.1.0'
# 应用是否开启热重载
APP_RELOAD = true
+# 应用是否开启IP归属区域查询
+APP_IP_LOCATION_QUERY = true
+# 应用是否允许账号同时登录
+APP_SAME_TIME_LOGIN = true
# -------- Jwt配置 --------
# Jwt秘钥
@@ -36,6 +40,8 @@ DB_USERNAME = 'root'
DB_PASSWORD = 'mysqlroot'
# 数据库名称
DB_DATABASE = 'ruoyi-fastapi'
+# 是否开启sqlalchemy日志
+DB_ECHO = true
# -------- Redis配置 --------
# Redis主机
diff --git a/ruoyi-fastapi-backend/.env.prod b/ruoyi-fastapi-backend/.env.prod
index 75f65aa67aac6d644db766f6121d608e3459e245..2bc3aca07bff5ffbb4dcf40872813054d43d89fc 100644
--- a/ruoyi-fastapi-backend/.env.prod
+++ b/ruoyi-fastapi-backend/.env.prod
@@ -10,9 +10,13 @@ APP_HOST = '0.0.0.0'
# 应用端口
APP_PORT = 9099
# 应用版本
-APP_VERSION= '1.0.3'
+APP_VERSION= '1.1.0'
# 应用是否开启热重载
APP_RELOAD = false
+# 应用是否开启IP归属区域查询
+APP_IP_LOCATION_QUERY = true
+# 应用是否允许账号同时登录
+APP_SAMETIME_LOGIN = true
# -------- Jwt配置 --------
# Jwt秘钥
@@ -36,6 +40,8 @@ DB_USERNAME = 'root'
DB_PASSWORD = 'root'
# 数据库名称
DB_DATABASE = 'ruoyi-fastapi'
+# 是否开启sqlalchemy日志
+DB_ECHO = true
# -------- Redis配置 --------
# Redis主机
diff --git a/ruoyi-fastapi-backend/config/database.py b/ruoyi-fastapi-backend/config/database.py
index 8d2012fbcd07067aacb69682876e474444058ace..4f00f8b73d941698ad19824c8eed134ba2afc1d9 100644
--- a/ruoyi-fastapi-backend/config/database.py
+++ b/ruoyi-fastapi-backend/config/database.py
@@ -8,7 +8,7 @@ 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
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
diff --git a/ruoyi-fastapi-backend/config/env.py b/ruoyi-fastapi-backend/config/env.py
index 224a2708a0292022bc1fd874b6556a3952053a9c..236b53ea8b7aad97dee4eb10fe3041e950a7d179 100644
--- a/ruoyi-fastapi-backend/config/env.py
+++ b/ruoyi-fastapi-backend/config/env.py
@@ -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,7 @@ class DataBaseSettings(BaseSettings):
db_username: str = 'root'
db_password: str = 'mysqlroot'
db_database: str = 'ruoyi-fastapi'
+ db_echo: bool = True
class RedisSettings(BaseSettings):
diff --git a/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py b/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py
index 13131f88d6b22c72b5c883bf2904ae52611b6a77..079bfd0f2720e8e43e075733ab842afbf653cfb5 100644
--- a/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py
+++ b/ruoyi-fastapi-backend/module_admin/annotation/log_annotation.py
@@ -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,122 +51,126 @@ 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}'
+ if AppConfig.app_ip_location_query:
+ 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 = '未知'
- 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 = '请求参数过长'
+ except Exception as e:
+ oper_location = '未知'
+ print(e)
+ # 根据不同的请求类型使用不同的方法获取请求参数
+ 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
diff --git a/ruoyi-fastapi-backend/module_admin/controller/login_controller.py b/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
index a036862a4dbba5406fe8f4f1a970e99bdbad5114..2b8b271179f8c0664423aaf329bec32cf1783fb1 100644
--- a/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
+++ b/ruoyi-fastapi-backend/module_admin/controller/login_controller.py
@@ -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('退出成功')
diff --git a/ruoyi-fastapi-backend/module_admin/service/login_service.py b/ruoyi-fastapi-backend/module_admin/service/login_service.py
index cfb6d90e53db0d06dfb5bced2edf30a55d4df0a3..d509a3077518c6bc838fae045f95b47403ce83c6 100644
--- a/ruoyi-fastapi-backend/module_admin/service/login_service.py
+++ b/ruoyi-fastapi-backend/module_admin/service/login_service.py
@@ -182,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:
diff --git a/ruoyi-fastapi-frontend/.env.development b/ruoyi-fastapi-frontend/.env.development
index bdde46ff4913a32284e8276c604a4b5298af9e7e..a086d04f20937a7ebffda817dc0507fbe764d6bc 100644
--- a/ruoyi-fastapi-frontend/.env.development
+++ b/ruoyi-fastapi-frontend/.env.development
@@ -4,5 +4,5 @@ VITE_APP_TITLE = vfadmin管理系统
# 开发环境配置
VITE_APP_ENV = 'development'
-# 若依管理系统/开发环境
+# vfadmin管理系统/开发环境
VITE_APP_BASE_API = '/dev-api'
diff --git a/ruoyi-fastapi-frontend/.env.production b/ruoyi-fastapi-frontend/.env.production
index 4a47787d82e5828f085c7fe4f0d705d09172b20a..ac80031b54463541d6565ae7fd180113f9204f1e 100644
--- a/ruoyi-fastapi-frontend/.env.production
+++ b/ruoyi-fastapi-frontend/.env.production
@@ -4,7 +4,7 @@ VITE_APP_TITLE = vfadmin管理系统
# 生产环境配置
VITE_APP_ENV = 'production'
-# 若依管理系统/生产环境
+# vfadmin管理系统/生产环境
VITE_APP_BASE_API = '/prod-api'
# 是否在打包时开启压缩,支持 gzip 和 brotli
diff --git a/ruoyi-fastapi-frontend/.env.staging b/ruoyi-fastapi-frontend/.env.staging
index b11336dbf2be1d7c121feff9097c3cf572d23756..c3fcf1a9a0aac916fadbd2210f9655e3471ec9ca 100644
--- a/ruoyi-fastapi-frontend/.env.staging
+++ b/ruoyi-fastapi-frontend/.env.staging
@@ -1,10 +1,10 @@
# 页面标题
-VITE_APP_TITLE = 若依管理系统
+VITE_APP_TITLE = vfadmin管理系统
# 生产环境配置
VITE_APP_ENV = 'staging'
-# 若依管理系统/生产环境
+# vfadmin管理系统/生产环境
VITE_APP_BASE_API = '/stage-api'
# 是否在打包时开启压缩,支持 gzip 和 brotli
diff --git a/ruoyi-fastapi-frontend/index.html b/ruoyi-fastapi-frontend/index.html
index d20d02e553c166a83ccb109fd3d3704b754e7f61..ab221b8c192361bfd79bc895f91da8dc26e5c687 100644
--- a/ruoyi-fastapi-frontend/index.html
+++ b/ruoyi-fastapi-frontend/index.html
@@ -7,7 +7,7 @@
-