diff --git a/backend/app/api/v1/services/system/auth_service.py b/backend/app/api/v1/services/system/auth_service.py index a6ac6889..6431419c 100644 --- a/backend/app/api/v1/services/system/auth_service.py +++ b/backend/app/api/v1/services/system/auth_service.py @@ -84,7 +84,7 @@ class LoginService: # 创建token token = await cls.create_token_service(redis=redis, username=user.username) user_agent = parse(request.headers.get("user-agent")) - + login_location = await IpLocalUtil.get_ip_location(request.client.host) # 缓存中构建在线用户信息 await RedisCURD(redis).set( key=f"{RedisInitKeyConfig.ONLINE_USER.key}:{user.username}", @@ -94,7 +94,7 @@ class LoginService: name=user.name, user_name=user.username, ipaddr=request.client.host, - login_location=IpLocalUtil.get_ip_location(request.client.host), + login_location=login_location, os=user_agent.os.family, browser = user_agent.browser.family, login_time=user.last_login diff --git a/backend/app/core/router_class.py b/backend/app/core/router_class.py index e5393cbc..d6ad201f 100644 --- a/backend/app/core/router_class.py +++ b/backend/app/core/router_class.py @@ -69,11 +69,7 @@ class OperationLogRoute(APIRoute): current_user_id = request.scope.get("user_id") if request.url.path == '/api/v1/system/auth/login': # 只有登录的才会获取登录地址 - if request.client.host == '36.163.173.156': - logger.info(f'{request.client.host} 等于 36.163.173.156') - else: - logger.error(f'{request.client.host} 不等于 36.163.173.156') - login_location = IpLocalUtil.get_ip_location(request.client.host) + login_location = await IpLocalUtil.get_ip_location(request.client.host) await OperationLogService.create_log_service(data=OperationLogCreateSchema( request_path = request.url.path, diff --git a/backend/app/utils/ip_local_util.py b/backend/app/utils/ip_local_util.py index 0776c0b6..9c1c8afd 100644 --- a/backend/app/utils/ip_local_util.py +++ b/backend/app/utils/ip_local_util.py @@ -23,7 +23,7 @@ class IpLocalUtil: return bool(re.match(ip_pattern, ip)) @classmethod - def get_ip_location(cls, ip: str) -> str: + async def get_ip_location(cls, ip: str) -> str: """ 获取IP归属地信息 @@ -47,9 +47,10 @@ class IpLocalUtil: f'https://qifu-api.baidubce.com/ip/geo/v1/district?ip={ip}', timeout=5 ) - if ip_result.status_code == 200: + result = ip_result.json() + if result['code']== 'Success': - data = ip_result.json().get('data', {}) + data = result['data'] logger.info(f"获取IP归属地成功: {data}") # "continent": "亚洲", # "country": "中国", @@ -60,12 +61,11 @@ class IpLocalUtil: # "prov": "陕西省", # "city": "西安市", # "district": "雁塔区" - country = data.get('country', '未知国家') - owner = data.get('owner', '未知运营商') - prov = data.get('prov', '未知省份') - city = data.get('city', '未知城市') - district = data.get('district', '未知地区') - + country = data['country'] + owner = data['owner'] + prov = data['prov'] + city = data['city'] + district = data['district'] return f'【{owner}】-{country}-{prov}-{city}-{district}' except Exception as e: