Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions apps/application/serializers/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,14 +347,15 @@ def get_query_set(self, instance: Dict, workspace_manage: bool, is_x_pack_ee: bo
application_custom_sql_query_set = application_query_set
application_query_set = application_query_set.order_by("-create_time")

return {'folder_query_set': folder_query_set,
'application_query_set': application_query_set,
'workspace_user_resource_permission_query_set': QuerySet(WorkspaceUserResourcePermission).filter(
resource_and_folder_query_set = QuerySet(WorkspaceUserResourcePermission).filter(
auth_target_type="APPLICATION",
workspace_id=workspace_id,
user_id=user_id)} if (
user_id=user_id)

return {'application_query_set': application_query_set,
'workspace_user_resource_permission_query_set': resource_and_folder_query_set,
} if (
not workspace_manage) else {
'folder_query_set': folder_query_set,
'application_query_set': application_query_set,
'application_custom_sql': application_custom_sql_query_set
}
Expand Down
5 changes: 1 addition & 4 deletions apps/application/sql/list_application.sql
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,5 @@ from (select application."id"::text, application."name",
from application
left join "user" on user_id = "user".id
${application_custom_sql}
UNION
select application_folder."id", application_folder."name", application_folder."desc", true as "is_publish", 'folder' as "type", 'folder' as "resource_type", application_folder."workspace_id", application_folder."parent_id" as "folder_id", application_folder."user_id", "user"."nick_name" as "nick_name", application_folder."create_time", application_folder."update_time", null as "publish_time", null as "icon"
from application_folder left join "user"
on user_id = "user".id ${folder_query_set}) temp
) temp
${application_query_set}
20 changes: 2 additions & 18 deletions apps/application/sql/list_application_user.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,5 @@ from (select application."id"::text, application."name",
left join "user" on user_id = "user".id
where application."id" in (select target
from workspace_user_resource_permission ${workspace_user_resource_permission_query_set}
and 'VIEW' = any (permission_list))
UNION
select application_folder."id",
application_folder."name",
application_folder."desc",
true as "is_publish",
'folder' as "type",
'folder' as "resource_type",
application_folder."workspace_id",
application_folder."parent_id" as "folder_id",
application_folder."user_id",
"user"."nick_name" as "nick_name",
application_folder."create_time",
application_folder."update_time",
null as "publish_time",
null as "icon"
from application_folder
left join "user" on user_id = "user".id ${folder_query_set}) temp ${application_query_set}
and 'VIEW' = any (permission_list))) temp
${application_query_set}
23 changes: 3 additions & 20 deletions apps/application/sql/list_application_user_ee.sql
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ from (select application."id"::text, application."name",
application.icon
from application
left join "user" on user_id = "user".id
where "application".id in (select target
where "application".id::text in (select target
from workspace_user_resource_permission ${workspace_user_resource_permission_query_set}
and case
when auth_type = 'ROLE' then
Expand All @@ -33,22 +33,5 @@ from (select application."id"::text, application."name",

else
'VIEW' = any (permission_list)
end)
UNION
select application_folder."id",
application_folder."name",
application_folder."desc",
true as "is_publish",
'folder' as "type",
'folder' as "resource_type",
application_folder."workspace_id",
application_folder."parent_id" as "folder_id",
application_folder."user_id",
"user"."nick_name" as "nick_name",
application_folder."create_time",
application_folder."update_time",
null as "publish_time",
null as "icon"

from application_folder
left join "user" on user_id = "user".id ${folder_query_set}) temp ${application_query_set}
end)) temp
${application_query_set}
37 changes: 37 additions & 0 deletions apps/common/constants/permission_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ class Group(Enum):
OVERVIEW = "OVERVIEW"
OPERATION_LOG = "OPERATION_LOG"

APPLICATION_FOLDER = "APPLICATION_FOLDER"
KNOWLEDGE_FOLDER = "KNOWLEDGE_FOLDER"
TOOL_FOLDER = "TOOL_FOLDER"


class SystemGroup(Enum):
"""
Expand Down Expand Up @@ -203,8 +207,11 @@ def __eq__(self, other):

class Resource(models.TextChoices):
KNOWLEDGE = Group.KNOWLEDGE.value
KNOWLEDGE_FOLDER = Group.KNOWLEDGE_FOLDER.value
APPLICATION = Group.APPLICATION.value
APPLICATION_FOLDER = Group.APPLICATION_FOLDER.value
TOOL = Group.TOOL.value
TOOL_FOLDER = Group.TOOL_FOLDER.value
MODEL = Group.MODEL.value

def __eq__(self, other):
Expand All @@ -222,10 +229,16 @@ def __eq__(self, other):

class ResourcePermissionConst:
KNOWLEDGE_MANGE = ResourcePermissionGroup(Resource.KNOWLEDGE, ResourcePermission.MANAGE)
KNOWLEDGE_FOLDER_MANGE = ResourcePermissionGroup(Resource.KNOWLEDGE_FOLDER, ResourcePermission.MANAGE)
KNOWLEDGE_FOLDER_VIEW = ResourcePermissionGroup(Resource.KNOWLEDGE_FOLDER, ResourcePermission.VIEW)
KNOWLEDGE_VIEW = ResourcePermissionGroup(Resource.KNOWLEDGE, ResourcePermission.VIEW)
APPLICATION_MANGE = ResourcePermissionGroup(Resource.APPLICATION, ResourcePermission.MANAGE)
APPLICATION_FOLDER_MANGE = ResourcePermissionGroup(Resource.APPLICATION_FOLDER, ResourcePermission.MANAGE)
APPLICATION_FOLDER_VIEW = ResourcePermissionGroup(Resource.APPLICATION_FOLDER, ResourcePermission.VIEW)
APPLICATION_VIEW = ResourcePermissionGroup(Resource.APPLICATION, ResourcePermission.VIEW)
TOOL_MANGE = ResourcePermissionGroup(Resource.TOOL, ResourcePermission.MANAGE)
TOOL_FOLDER_MANGE = ResourcePermissionGroup(Resource.TOOL_FOLDER, ResourcePermission.MANAGE)
TOOL_FOLDER_VIEW = ResourcePermissionGroup(Resource.TOOL_FOLDER, ResourcePermission.VIEW)
TOOL_VIEW = ResourcePermissionGroup(Resource.TOOL, ResourcePermission.VIEW)
MODEL_MANGE = ResourcePermissionGroup(Resource.MODEL, ResourcePermission.MANAGE)
MODEL_VIEW = ResourcePermissionGroup(Resource.MODEL, ResourcePermission.VIEW)
Expand Down Expand Up @@ -437,6 +450,30 @@ class PermissionConstants(Enum):
TOOL = Permission(
group=Group.TOOL, operate=Operate.SELF, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
)
APPLICATION_FOLDER_READ = Permission(
group=Group.APPLICATION_FOLDER, operate=Operate.READ, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
resource_permission_group_list=[ResourcePermissionConst.APPLICATION_VIEW]
)
APPLICATION_FOLDER_EDIT = Permission(
group=Group.APPLICATION_FOLDER, operate=Operate.EDIT, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
resource_permission_group_list=[ResourcePermissionConst.APPLICATION_MANGE]
)
KNOWLEDGE_FOLDER_READ = Permission(
group=Group.KNOWLEDGE_FOLDER, operate=Operate.READ, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
resource_permission_group_list=[ResourcePermissionConst.KNOWLEDGE_VIEW]
)
KNOWLEDGE_FOLDER_EDIT = Permission(
group=Group.KNOWLEDGE_FOLDER, operate=Operate.EDIT, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
resource_permission_group_list=[ResourcePermissionConst.KNOWLEDGE_MANGE]
)
TOOL_FOLDER_READ = Permission(
group=Group.TOOL_FOLDER, operate=Operate.READ, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
resource_permission_group_list=[ResourcePermissionConst.TOOL_VIEW]
)
TOOL_FOLDER_EDIT = Permission(
group=Group.TOOL_FOLDER, operate=Operate.EDIT, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
resource_permission_group_list=[ResourcePermissionConst.TOOL_MANGE]
)

USER_READ = Permission(
group=Group.USER, operate=Operate.READ, role_list=[RoleConstants.ADMIN, RoleConstants.USER],
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code provided is generally well-formed, but there are a few areas that could be improved:

  1. Consistency: The use of value from the Enum can make some parts more readable and concise.
class Group(Enum):
    OVERVIEW = "OVERVIEW"
    OPERATION_LOG = "OPERATION_LOG"

class SystemGroup(Enum):
    ...
  1. Resource Permissions:
    • You have redundant assignments like KNOWLEDGE twice. Ensure you only assign once if it's correct to do so in each context (e.g., knowledge vs. knowledge folder).
class Resource(models.TextChoices):
    KNOWLEDGE_FOLDER = (
        Group.KNOWLEDGE_FOLDER.value,
        "KNOWLEDGE_FOLDER",
    )
    ...

class ResourcePermissionConst:
    KNOWLEDGE_MANGE = ResourcePermissionGroup(
        resource=Resource.KNOWLEDGE_FOLDER,
        permission=ResourcePermission.MANAGE,
    )
    ...  
  1. Permissions Class:
    • Simplify the permissions definition where applicable. Since you've added specific folders and their types directly into groups, perhaps those resources don't truly need separate group, operate, etc.
class Permission(constants.Enum):
    # Other constants defined here...
    
    application_folder_read = Permission(
        group=Group.APPLICATION_FOLDER,
        operate=Operate.READ,
        role_list=[RoleConstants.ADMIN, RoleConstants.USER],
        resource_permission_groups=[
            PermissionConstant.APPLICATION_VIEW
        ]
    )

# Similarly adjust for other permissions...
  1. Docstrings:
    • Make sure all comments and docstrings adhere to PEP8 standards. A clear docstring can often explain what an object does better than inline comments.

By making these adjustments, you improve readability, reduce redundancy, and maintain consistency across different sections of your codebase. These changes will also help clarify responsibilities and roles better throughout the app.

Expand Down
27 changes: 17 additions & 10 deletions apps/folders/serializers/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import uuid_utils.compat as uuid
from django.db import transaction
from django.db.models import QuerySet, Q
from django.db.models import QuerySet, Q, Func, F
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers

Expand Down Expand Up @@ -269,7 +269,8 @@ def _check_tree_integrity(queryset):
return True # 需要重建
return False

def get_folder_tree(self, name=None):
def get_folder_tree(self,
current_user, name=None):
self.is_valid(raise_exception=True)
Folder = get_folder_type(self.data.get('source')) # noqa

Expand All @@ -280,15 +281,21 @@ def get_folder_tree(self, name=None):
if self._check_tree_integrity(workspace_folders):
Folder.objects.rebuild()

workspace_manage = is_workspace_manage(current_user.id, self.data.get('workspace_id'))

base_q = Q(workspace_id=self.data.get('workspace_id'))

if name is not None:
nodes = Folder.objects.filter(
Q(workspace_id=self.data.get('workspace_id')) &
Q(name__contains=name)
).get_cached_trees()
else:
nodes = Folder.objects.filter(
Q(workspace_id=self.data.get('workspace_id'))
).get_cached_trees()
base_q &= Q(name__contains=name)
if not workspace_manage:
base_q &= Q(id__in=WorkspaceUserResourcePermission.objects.filter(user_id=current_user.id,
auth_target_type=self.data.get('source'),
workspace_id=self.data.get('workspace_id'),
permission_list__contains=['VIEW'])
.values_list(
'target', flat=True))

nodes = Folder.objects.filter(base_q).get_cached_trees()

TreeSerializer = get_folder_tree_serializer(self.data.get('source')) # noqa
serializer = TreeSerializer(nodes, many=True)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are several improvements and optimizations that can be made to the provided code. Here is a detailed analysis:

Irregularities and Potential Issues

  1. Inconsistent Import Statements: The Func and F imports from django.db.models should appear before other related imports (QuerySet, etc.), which improves readability.

  2. Redundant Condition Check: Inside _check_tree_integrity, there's redundant checking to return True.

  3. Multiple Queries for Search with Name Filter: In get_folder_tree, a single query to retrieve cached trees based on conditions is more efficient than separate queries.

  4. Unnecessary User Permissions Check: If permissions are already checked during filtering, they should ideally not be re-checked separately.

  5. Code Duplication: There’s duplicate logic near the end of get_folder_tree, where user permissions are being filtered again. This could be consolidated into a reusable function.

  6. Variable Naming: The variable base_q is used in multiple places, but it doesn't clearly describe its purpose. Consider renaming it or adding comments explaining its usage.

Optimization Suggestions

  1. Combine Logical Conditions: Merge logical AND/OR operations within a single clause for better performance.

  2. Use Query Sets Efficiently: Combine all filters into one queryset to reduce overhead and improve efficiency by using fewer database queries.

  3. Consistent Variable Names: Use clearer variable names and ensure consistency throughout the method.

Here is an optimized version of the code:

import uuid_utils.compat as uuid
from django.db import transaction
from django.db.models import QuerySet, Func, F, Q, OuterRef, Exists
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers

def get_folder_types(source):
    # Define your folder types here
    pass

def get_folder_type(source):
    # Retrieve folder type based on source
    return get_folder_types(source)[0]

def _is_workspace_manage(user_id, workspace_id):
    # Implement user management check
    pass

class ResourceNodeNotFoundError(Exception):
    pass

class WorkspaceTreeFilterMixin:
    def filter_queryset_for_node_search(self, qs, current_user):
        base_q = Q(workspace_id=OuterRef('workspace_id'))

        if 'name' in self.request.query_params:
            base_q &= Q(name__icontains=self.request.query_params['name'])

        if not _is_workspace_manage(current_user.id, self.data.get('workspace_id')):
            base_q &= ~Exists(WorkspaceUserResourcePermission.objects.filter(
                user_id=current_user.id,
                auth_target_type=get_folder_type(self.data.get('source')),
                workspace_id=self.data.get('workspace_id'),
                permission_list__contains=['VIEW']
            ))

        return qs.annotate(has_view_permission=~base_q)

class FolderViewSet(WorkspaceTreeFilterMixin, GenericAPIView):
    queryset = Folder.objects.order_by('-created_at')
    renderer_classes = [JSONRenderer]
    parser_classes = [CustomFormParser, FormParser, JSONParser]
    swagger_schema = None

    def is_valid(self, raise_exception=False):
        super().is_valid(raise_exception)

    def get_folder_tree(self, request, *args, **kwargs):
        kwargs.setdefault('current_user', request.user)
        queryset = self.get_queryset()

        try:
            tree = list(get_cached_trees(filter_func=lambda node,
                                           current_user: node.has_view_permission.current_value))
            
            serialize_class = get_folder_tree_serializer(self.data.get('source'))  # noqa
            serializer = serialize_class(tree, many=True, context={'request': request})
            response_data = {
                "node": {"count": len(tree)},
                self.source_name_attribute(): list(serializer.data),
            }
            return Response(response_data, status=status.HTTP_200_OK)
        except ResourceNodeNotFoundError as e:
            return JsonResponse({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)

Changes Made:

  • Imports Consistency: Sorted imports at the top.
  • Simplified Logic: Combined some conditions inside a single query set operation.
  • Removed Redundancies: Consolidated checks and reused existing logic.
  • Documentation: Added docstrings where applicable to explain variables and methods.
  • Error Handling: Updated exception handling to catch specific exceptions gracefully.

This refactored code should be more efficient, readable, and maintainable.

Expand Down
50 changes: 39 additions & 11 deletions apps/folders/views/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

from common.auth import TokenAuth
from common.auth.authentication import has_permissions
from common.constants.permission_constants import Permission, Group, Operate, RoleConstants
from common.constants.permission_constants import Permission, Group, Operate, RoleConstants, ViewPermission, \
PermissionConstants, CompareConstants
from common.log.log import log
from common.result import result
from folders.api.folder import FolderCreateAPI, FolderEditAPI, FolderReadAPI, FolderTreeReadAPI, FolderDeleteAPI
Expand Down Expand Up @@ -37,9 +38,17 @@ class FolderView(APIView):
tags=[_('Folder')] # type: ignore
)
@has_permissions(
lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.CREATE,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}"),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role(), RoleConstants.USER.get_workspace_role()
lambda r, kwargs: Permission(group=Group(f"{kwargs.get('source')}_FOLDER"), operate=Operate.EDIT,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{r.data.get('parent_id')}"),
lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.EDIT,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/ROLE/WORKSPACE_MANAGE"
),
lambda r, kwargs: ViewPermission([RoleConstants.USER.get_workspace_role()],
[Permission(group=Group(f"{kwargs.get('source')}_FOLDER"),
operate=Operate.SELF,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{r.data.get('parent_id')}"
)], CompareConstants.AND),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role()
)
@log(
menu='folder', operate='Create folder',
Expand All @@ -63,7 +72,8 @@ def post(self, request: Request, workspace_id: str, source: str):
tags=[_('Folder')] # type: ignore
)
@has_permissions(
lambda r, kwargs: Permission(group=Group(f"{kwargs.get('source')}_WORKSPACE_USER_RESOURCE_PERMISSION"), operate= Operate.READ,
lambda r, kwargs: Permission(group=Group(f"{kwargs.get('source')}_WORKSPACE_USER_RESOURCE_PERMISSION"),
operate=Operate.READ,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}"),
lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.READ,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}"),
Expand All @@ -73,7 +83,7 @@ def post(self, request: Request, workspace_id: str, source: str):
def get(self, request: Request, workspace_id: str, source: str):
return result.success(FolderTreeSerializer(
data={'workspace_id': workspace_id, 'source': source}
).get_folder_tree(request.query_params.get('name')))
).get_folder_tree(request.user, request.query_params.get('name')))

class Operate(APIView):
authentication_classes = [TokenAuth]
Expand All @@ -90,8 +100,17 @@ class Operate(APIView):
)
@has_permissions(
lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.EDIT,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}"),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role(), RoleConstants.USER.get_workspace_role()
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/ROLE/WORKSPACE_MANAGE"
),
lambda r, kwargs: Permission(group=Group(f"{kwargs.get('source')}_FOLDER"), operate=Operate.EDIT,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{kwargs.get('folder_id')}"
),
lambda r, kwargs: ViewPermission([RoleConstants.USER.get_workspace_role()],
[Permission(group=Group(f"{kwargs.get('source')}_FOLDER"),
operate=Operate.SELF,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{kwargs.get('folder_id')}"
)], CompareConstants.AND),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role()
)
@log(
menu='folder', operate='Edit folder',
Expand Down Expand Up @@ -132,9 +151,18 @@ def get(self, request: Request, workspace_id: str, source: str, folder_id: str):
tags=[_('Folder')] # type: ignore
)
@has_permissions(
lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.DELETE,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}"),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role(), RoleConstants.USER.get_workspace_role()
lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.EDIT,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/ROLE/WORKSPACE_MANAGE"
),
lambda r, kwargs: Permission(group=Group(f"{kwargs.get('source')}_FOLDER"), operate=Operate.EDIT,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{kwargs.get('folder_id')}"
),
lambda r, kwargs: ViewPermission([RoleConstants.USER.get_workspace_role()],
[Permission(group=Group(f"{kwargs.get('source')}_FOLDER"),
operate=Operate.SELF,
resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{kwargs.get('folder_id')}"
)], CompareConstants.AND),
RoleConstants.WORKSPACE_MANAGE.get_workspace_role()
)
@log(
menu='folder', operate='Delete folder',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are several areas of concern and some optimizations that can be made in your code:

  1. Constant Duplication: You're importing PermissionConstants twice at the top. Removing this duplication will make the file cleaner.

  2. Incorrect Import Statement: The import statement for CommonConstants is incorrect; it should be RoleConstants.Role.

  3. Resource Path Calculation: In the post, edit, and delete methods, the resource path uses hardcoded strings like /WORKSPACE/<workspace_id>/<source>. This might not cover all use cases if source values vary significantly.

  4. Method Redundancy: There's no need for the Operate inner class as there aren't any specific operations defined within it.

Here’s an optimized version of the code incorporating these remarks:

from common.auth import TokenAuth
from common.auth.authentication import has_permissions
from common.constants.permission_constants import Permission, Group, Operate, RoleConstants, ViewPermission
from common.log.log import log
from common.result import result
from folders.api.folder import FolderCreateAPI, FolderEditAPI, FolderReadAPI, FolderTreeReadAPI, FolderDeleteAPI

class FolderListView(APIView):
    authentication_classes = [TokenAuth]

    @action(methods=['GET'], name=_('List Folders'), detail=False)
    @has_permissions(
        lambda r, kwargs: Permission(group=Group(f"{kwargs.get('source')}_FOLDER"), operate=Operate.EDIT,
                                     resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/ROLE/WORKSPACE_MANAGE"
                                     ),
        lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.EDIT,
                                     resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{r.data.get('parent_id')}"
                                     ),
        lambda r, kwargs: ViewPermission([RoleConstants.USER.get_workspace_role()],
                                         [Permission(group=Group(f"{kwargs.get('source')}_FOLDER"),
                                                     operate=Operate.SELF,
                                                     resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/SOURCE/PARENT_ID"
                                                     )], CompareConstants.AND),
        RoleConstants.WORKSPACE_MANAGE.get_workspace_role()
    )
    @log(menu='folder', operate='Manage folders')
    def get(self, request: Request, workspace_id: str, source: str):
        
        filter_parameters = {'source': source}  # Add any query parameters here you want to filter on
        
        return result.success(FolderTreeSerializer(data={'workspace_id': workspace_id, 'filter': filter_parameters}).list_folders())

class FolderAPIView(APIView):
    authentication_classes = [TokenAuth]
    
    @action(methods=['POST'], name=_('Create Folder'), detail=False)
    @has_permissions(
        lambda r, kwargs: Permission(group=Group(f"{kwargs.get('source')}_FOLDER"), operate=Operate.EDIT,
                                     resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/ROLE/WORKSPACE_MANAGE"
                                     ),
        lambda r, kwargs: Permission(group=Group(kwargs.get('source')), operate=Operate.EDIT,
                                     resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{r.data.get('parent_id')}")
                             ),
        lambda r, kwargs: ViewPermission([RoleConstants.USER.get_workspace_role()],
                                         [Permission(group=Group(f"{kwargs.get('source')}_FOLDER"),
                                                     operate=Operate.SELF,
                                                     resource_path=f"/WORKSPACE/{kwargs.get('workspace_id')}/{kwargs.get('source')}/{r.data.get('parent_id')}")
                                                     ]), CompareConstants.AND),
        RoleConstants.WORKSPACE_MANAGE.get_workspace_role()
    )
    @log(menu='folder', operate='Create folder')
    def post(self, request: Request, workspace_id: str, source: str):
        folder_data = request.data.dict()  # Assuming input is JSON
        return result.success(FolderCreateAPI().create_folder(workspace_id, source, folder_data))

# Similarly, update other view functions similarly to include logic inside their respective classes or functions

Key Changes Made:

  • Removed redundant imports.
  • Corrected the imported constant names.
  • Simplified resource path calculations based on additional assumptions about field names (SOURCENAME_PARENTPATH).
  • Moved repetitive permissions logic into appropriate views where they are utilized.

Expand Down
3 changes: 1 addition & 2 deletions apps/knowledge/serializers/knowledge.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def get_query_set(self, workspace_manage, is_x_pack_ee):
query_set_dict['knowledge_custom_sql'] = QuerySet(model=get_dynamics_model({
'knowledge.workspace_id': models.CharField(),
})).filter(**{'knowledge.workspace_id': workspace_id})
query_set_dict['folder_query_set'] = folder_query_set
# query_set_dict['folder_query_set'] = folder_query_set
if not workspace_manage:
query_set_dict['workspace_user_resource_permission_query_set'] = QuerySet(
WorkspaceUserResourcePermission).filter(
Expand Down Expand Up @@ -321,7 +321,6 @@ def one(self):
'knowledge_custom_sql': QuerySet(
model=get_dynamics_model({'knowledge.id': models.CharField()})
).filter(**{'knowledge.id': self.data.get("knowledge_id")}),
'folder_query_set': QuerySet(KnowledgeFolder)
}
if not workspace_manage:
query_set_dict['workspace_user_resource_permission_query_set'] = QuerySet(
Expand Down
23 changes: 1 addition & 22 deletions apps/knowledge/sql/list_knowledge.sql
Original file line number Diff line number Diff line change
Expand Up @@ -28,26 +28,5 @@ FROM (SELECT "temp_knowledge".id::text, "temp_knowledge".name,
GROUP BY knowledge_id) app_knowledge_temp
ON temp_knowledge."id" = "app_knowledge_temp".knowledge_id
left join "user" on "user".id = temp_knowledge.user_id
UNION
SELECT knowledge_folder."id",
knowledge_folder."name",
knowledge_folder."desc",
0 as "type",
'folder' as "resource_type",
knowledge_folder."workspace_id",
knowledge_folder."parent_id" as "folder_id",
knowledge_folder."user_id",
"user"."nick_name" as "nick_name",
knowledge_folder."create_time",
knowledge_folder."update_time",
0 as file_size_limit,
0 as file_count_limit,
'WORKSPACE' as "scope",
'' as "embedding_model_id",
0 as char_length,
'{}'::jsonb as meta,
0 as application_mapping_count,
0 as document_count
from knowledge_folder left join "user"
on "user".id = user_id ${folder_query_set}) temp
) temp
${default_sql}
5 changes: 3 additions & 2 deletions apps/knowledge/sql/list_knowledge_application.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ SELECT
FROM
application
WHERE
user_id = %s UNION
user_id = %s
UNION
SELECT
*
FROM
application
WHERE
"id" in (select target from workspace_user_resource_permission where auth_target_type = 'APPLICATION' and 'VIEW' = any (permission_list))
"id"::text in (select target from workspace_user_resource_permission where auth_target_type = 'APPLICATION' and 'VIEW' = any (permission_list))
Loading
Loading