|
12 | 12 | from module_admin.service.login_service import LoginService |
13 | 13 | from module_admin.service.log_service import OperationLogService, LoginLogService |
14 | 14 | from module_admin.entity.vo.log_vo import OperLogModel, LogininforModel |
| 15 | +from config.env import AppConfig |
15 | 16 |
|
16 | 17 |
|
17 | 18 | def log_decorator(title: str, business_type: int, log_type: Optional[str] = 'operation'): |
@@ -50,122 +51,126 @@ async def wrapper(*args, **kwargs): |
50 | 51 | # 获取请求的ip及ip归属区域 |
51 | 52 | oper_ip = request.headers.get("X-Forwarded-For") |
52 | 53 | oper_location = '内网IP' |
53 | | - try: |
54 | | - if oper_ip != '127.0.0.1' and oper_ip != 'localhost': |
55 | | - ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}') |
56 | | - if ip_result.status_code == 200: |
57 | | - prov = ip_result.json().get('data').get('prov') |
58 | | - city = ip_result.json().get('data').get('city') |
59 | | - if prov or city: |
60 | | - oper_location = f'{prov}-{city}' |
| 54 | + if AppConfig.app_ip_location_query: |
| 55 | + try: |
| 56 | + if oper_ip != '127.0.0.1' and oper_ip != 'localhost': |
| 57 | + ip_result = requests.get(f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={oper_ip}') |
| 58 | + if ip_result.status_code == 200: |
| 59 | + prov = ip_result.json().get('data').get('prov') |
| 60 | + city = ip_result.json().get('data').get('city') |
| 61 | + if prov or city: |
| 62 | + oper_location = f'{prov}-{city}' |
| 63 | + else: |
| 64 | + oper_location = '未知' |
61 | 65 | else: |
62 | 66 | oper_location = '未知' |
63 | | - else: |
64 | | - oper_location = '未知' |
65 | | - except Exception as e: |
66 | | - oper_location = '未知' |
67 | | - print(e) |
68 | | - finally: |
69 | | - # 根据不同的请求类型使用不同的方法获取请求参数 |
70 | | - content_type = request.headers.get("Content-Type") |
71 | | - if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type): |
72 | | - payload = await request.form() |
73 | | - oper_param = "\n".join([f"{key}: {value}" for key, value in payload.items()]) |
74 | | - else: |
75 | | - payload = await request.body() |
76 | | - # 通过 request.path_params 直接访问路径参数 |
77 | | - path_params = request.path_params |
78 | | - oper_param = {} |
79 | | - if payload: |
80 | | - oper_param.update(json.loads(str(payload, 'utf-8'))) |
81 | | - if path_params: |
82 | | - oper_param.update(path_params) |
83 | | - oper_param = json.dumps(oper_param, ensure_ascii=False) |
84 | | - # 日志表请求参数字段长度最大为2000,因此在此处判断长度 |
85 | | - if len(oper_param) > 2000: |
86 | | - oper_param = '请求参数过长' |
| 67 | + except Exception as e: |
| 68 | + oper_location = '未知' |
| 69 | + print(e) |
| 70 | + # 根据不同的请求类型使用不同的方法获取请求参数 |
| 71 | + content_type = request.headers.get("Content-Type") |
| 72 | + if content_type and ("multipart/form-data" in content_type or 'application/x-www-form-urlencoded' in content_type): |
| 73 | + payload = await request.form() |
| 74 | + oper_param = "\n".join([f"{key}: {value}" for key, value in payload.items()]) |
| 75 | + else: |
| 76 | + payload = await request.body() |
| 77 | + # 通过 request.path_params 直接访问路径参数 |
| 78 | + path_params = request.path_params |
| 79 | + oper_param = {} |
| 80 | + if payload: |
| 81 | + oper_param.update(json.loads(str(payload, 'utf-8'))) |
| 82 | + if path_params: |
| 83 | + oper_param.update(path_params) |
| 84 | + oper_param = json.dumps(oper_param, ensure_ascii=False) |
| 85 | + # 日志表请求参数字段长度最大为2000,因此在此处判断长度 |
| 86 | + if len(oper_param) > 2000: |
| 87 | + oper_param = '请求参数过长' |
87 | 88 |
|
88 | | - # 获取操作时间 |
89 | | - oper_time = datetime.now() |
90 | | - # 此处在登录之前向原始函数传递一些登录信息,用于监测在线用户的相关信息 |
91 | | - login_log = {} |
92 | | - if log_type == 'login': |
93 | | - user_agent_info = parse(user_agent) |
94 | | - browser = f'{user_agent_info.browser.family} {user_agent_info.browser.version[0]}' |
95 | | - system_os = f'{user_agent_info.os.family} {user_agent_info.os.version[0]}' |
96 | | - login_log = dict( |
97 | | - ipaddr=oper_ip, |
98 | | - loginLocation=oper_location, |
99 | | - browser=browser, |
100 | | - os=system_os, |
101 | | - loginTime=oper_time.strftime('%Y-%m-%d %H:%M:%S') |
102 | | - ) |
103 | | - kwargs['form_data'].login_info = login_log |
104 | | - # 调用原始函数 |
105 | | - result = await func(*args, **kwargs) |
106 | | - # 获取请求耗时 |
107 | | - cost_time = float(time.time() - start_time) * 100 |
108 | | - # 判断请求是否来自api文档 |
109 | | - request_from_swagger = request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False |
110 | | - request_from_redoc = request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False |
111 | | - # 根据响应结果的类型使用不同的方法获取响应结果参数 |
112 | | - if isinstance(result, JSONResponse) or isinstance(result, ORJSONResponse) or isinstance(result, UJSONResponse): |
113 | | - result_dict = json.loads(str(result.body, 'utf-8')) |
| 89 | + # 获取操作时间 |
| 90 | + oper_time = datetime.now() |
| 91 | + # 此处在登录之前向原始函数传递一些登录信息,用于监测在线用户的相关信息 |
| 92 | + login_log = {} |
| 93 | + if log_type == 'login': |
| 94 | + user_agent_info = parse(user_agent) |
| 95 | + browser = f'{user_agent_info.browser.family}' |
| 96 | + system_os = f'{user_agent_info.os.family}' |
| 97 | + if user_agent_info.browser.version != (): |
| 98 | + browser += f' {user_agent_info.browser.version[0]}' |
| 99 | + if user_agent_info.os.version != (): |
| 100 | + system_os += f' {user_agent_info.os.version[0]}' |
| 101 | + login_log = dict( |
| 102 | + ipaddr=oper_ip, |
| 103 | + loginLocation=oper_location, |
| 104 | + browser=browser, |
| 105 | + os=system_os, |
| 106 | + loginTime=oper_time.strftime('%Y-%m-%d %H:%M:%S') |
| 107 | + ) |
| 108 | + kwargs['form_data'].login_info = login_log |
| 109 | + # 调用原始函数 |
| 110 | + result = await func(*args, **kwargs) |
| 111 | + # 获取请求耗时 |
| 112 | + cost_time = float(time.time() - start_time) * 100 |
| 113 | + # 判断请求是否来自api文档 |
| 114 | + request_from_swagger = request.headers.get('referer').endswith('docs') if request.headers.get('referer') else False |
| 115 | + request_from_redoc = request.headers.get('referer').endswith('redoc') if request.headers.get('referer') else False |
| 116 | + # 根据响应结果的类型使用不同的方法获取响应结果参数 |
| 117 | + if isinstance(result, JSONResponse) or isinstance(result, ORJSONResponse) or isinstance(result, UJSONResponse): |
| 118 | + result_dict = json.loads(str(result.body, 'utf-8')) |
| 119 | + else: |
| 120 | + if request_from_swagger or request_from_redoc: |
| 121 | + result_dict = {} |
114 | 122 | else: |
115 | | - if request_from_swagger or request_from_redoc: |
116 | | - result_dict = {} |
| 123 | + if result.status_code == 200: |
| 124 | + result_dict = {'code': result.status_code, 'message': '获取成功'} |
117 | 125 | else: |
118 | | - if result.status_code == 200: |
119 | | - result_dict = {'code': result.status_code, 'message': '获取成功'} |
120 | | - else: |
121 | | - result_dict = {'code': result.status_code, 'message': '获取失败'} |
122 | | - json_result = json.dumps(result_dict, ensure_ascii=False) |
123 | | - # 根据响应结果获取响应状态及异常信息 |
124 | | - status = 1 |
125 | | - error_msg = '' |
126 | | - if result_dict.get('code') == 200: |
127 | | - status = 0 |
| 126 | + result_dict = {'code': result.status_code, 'message': '获取失败'} |
| 127 | + json_result = json.dumps(result_dict, ensure_ascii=False) |
| 128 | + # 根据响应结果获取响应状态及异常信息 |
| 129 | + status = 1 |
| 130 | + error_msg = '' |
| 131 | + if result_dict.get('code') == 200: |
| 132 | + status = 0 |
| 133 | + else: |
| 134 | + error_msg = result_dict.get('msg') |
| 135 | + # 根据日志类型向对应的日志表插入数据 |
| 136 | + if log_type == 'login': |
| 137 | + # 登录请求来自于api文档时不记录登录日志,其余情况则记录 |
| 138 | + if request_from_swagger or request_from_redoc: |
| 139 | + pass |
128 | 140 | else: |
129 | | - error_msg = result_dict.get('msg') |
130 | | - # 根据日志类型向对应的日志表插入数据 |
131 | | - if log_type == 'login': |
132 | | - # 登录请求来自于api文档时不记录登录日志,其余情况则记录 |
133 | | - if request_from_swagger or request_from_redoc: |
134 | | - pass |
135 | | - else: |
136 | | - user = kwargs.get('form_data') |
137 | | - user_name = user.username |
138 | | - login_log['loginTime'] = oper_time |
139 | | - login_log['userName'] = user_name |
140 | | - login_log['status'] = str(status) |
141 | | - login_log['msg'] = result_dict.get('msg') |
| 141 | + user = kwargs.get('form_data') |
| 142 | + user_name = user.username |
| 143 | + login_log['loginTime'] = oper_time |
| 144 | + login_log['userName'] = user_name |
| 145 | + login_log['status'] = str(status) |
| 146 | + login_log['msg'] = result_dict.get('msg') |
142 | 147 |
|
143 | | - LoginLogService.add_login_log_services(query_db, LogininforModel(**login_log)) |
144 | | - else: |
145 | | - current_user = await LoginService.get_current_user(request, token, query_db) |
146 | | - oper_name = current_user.user.user_name |
147 | | - dept_name = current_user.user.dept.dept_name if current_user.user.dept else None |
148 | | - operation_log = OperLogModel( |
149 | | - title=title, |
150 | | - businessType=business_type, |
151 | | - method=func_path, |
152 | | - requestMethod=request_method, |
153 | | - operatorType=operator_type, |
154 | | - operName=oper_name, |
155 | | - deptName=dept_name, |
156 | | - operUrl=oper_url, |
157 | | - operIp=oper_ip, |
158 | | - operLocation=oper_location, |
159 | | - operParam=oper_param, |
160 | | - jsonResult=json_result, |
161 | | - status=status, |
162 | | - errorMsg=error_msg, |
163 | | - operTime=oper_time, |
164 | | - costTime=int(cost_time) |
165 | | - ) |
166 | | - OperationLogService.add_operation_log_services(query_db, operation_log) |
| 148 | + LoginLogService.add_login_log_services(query_db, LogininforModel(**login_log)) |
| 149 | + else: |
| 150 | + current_user = await LoginService.get_current_user(request, token, query_db) |
| 151 | + oper_name = current_user.user.user_name |
| 152 | + dept_name = current_user.user.dept.dept_name if current_user.user.dept else None |
| 153 | + operation_log = OperLogModel( |
| 154 | + title=title, |
| 155 | + businessType=business_type, |
| 156 | + method=func_path, |
| 157 | + requestMethod=request_method, |
| 158 | + operatorType=operator_type, |
| 159 | + operName=oper_name, |
| 160 | + deptName=dept_name, |
| 161 | + operUrl=oper_url, |
| 162 | + operIp=oper_ip, |
| 163 | + operLocation=oper_location, |
| 164 | + operParam=oper_param, |
| 165 | + jsonResult=json_result, |
| 166 | + status=status, |
| 167 | + errorMsg=error_msg, |
| 168 | + operTime=oper_time, |
| 169 | + costTime=int(cost_time) |
| 170 | + ) |
| 171 | + OperationLogService.add_operation_log_services(query_db, operation_log) |
167 | 172 |
|
168 | | - return result |
| 173 | + return result |
169 | 174 |
|
170 | 175 | return wrapper |
171 | 176 |
|
|
0 commit comments