def verify(self, request): """权限判断接口,前端使用""" # serializer在设置字段required为false时,如果参数为None,会提示字段为null if not request.data.get('resource_code'): request.data.pop('resource_code', '') serializer = serializers.PermVerifySLZ(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) data = serializer.data resource_code = data.get('resource_code') resource_name = data.get('resource_name') is_raise = data.get('is_raise') self.get_project_info(request, data['project_id']) try: perm = bcs_perm.get_perm_cls(data['resource_type'], request, data['project_id'], resource_code, resource_name) except (AttributeError, TypeError): raise APIError(_("resource_code不合法")) handler = getattr(perm, 'can_%s' % data['policy_code']) if handler: try: handler(raise_exception=True) except NoAuthPermError as error: if is_raise: raise VerifyAuthPermError(error.args[0], error.args[1]) else: raise VerifyAuthPermErrorWithNoRaise( error.args[0], error.args[1]) return APIResult({}, _("验证权限成功"))
def get_paginated_response(self, data): data = OrderedDict([('count', self.count), ('next', self.get_next_link()), ('previous', self.get_previous_link()), ('results', data)]) # 按约定返回数据格式, message需要对象指定赋值 return APIResult(data, message=getattr(self.view, 'message', ''))
def verify_multi(self, request): """权限判断接口,前端使用, 批量接口 """ serializer = serializers.PermMultiVerifySLZ(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) data = serializer.data operator = data['operator'] msg = '' err_data = [] self.get_project_info(request, data['project_id']) for res in data['resource_list']: resource_code = res.get('resource_code') resource_name = res.get('resource_name') try: perm = bcs_perm.get_perm_cls( res['resource_type'], request, data['project_id'], resource_code, resource_name) except (AttributeError, TypeError): raise APIError(_("resource_code不合法")) handler = getattr(perm, 'can_%s' % res['policy_code']) try: if handler: handler(raise_exception=True) except bcs_perm.NoAuthPermError as error: msg = msg or error.args[0] err_data.extend(error.args[1]) if len(data['resource_list']) == 1 and err_data: raise VerifyAuthPermError(msg, err_data) elif operator == constants.PermMultiOperator.AND.value and err_data: raise VerifyAuthPermError(msg, err_data) elif operator == constants.PermMultiOperator.OR.value and len(data['resource_list']) == len(err_data): raise VerifyAuthPermError(msg, err_data) return APIResult({}, _("验证权限成功"))
def list(self, request, project_id): """命名空间列表 权限控制: 必须有对应集群的使用权限 """ access_token = request.user.token.access_token valid_group_by = ['env_type', 'cluster_id', 'cluster_name'] group_by = request.GET.get('group_by') cluster_id = request.GET.get('cluster_id') with_lb = request.GET.get('with_lb', 0) # 过滤有使用权限的命名空间 perm_can_use = request.GET.get('perm_can_use') if perm_can_use == '1': perm_can_use = True else: perm_can_use = False # 获取全部namespace,前台分页 result = paas_cc.get_namespace_list(access_token, project_id, with_lb=with_lb, limit=constants.ALL_LIMIT) if result.get('code') != 0: raise error_codes.APIError.f(result.get('message', '')) results = result["data"]["results"] or [] # 针对k8s集群过滤掉系统和平台命名空间 if request.project.kind == ProjectKind.K8S.value: results = self._ignore_ns_for_k8s(results) # 是否有创建权限 perm = bcs_perm.Namespace(request, project_id, bcs_perm.NO_RES) can_create = perm.can_create(raise_exception=False) # 补充cluster_name字段 cluster_list = get_clusters(access_token, project_id) # TODO: 后续发现cluster_id不存在时,再处理 cluster_dict = {i["cluster_id"]: i for i in (cluster_list or [])} # no_vars=1 不显示变量 no_vars = request.GET.get('no_vars') if no_vars == '1': project_var = [] else: project_var = NameSpaceVariable.get_project_ns_vars(project_id) for i in results: # ns_vars = NameSpaceVariable.get_ns_vars(i['id'], project_id) ns_id = i['id'] ns_vars = [] for _var in project_var: _ns_values = _var['ns_values'] _ns_value_ids = _ns_values.keys() ns_vars.append({ 'id': _var['id'], 'key': _var['key'], 'name': _var['name'], 'value': _ns_values.get(ns_id) if ns_id in _ns_value_ids else _var['default_value'], }) i['ns_vars'] = ns_vars if i['cluster_id'] in cluster_dict: i['cluster_name'] = cluster_dict[i['cluster_id']]['name'] i['environment'] = cluster_dict[i['cluster_id']]['environment'] else: i['cluster_name'] = i['cluster_id'] i['environment'] = None # 添加permissions到数据中 results = perm.hook_perms(results, perm_can_use) if cluster_id: results = filter(lambda x: x['cluster_id'] == cluster_id, results) if group_by and group_by in valid_group_by: # 分组, 排序 results = [{ 'name': k, 'results': sorted(list(v), key=lambda x: x['id'], reverse=True) } for k, v in groupby(sorted(results, key=lambda x: x[group_by]), key=lambda x: x[group_by])] if group_by == 'env_type': ordering = [i.value for i in constants.EnvType] results = sorted(results, key=lambda x: ordering.index(x['name'])) else: results = sorted(results, key=lambda x: x['name'], reverse=True) # 过滤带有ns的集群id cluster_ids_with_ns = [] # 按集群分组时,添加集群环境信息 for r in results: r_ns_list = r.get('results') or [] r_ns = r_ns_list[0] if r_ns_list else {} r['environment'] = r_ns.get('environment', '') r['environment_name'] = get_cluster_env_name( r['environment']) r["cluster_id"] = r_ns.get("cluster_id") cluster_ids_with_ns.append(r_ns.get("cluster_id")) # 添加无命名空间集群ID results.extend( self.get_clusters_without_ns(cluster_dict, cluster_ids_with_ns)) else: results = sorted(results, key=lambda x: x['id'], reverse=True) permissions = { 'create': can_create, 'sync_namespace': enabled_sync_namespace(project_id) } return APIResult(results, 'success', permissions=permissions)
def list(self, request, project_id): """命名空间列表 权限控制: 必须有对应集群的使用权限 """ access_token = request.user.token.access_token valid_group_by = ['env_type', 'cluster_id', 'cluster_name'] group_by = request.GET.get('group_by') cluster_id = request.GET.get('cluster_id') with_lb = request.GET.get('with_lb', 0) # 过滤有使用权限的命名空间 perm_can_use = request.GET.get('perm_can_use') if perm_can_use == '1': perm_can_use = True else: perm_can_use = False # 获取全部namespace,前台分页 result = paas_cc.get_namespace_list(access_token, project_id, with_lb=with_lb, limit=constants.ALL_LIMIT) if result.get('code') != 0: raise error_codes.APIError.f(result.get('message', '')) results = result['data']['results'] or [] # 是否有创建权限 perm = bcs_perm.Namespace(request, project_id, bcs_perm.NO_RES) can_create = perm.can_create(raise_exception=False) # 补充cluster_name字段 cluster_ids = [i['cluster_id'] for i in results] cluster_list = paas_cc.get_cluster_list(access_token, project_id, cluster_ids).get('data') or [] # cluster_list = bcs_perm.Cluster.hook_perms(request, project_id, cluster_list) cluster_dict = {i['cluster_id']: i for i in cluster_list} # no_vars=1 不显示变量 no_vars = request.GET.get('no_vars') if no_vars == '1': project_var = [] else: project_var = NameSpaceVariable.get_project_ns_vars(project_id) for i in results: # ns_vars = NameSpaceVariable.get_ns_vars(i['id'], project_id) ns_id = i['id'] ns_vars = [] for _var in project_var: _ns_values = _var['ns_values'] _ns_value_ids = _ns_values.keys() ns_vars.append({ 'id': _var['id'], 'key': _var['key'], 'name': _var['name'], 'value': _ns_values.get(ns_id) if ns_id in _ns_value_ids else _var['default_value'], }) i['ns_vars'] = ns_vars if i['cluster_id'] in cluster_dict: i['cluster_name'] = cluster_dict[i['cluster_id']]['name'] i['environment'] = cluster_dict[i['cluster_id']]['environment'] else: i['cluster_name'] = i['cluster_id'] i['environment'] = None # 添加permissions到数据中 results = perm.hook_perms(results, perm_can_use) if cluster_id: results = filter(lambda x: x['cluster_id'] == cluster_id, results) if group_by and group_by in valid_group_by: # 分组, 排序 results = [{ 'name': k, 'results': sorted(list(v), key=lambda x: x['id'], reverse=True) } for k, v in groupby(sorted(results, key=lambda x: x[group_by]), key=lambda x: x[group_by])] if group_by == 'env_type': ordering = [i.value for i in constants.EnvType] results = sorted(results, key=lambda x: ordering.index(x['name'])) else: results = sorted(results, key=lambda x: x['name'], reverse=True) # 按集群分组时,添加集群环境信息 for r in results: r_ns_list = r.get('results') or [] r_ns = r_ns_list[0] if r_ns_list else {} r['environment'] = r_ns.get('environment', '') r['environment_name'] = "正式" if r[ 'environment'] == 'prod' else "测试" else: results = sorted(results, key=lambda x: x['id'], reverse=True) return APIResult(results, '取Namespace成功', permissions={'create': can_create})