diff --git a/mg/handlers/business_v4_handler.py b/mg/handlers/business_v4_handler.py index ccca220..019e33b 100644 --- a/mg/handlers/business_v4_handler.py +++ b/mg/handlers/business_v4_handler.py @@ -15,7 +15,8 @@ from libs.base_handler import BaseHandler from websdk2.db_context import DBContextV2 as DBContext from models.paas_model import BizModel -from services.biz_service import opt_obj, get_biz_list_for_api, get_biz_list_v3, sync_biz_role_user +from services.biz_service import opt_obj, get_biz_list_for_api, get_biz_list_v3, sync_biz_role_user, get_biz_map, \ + switch_business, get_biz_list_v4 class BusinessHandler(BaseHandler, ABC): @@ -64,7 +65,7 @@ def delete(self): self.write(res) - +# TODO 待废弃 class BusinessListHandler(BaseHandler, ABC): def check_xsrf_cookie(self): @@ -74,25 +75,13 @@ def prepare(self): self.get_params_dict() self.codo_login() - @staticmethod - def get_biz_map(view_biz, request_tenantid): - if request_tenantid: - # 使用 next() 寻找第一个匹配的业务,如果没有找到则返回 None - the_biz = next((biz for biz in view_biz if biz.get('biz_id') == request_tenantid), None) - else: - # 使用列表推导式过滤出不包含指定 biz_id 的业务列表 - the_biz_list = [biz for biz in view_biz if biz.get('biz_id') not in ['501', '502']] - the_biz = the_biz_list[0] if the_biz_list else None - - return dict(biz_cn_name=the_biz.get('biz_cn_name'), biz_id=the_biz.get('biz_id')) if the_biz else None - def get(self): self.params['is_superuser'] = self.request_is_superuser self.params['user_id'] = self.request_user_id view_biz = get_biz_list_v3(**self.params) try: - the_biz_map = self.get_biz_map(view_biz, self.request_tenantid) + the_biz_map = get_biz_map(view_biz, self.request_tenantid) if not the_biz_map: the_biz_map = dict(biz_cn_name='默认项目', biz_id='502') except Exception as err: @@ -101,32 +90,6 @@ def get(self): self.write(dict(code=0, msg="获取成功", data=view_biz, the_biz_map=the_biz_map)) - # def get(self): - # self.params['is_superuser'] = self.request_is_superuser - # self.params['user_id'] = self.request_user_id - # # self.params['user'] = self.request_fullname() - # view_biz = get_biz_list_v3(**self.params) - # - # the_biz_map = dict() - # try: - # if self.request_tenantid: - # the_biz_list = list(filter(lambda x: x.get('biz_id') == self.request_tenantid, view_biz)) - # if the_biz_list and isinstance(the_biz_list, list) and len(the_biz_list) == 1: - # the_biz = the_biz_list[0] - # the_biz_map = dict(biz_cn_name=the_biz.get('biz_cn_name'), biz_id=the_biz.get('biz_id')) - # else: - # the_biz_list = list(filter(lambda x: x.get('biz_id') not in ['501', '502'], view_biz)) - # if the_biz_list and isinstance(the_biz_list, list) and len(the_biz_list) >= 1: - # the_biz = the_biz_list[0] - # the_biz_map = dict(biz_cn_name=the_biz.get('biz_cn_name'), biz_id=the_biz.get('biz_id')) - # except Exception as err: - # logging.error(f'业务列表 请求错误, {err}') - # - # if not the_biz_map: - # the_biz_map = dict(biz_cn_name='默认项目', biz_id='502') - # - # self.write(dict(code=0, msg="获取成功", data=view_biz, the_biz_map=the_biz_map)) - def patch(self): # 手动切换 前端记录 data = json.loads(self.request.body.decode("utf-8")) @@ -150,51 +113,39 @@ def patch(self): return self.write(dict(code=0, msg="获取成功", data=biz_dict)) -# class BusinessTreeHandler(BaseHandler, ABC): -# -# def check_xsrf_cookie(self): -# pass -# -# def prepare(self): -# self.get_params_dict() -# self.codo_login() -# -# def get(self): -# self.params['is_superuser'] = self.request_is_superuser -# self.params['user'] = str(self.request_user_id) -# tree_data = get_biz_tree(**self.params) -# return self.write(dict(code=0, msg="获取成功", data=tree_data)) - - -# class TenantHandler(BaseHandler, ABC): -# def get(self): -# res = get_tenant_list_for_api(**self.params) -# self.write(res) -# -# def post(self): -# data = json.loads(self.request.body.decode("utf-8")) -# res = opt_obj2.handle_add(data) -# -# self.write(res) -# -# def put(self): -# data = json.loads(self.request.body.decode("utf-8")) -# res = opt_obj2.handle_update(data) -# -# self.write(res) -# -# def delete(self): -# data = json.loads(self.request.body.decode("utf-8")) -# res = opt_obj2.handle_delete(data) -# -# self.write(res) +class BizListNaHandler(BaseHandler, ABC): + + def get(self): + self.params['is_superuser'] = self.request_is_superuser + self.params['user_id'] = self.request_user_id + view_biz = get_biz_list_v4(**self.params) + + try: + the_biz_map = get_biz_map(view_biz, self.request_tenantid) + if not the_biz_map: + the_biz_map = dict(biz_cn_name='默认项目', biz_id='502') + except Exception as err: + logging.error(f'Error fetching business list: {err}') + the_biz_map = dict(biz_cn_name='默认项目', biz_id='502') + + self.write(dict(code=0, msg="获取成功", data=view_biz, the_biz_map=the_biz_map)) + + +class BizChangeNaHandler(BaseHandler, ABC): + + def get(self): + self.params['is_superuser'] = self.request_is_superuser + self.params['user_id'] = self.request_user_id + res = switch_business(self.set_secure_cookie, **self.params) + + return self.write(res) biz_v4_mg_urls = [ (r"/v4/biz/", BusinessHandler, {"handle_name": "权限中心-业务管理", "method": ["ALL"]}), - # (r"/v4/tenant/", TenantHandler, {"handle_name": "权限中心-租户管理"}), (r"/v4/biz/list/", BusinessListHandler, {"handle_name": "PAAS基础功能-查看业务列表和切换", "method": ["GET"]}), - # (r"/v4/biz/tree/", BusinessTreeHandler, {"handle_name": "权限中心-业务树"}), + (r"/v4/na/biz/list/", BizListNaHandler, {"handle_name": "PAAS-基础功能-免认证查看业务列表", "method": ["GET"]}), + (r"/v4/na/biz/change/", BizChangeNaHandler, {"handle_name": "PAAS-基础功能-免认证切换业务", "method": ["GET"]}) ] if __name__ == "__main__": pass diff --git a/services/biz_service.py b/services/biz_service.py index 17804e7..977ac6a 100644 --- a/services/biz_service.py +++ b/services/biz_service.py @@ -4,12 +4,12 @@ Version : 0.0.1 Contact : 191715030@qq.com Author : shenshuo -Date : 2020/12/10 15:14 -Desc : 解释一下吧 +Date : 2024/12/6 15:14 +Desc : 业务数据 """ import json - +import logging from sqlalchemy import or_ from websdk2.cache_context import cache_conn from websdk2.db_context import DBContextV2 as DBContext @@ -23,9 +23,6 @@ opt_obj = CommonOptView(BizModel) -# opt_obj2 = CommonOptView(TenantModel) - - def _get_biz_value(value: str = None): if not value: return True @@ -80,6 +77,7 @@ def add_init_default(): return +# TODO 待废弃 def get_biz_list_v3(**params): params['page_size'] = 300 # 默认获取到全部数据 is_superuser = params.get('is_superuser') @@ -87,15 +85,47 @@ def get_biz_list_v3(**params): with DBContext('r') as session: queryset = session.query(BizModel).filter(BizModel.life_cycle != "停运").all() - view_biz_list = [] - for b in queryset: - if is_superuser or b.biz_id in ['501', '502'] or str(user_id) in b.users_info: - view_biz_list.append( - dict(id=b.id, biz_id=b.biz_id, biz_cn_name=b.biz_cn_name, biz_en_name=b.biz_en_name)) + view_biz_list = [] + for b in queryset: + if is_superuser or b.biz_id in ['501', '502'] or str(user_id) in b.users_info: + view_biz_list.append( + dict(id=b.id, biz_id=b.biz_id, biz_cn_name=b.biz_cn_name, biz_en_name=b.biz_en_name)) # print(view_biz_list) return view_biz_list +def get_biz_list_v4(**params): + try: + params['page_size'] = 300 # 默认获取到全部数据 + is_superuser = params.get('is_superuser') + user_id = params.get('user_id') + + # 使用数据库上下文进行查询,并且在查询时加入过滤条件,减少无用数据的传输 + with DBContext('r') as session: + # 过滤掉停运的业务,确保只处理有效的业务 + queryset = session.query(BizModel).filter(BizModel.life_cycle != "停运").all() + + # 构建返回的业务列表 + view_biz_list = [ + dict(id=b.id, biz_id=b.biz_id, biz_cn_name=b.biz_cn_name, biz_en_name=b.biz_en_name) + for b in queryset + if can_view_biz(is_superuser, user_id, b) + ] + + return view_biz_list + + except Exception as err: + logging.error(f"Error occurred in get_biz_list_v4: {err}") + return {"code": -1, "msg": "服务器内部错误"} + + +def can_view_biz(is_superuser, user_id, biz_model): + """ + Helper function to determine if the user has permission to view the business. + """ + # Check if the user is a superuser or has access to the business + return is_superuser or biz_model.biz_id in ['501', '502'] or str(user_id) in biz_model.users_info + # def get_biz_tree(**params) -> list: # # TODO 后续补充权限 # the_tree = [] @@ -189,3 +219,57 @@ def sync_biz_role_user(**params): session.bulk_update_mappings(BizModel, new_data) session.commit() + + +def get_biz_map(view_biz, request_tenant_id) -> dict: + if request_tenant_id: + # 使用 next() 寻找第一个匹配的业务,如果没有找到则返回 None + the_biz = next((biz for biz in view_biz if biz.get('biz_id') == request_tenant_id), None) + else: + # 使用列表推导式过滤出不包含指定 biz_id 的业务列表 + the_biz_list = [biz for biz in view_biz if biz.get('biz_id') not in ['501', '502']] + the_biz = the_biz_list[0] if the_biz_list else None + + return dict(biz_cn_name=the_biz.get('biz_cn_name'), biz_id=the_biz.get('biz_id')) if the_biz else None + + +def switch_business(set_secure_cookie, **params) -> dict: + biz_id = params.get('biz_id') or params.get('tenantid') + is_superuser = params.get('is_superuser') + user_id = params.get('user_id') + + # 参数验证 + if not biz_id: + return {"code": -1, "msg": "缺少必要参数"} + + # 封装数据库查询和权限检查 + try: + with DBContext('r') as session: + biz_info = session.query(BizModel).filter(BizModel.biz_id == str(biz_id)).first() + + # 业务信息检查 + if not biz_info: + return {"code": -2, "msg": "未知业务信息/资源组信息"} + # 权限检查,是否为超级用户或该用户是否在业务信息中 + if is_superuser or user_id in biz_info.users_info: + return {"code": -3, "msg": "你没有访问的业务权限,请联系管理员"} + + except Exception as db_err: + logging.error(f"数据库查询失败: {db_err}") + return {"code": -4, "msg": "数据库操作失败"} + + # 设置cookie + try: + set_secure_cookie("biz_id", str(biz_info.biz_id)) + except Exception as err: + logging.error(f"设置 cookie 失败: {err}") + return {"code": -5, "msg": "设置 cookie 失败"} + + # 返回业务数据 + biz_dict = { + "biz_id": str(biz_info.biz_id), + "biz_cn_name": str(biz_info.biz_cn_name), + "biz_en_name": biz_info.biz_en_name + } + + return {"code": 0, "msg": "获取成功", "data": biz_dict} diff --git a/services/user_services.py b/services/user_services.py index 12ef2a0..fd0ba08 100644 --- a/services/user_services.py +++ b/services/user_services.py @@ -4,16 +4,14 @@ Version : 0.0.1 Contact : 191715030@qq.com Author : shenshuo -Date : 2020/12/10 15:14 +Date : 2024/12/06 15:14 Desc : 解释一下吧 """ -from sqlalchemy import or_, and_, func, desc, case +from sqlalchemy import or_ from websdk2.db_context import DBContextV2 as DBContext from websdk2.sqlalchemy_pagination import paginate -# from models.authority_model import Roles, UserRoles, Groups, UserGroups, GroupRoles -from models.authority import Users, Roles, UserRoles -# from websdk2.model_utils import CommonOptView +from models.authority import Users, UserRoles from libs.feature_model_utils import CommonOptView opt_obj = CommonOptView(Users)