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
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,18 @@

from common.constants.permission_constants import WorkspaceUserRoleMapping
from common.utils.common import group_by
from application.models import ApplicationFolder
from knowledge.models import KnowledgeFolder
from tools.models import ToolFolder
from system_manage.models import WorkspaceUserResourcePermission
from users.models import User


def delete_auth(folder_model):
QuerySet(WorkspaceUserResourcePermission).filter(target__in=QuerySet(folder_model).values_list('id')).delete()
def delete_auth(apps,folder_model):
workspace_user_resource_permission_model = apps.get_model('system_manage', 'WorkspaceUserResourcePermission')
QuerySet(workspace_user_resource_permission_model).filter(target__in=QuerySet(folder_model).values_list('id')).delete()


def get_workspace_user_resource_permission_list(auth_target_type, workspace_user_role_mapping_model_workspace_dict,
def get_workspace_user_resource_permission_list(apps, auth_target_type, workspace_user_role_mapping_model_workspace_dict,
folder_model):
workspace_user_resource_permission_model = apps.get_model('system_manage', 'WorkspaceUserResourcePermission')
return reduce(lambda x, y: [*x, *y], [
[WorkspaceUserResourcePermission(target=f.id, workspace_id=f.workspace_id, user_id=wurm.user_id,
[workspace_user_resource_permission_model(target=f.id, workspace_id=f.workspace_id, user_id=wurm.user_id,
auth_target_type=auth_target_type, auth_type="RESOURCE_PERMISSION_GROUP",
permission_list=['VIEW','MANAGE'] if wurm.user_id == f.user_id else ['VIEW']) for wurm in
workspace_user_role_mapping_model_workspace_dict.get(f.workspace_id, [])] for f in
Expand All @@ -30,31 +27,38 @@ def get_workspace_user_resource_permission_list(auth_target_type, workspace_user
def auth_folder(apps, schema_editor):
from common.database_model_manage.database_model_manage import DatabaseModelManage
DatabaseModelManage.init()

user_model = apps.get_model('users', 'User')
application_folder_model = apps.get_model('application', 'ApplicationFolder')
knowledge_folder_model = apps.get_model('knowledge', 'KnowledgeFolder')
tool_folder_model = apps.get_model('tools', 'ToolFolder')
workspace_user_resource_permission_model = apps.get_model('system_manage', 'WorkspaceUserResourcePermission')

workspace_user_role_mapping_model = DatabaseModelManage.get_model("workspace_user_role_mapping")
if workspace_user_role_mapping_model is None:
workspace_user_role_mapping_model_workspace_dict = {
'default': [WorkspaceUserRoleMapping('default', '', u.id) for u in QuerySet(User).all()]}
'default': [WorkspaceUserRoleMapping('default', '', u.id) for u in QuerySet(user_model).all()]}
else:
workspace_user_role_mapping_model_workspace_dict = group_by(
[v for v in {str(wurm.user_id) + str(wurm.workspace_id): wurm for wurm in
QuerySet(workspace_user_role_mapping_model)}.values()],
lambda item: item.workspace_id)

workspace_user_resource_permission_list = get_workspace_user_resource_permission_list("APPLICATION",
workspace_user_resource_permission_list = get_workspace_user_resource_permission_list(apps,"APPLICATION",
workspace_user_role_mapping_model_workspace_dict,
ApplicationFolder)
application_folder_model)

workspace_user_resource_permission_list += get_workspace_user_resource_permission_list("TOOL",
workspace_user_resource_permission_list += get_workspace_user_resource_permission_list(apps,"TOOL",
workspace_user_role_mapping_model_workspace_dict,
ToolFolder)
knowledge_folder_model)

workspace_user_resource_permission_list += get_workspace_user_resource_permission_list("KNOWLEDGE",
workspace_user_resource_permission_list += get_workspace_user_resource_permission_list(apps,"KNOWLEDGE",
workspace_user_role_mapping_model_workspace_dict,
KnowledgeFolder)
delete_auth(ApplicationFolder)
delete_auth(ToolFolder)
delete_auth(KnowledgeFolder)
QuerySet(WorkspaceUserResourcePermission).bulk_create(workspace_user_resource_permission_list)
tool_folder_model)
delete_auth(apps,application_folder_model)
delete_auth(apps,knowledge_folder_model)
delete_auth(apps,tool_folder_model)
QuerySet(workspace_user_resource_permission_model).bulk_create(workspace_user_resource_permission_list)


class Migration(migrations.Migration):
Copy link
Contributor Author

Choose a reason for hiding this comment

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

To review the provided Python code, here are some suggestions:

  1. Imports:

    • The group_by function is imported but not used elsewhere, which can be removed.
  2. Function Definitions:

    • In both get_workspace_user_resource_permission_list and auth_folder, there's an unused parameter folder_model. This should be removed to simplify the function signatures.
  3. Database Operations:

    • In the auth_folder method, using QuerySet(...).bulk_create() might lead to performance issues if dealing with a large number of records. Consider iterating over individual objects for better control.
    • Ensure that all models (User, etc.) have the expected relationships defined before attempting deletions or bulk creation.
  4. General Readability:

    • Split long lines into smaller ones where possible for easier readability without excessive indentation.
    • Adding comments about specific parts of the code could help others (or yourself later) understand its purpose more quickly.

Here’s the revised snippet incorporating these improvements:

from common.constants.permission_constants import WorkspaceUserRoleMapping
from common.utils.common import group_by
from application.models import ApplicationFolder
from knowledge.models import KnowledgeFolder
from tools.models import ToolFolder
from system_manage.models import WorkspaceUserResourcePermission
from users.models import User

def delete_auth(apps, folder_model):
    workspace_user_resource_permission_model = apps.get_model('system_manage', 'WorkspaceUserResourcePermission')
    QuerySet(workspace_user_resource_permission_model).filter(target__in=QuerySet(folder_model).values_list('id')).delete()

def get_workspace_user_resource_permission_list(apps, auth_target_type, workspace_user_role_mapping_model_workspace_dict):
    workspace_user_resource_permission_model = apps.get_model('system_manage', 'WorkspaceUserResourcePermission')
    return list(reduce(lambda x, y: [*x, *y], [
        [workspace_user_resource_permission_model(target=f.id, workspace_id=f.workspace_id, user_id=wurm.user_id,
                                          auth_target_type=auth_target_type, auth_type="RESOURCE_PERMISSION_GROUP",
                                          permission_list=['VIEW','MANAGE'] if wurm.user_id == f.user_id else ['VIEW'])
         for wurm in workspace_user_role_mapping_model_workspace_dict.get(f.workspace_id, [])]
         for f in folder_model.objects.all()])
    
def auth_folder(apps, schema_editor):
    from common.database_model_manage.database_model_manage import DatabaseModelManage
    
    database_model_manager = DatabaseModelManage()
    database_model_manager.init()
    
    try:
        # Get related User model dynamically
        user_model = apps.get_model('users', 'User')
        
        # Initialize dictionary mapping workspace ID to user IDs
        workspace_user_role_map = {}
        
        # Populate the dictionary
        queryset_filter_query = QuerySet(WorkspaceUserRoleMapping)
        map_obj_ids_to_user_ids = \
            {(row.workspace_id, row.user_id) : row.id 
                for row in queryset_filter_query}
                
        for key, value in map_obj_ids_to_user_ids.items():  
            workspace_user_role_map.setdefault(key[0], []).append(value)
        
        # Obtain a queryset of each type of object
        app_queryset = ApplicationFolder.objects.all()
        tool_queryset = ToolFolder.objects.all()
        kwnl_qs = KnowledgeFolder.objects.all()
                    
        # Get resources associated with ApplicationFolders
        resource_permissions = []
        for wkrp_entry_id in list(map(list, workspace_user_role_map.values()))[0]:
            resp = database_model_manager.fetch_object_details_from_db(entry=wkrp_entry_id)
            
            # Assuming it has details like target_id corresponding to either folders or users
            if "target_id" in resp["object_detail"]:
                # Filter based on authentication targets
                if response["authentication_target"] != auth_target_type.lower():
                    continue
                
                # If matching criteria, add relevant permissions
                if auth_target_type == "APPLICATION":
                    current_obj_set = app_queryset
                elif auth_target_type == "TOOL":
                    current_obj_set = tool_queryset
                elif auth_target_type == "KNOWLEDGE":
                    current_obj_set = kwnl_qs
                    
                resource_resources.append({
                    "target": resp["object_detail"]["target_id"],
                    "workspace_id": resp["object_detail"]["workspace_id"], 
                    "user_id": resp["object_detail"]["user_id"], 
                    "auth_target_type": auth_target_type,
                    "auth_type": "RESOURCE_PERMISSION_GROUP", 
                    "permission_list": ["VIEW","MANAGE"]
                        } if resp["object_detail"]["user_id"] == current_obj_set.values()[resp["object_detail"]["target_id"]]
                             else ["VIEW"])
        
        # Perform batch deletion first
        workspace_user_resource_permission_model.objects.filter(authorization_target=auth_target_type).delete()
        
        # Then perform bulk create operation
        if len(resource_permissions) > 0:
            workspace_user_resource_permission_model.objects.bulk_create([
                workspace_user_resource_permission_model(**rp_info) 
                 for rp_info in resource_permissions])
    
    except Exception as e:
        print(f"Error occurred in auth_folder migration task:")
        raise e


class Migration(migrations.Migration):
    ...

These changes address some identified potential issues and enhance the overall clarity and maintainability of the code.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
v-model="form.access_num"
:min="0"
:step="1"
:max="10000"
:max="10000000"
:value-on-clear="0"
controls-position="right"
style="width: 268px"
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 has an issue with the max attribute. It currently sets the maximum value to 10,000,000 which might be too large for some use cases due to its significant size. A better practice is to set a more appropriate max value based on what fits within your application's requirements. If no specific limit is required, consider setting it higher than what makes sense for most scenarios.

Optimization suggestions:

  1. Ensure that the number type used matches the precision needed for calculations if this input deals with monetary values or other quantities where high precision is important.

  2. Consider adding validation logic in the form component to ensure that users do not submit invalid inputs (e.g., negative numbers).

  3. Review whether there are any larger UI elements around this input that could improve user experience by making space or providing context clues related to how much can be entered here.

These changes will help enhance both functionality and usability of the form control in your application.

Expand Down
Loading