Example #1
0
 def __init__(self, *args, **kwargs):
     super(UserManagerMixin, self).__init__(*args, **kwargs)
     #self.resource = ResourceProxy(self)
     self.__cache_resource_map = {}
     self.__cache_roles = None
     self.allow_menu = None
     self.menu_map = ObjectDict()
     self.cache_allow_menu_key, self.cache_menu_map_key = self.get_cache_keys_for_id(
         self.id)
Example #2
0
 def svn_project_list(self, request):
     """
     获取 svn 项目
     :param request:
     :return:
     """
     project_list = SvnPath.get_svn_project_list()
     data = ObjectDict()
     data.results = []
     for project_name in project_list:
         data.results.append(dict(id=project_name, alias=project_name))
     return JsonResponse(data)
Example #3
0
    def autodiscover_app_view_functions(cls):
        from framework.views import is_notcheck
        urlconf = __import__(getattr(settings, 'ROOT_URLCONF'), {}, {}, [''])
        app_menu_map = {}
        views = []
        decorator = ['login_required']

        view_functions = Command().extract_views_from_urlpatterns(urlconf.urlpatterns)
        for (func, regex, url_name) in view_functions:
            if hasattr(func, '__globals__'):
                func_globals = func.__globals__
            elif hasattr(func, 'func_globals'):
                func_globals = func.func_globals
            else:
                func_globals = {}

            decorators = [d for d in decorator if d in func_globals]

            if isinstance(func, functools.partial):
                func = func.func
                decorators.insert(0, 'functools.partial')

            if hasattr(func, '__name__'):
                func_name = func.__name__
            elif hasattr(func, '__class__'):
                func_name = '%s()' % func.__class__.__name__
            else:
                func_name = re.sub(r' at 0x[0-9a-f]+', '', repr(func))

            module = '{0}.{1}'.format(func.__module__, func_name)
            url_name = url_name or module
            url = simplify_regex(regex).replace('[/]', '')
            decorator = ', '.join(decorators)

            if url_name.count('.') >= 1:
                url_name_split = url_name.split('.')
                method_name = url_name_split[-1]
                if hasattr(func, 'actions'):
                    func = getattr(func.cls, method_name, None)
                if is_notcheck(func):
                    _logger.info('%s is notcheck' % func)
                    continue
                views_data = ObjectDict()
                views_data.url_name = url_name
                views_data.method_name = method_name
                views_data.app_name = module.split('.')[0]
                views_data.url = url
                views_data.module = module

                views_data.describe = MenuConfig.find_view_func_doc(func, views_data.method_name)
                views_data.module_name = module
                app_menu_map.setdefault(views_data.app_name, {})
                app_menu_map[views_data.app_name].setdefault(views_data.module_name, [])
                app_menu_map[views_data.app_name][views_data.module_name].append(views_data)

        return app_menu_map
Example #4
0
    def code_paragraphs_tree(self, request):
        """树信息"""
        params = self.ParagraphsTreeParmas(request.query_params).params_data
        query_set = self.get_queryset()
        if params.is_project_private:
            query_set = self.get_queryset().filter(is_share=False)

        model_list: List[CodeParagraph] = self.filter_queryset(query_set)
        code_paragraphs_tree_map = Dict()

        for model in model_list:
            tag_name = model.tag
            connector_name = model.connector.type if model.connector else ''
            group_name = model.group or ''

            code_paragraphs_tree_map[tag_name][connector_name].setdefault(
                group_name, [])
            parent_list = code_paragraphs_tree_map[tag_name][connector_name][
                group_name]

            child_item = ObjectDict(title=model.name,
                                    key=model.id,
                                    alias=model.alias,
                                    table_schema=model.table_schema)
            parent_list.append(child_item)

        return self.response(code_paragraphs_tree_map)
Example #5
0
    def make_allow_map(self):
        """生成权限"""
        self.allow_menu = cache.get(self.cache_allow_menu_key, self.allow_menu)
        self.menu_map = cache.get(self.cache_menu_map_key, self.menu_map)
        if not self.allow_menu and not self.menu_map:
            self.allow_menu = ObjectDict()
            for m in self.get_menus():
                menu_name = m.name
                self.allow_menu[menu_name] = m
                # 兼容旧的用中文权限检查方式
                self.allow_menu[m.alias] = m

                self.menu_map.setdefault(m.url_path, [])
                self.menu_map[m.url_path].append(m)
            cache.set(self.cache_allow_menu_key, self.allow_menu)
            cache.set(self.cache_menu_map_key, self.menu_map)
Example #6
0
 def get_storage_file_list_status(self, backend, type_name, path):
     path_obj = furl(path)
     path = path_obj.pathstr
     origin = furl(self.last_execution_savepoint).origin
     data_list = []
     try:
         for dir_name, dir_status in backend.list(path, status=True):
             data: FlinkStorageFileSerializer = ObjectDict()
             data.dir_path = origin + os.path.join(path, dir_name)
             data.storage_type = type_name
             data.owner = dir_status.get('owner', '')
             data.modification_time = timestamp_to_datetime_str(
                 dir_status.get('modificationTime', 1000) / 1000)
             data_list.append(data)
     except Exception as e:
         logging.error(trace_msg())
     return data_list
Example #7
0
class UserManagerMixin(object):
    """用户管理者,扩展admin模型的方法
    """
    _CACHE_ALLOW_MENU_KEY = '_cache_allow_menu'
    _CACHE_MENU_MAP_KEY = '_cache_menu_map'

    def __init__(self, *args, **kwargs):
        super(UserManagerMixin, self).__init__(*args, **kwargs)
        #self.resource = ResourceProxy(self)
        self.__cache_resource_map = {}
        self.__cache_roles = None
        self.allow_menu = None
        self.menu_map = ObjectDict()
        self.cache_allow_menu_key, self.cache_menu_map_key = self.get_cache_keys_for_id(
            self.id)

    def check_permission(self, key):
        return self.allow_menu.get(key, None)

    def get_menus(self):
        user_menus = self.get_resource('menu').using('read')
        return user_menus.all()

    @classmethod
    def get_cache_keys_for_id(cls, id):
        return [
            f'{cls._CACHE_ALLOW_MENU_KEY}_{id}',
            f'{cls._CACHE_MENU_MAP_KEY}_{id}'
        ]

    @classmethod
    def clean_cache(cls, id):
        cache.delete_many(cls.get_cache_keys_for_id(id))

    def make_allow_map(self):
        """生成权限"""
        self.allow_menu = cache.get(self.cache_allow_menu_key, self.allow_menu)
        self.menu_map = cache.get(self.cache_menu_map_key, self.menu_map)
        if not self.allow_menu and not self.menu_map:
            self.allow_menu = ObjectDict()
            for m in self.get_menus():
                menu_name = m.name
                self.allow_menu[menu_name] = m
                # 兼容旧的用中文权限检查方式
                self.allow_menu[m.alias] = m

                self.menu_map.setdefault(m.url_path, [])
                self.menu_map[m.url_path].append(m)
            cache.set(self.cache_allow_menu_key, self.allow_menu)
            cache.set(self.cache_menu_map_key, self.menu_map)

    @CacheAttribute
    def resource(self) -> Resource:
        return ResourceProxy(self)

    def get_role_index(self):
        for r in self.get_roles():
            if r.index:
                return r.index
        else:
            return ''

    @classmethod
    def get_normal_user_list(cls):
        return User.objects.filter(status=User.Status.NORMAL)

    @classmethod
    def get_user(cls, user_id):
        """获取用户
        """
        return cls.objects.filter(id=user_id).prefetch_related('role').first()

    def check_role(self, name):
        for r in self.get_roles():
            if r.name == name:
                return True
        return False

    @CacheAttribute
    def is_root(self):
        """是否超级管理员
        """
        return self.check_role('root')

    @CacheAttribute
    def is_sdk_manager(self):
        return self.check_role('sdk_manager')

    @CacheAttribute
    def is_yunying(self):
        return self.check_role('yunying')

    @property
    def is_agent(self):
        """是否渠道用户
        """
        return self.id < 0

    @property
    def is_channel_user(self):
        return self.is_agent

    @CacheAttribute
    def is_kefu(self):
        """是否客服
        """
        return self.check_role('kefu')

    @property
    def is_not_active(self):
        return self.status == User.Status.NotActive

    @CacheAttribute
    def is_manager(self):
        """是否管理员
        """
        return self.is_root or self.check_role(
            'manager') or self.get_manageable_user().exists()

    def get_manageable_user(self):
        """获取自己的下属,除权限集合 如果是管理员这不能获取到
        """
        return User.objects.filter(role__in=self.get_resource('role').exclude(
            type=Role.RoleType.PERMISSION)).prefetch_related(
                'role').distinct()

    def get_resource_attrs(self,
                           resource_name,
                           attr_name,
                           input_list=None,
                           allow_none=False):
        input_list = input_list or []
        input_list = set([str(x) for x in input_list])
        resource_attrs = set([
            str(x)
            for x in self.get_resource(resource_name).values_list(attr_name,
                                                                  flat=True)
        ])
        if allow_none and input_list:
            new_attrs = list((input_list & resource_attrs))
        else:
            new_attrs = list((input_list & resource_attrs) or resource_attrs)
        return new_attrs

    def get_resource_ids(self, name, input_list=None):
        return self.get_resource_attrs(name, 'id', input_list)

    def set_resource(self, name, query_set):
        """设置资源,平台登录时就设置资源了
        """
        self.__cache_resource_map[name] = query_set

    def get_resource(self, name):
        """按资源名获取所属角色相应的资源
        """
        _r = self.__cache_resource_map.get(name, None)
        if _r == None:
            _r = self._get_resource(name)
        self.__cache_resource_map[name] = _r
        return self.__cache_resource_map[name]

    def _get_resource(self, name):
        return Resource.get_model_resource(name).get_resource_queryset(self)

    _get_resource_from_model = _get_resource

    def get_roles(self):
        """获取角色
        """
        if self.id:
            if self.__cache_roles != None:
                return self.__cache_roles
            self.__cache_roles = self.role.all()
            return self.__cache_roles
        else:
            return []

    @classmethod
    def create_role_from_name(cls, name):
        _role, _c = Role.objects.get_or_create(name=name)
        return _role

    @classmethod
    def create_root(cls):
        """创建系统管理员root账户
        """
        super_role, _c = Role.objects.get_or_create(name='root')
        user, _c = cls.objects.get_or_create(alias="系统管理员", username='******')
        user.role_ids = [super_role.id]
        user.status = cls.Status.NORMAL
        user.set_password('123456')
        user.save()

        logger.info('创建相关角色后,请务必删除root账户!')
        return user