Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import csv
from extras.scripts import Script, FileVar
from django.contrib.contenttypes.models import ContentType
from users.models import ObjectPermission
from django.contrib.auth.models import Group
class InitializeRolesScript(Script):
csv_file = FileVar(description="Upload a CSV file with roles configuration")
class Meta:
name = "Initialize Roles and Permissions"
description = "Create or update roles and permissions based on a CSV file."
field_order = ['csv_file']
def run(self, data, commit):
csv_file = data['csv_file']
# Required groups to ensure exist
required_groups = ['SuperAccess', 'Administrator', 'Global Viewer', 'Overall Viewer']
# Ensure groups exist
for group_name in required_groups:
group, created = Group.objects.get_or_create(name=group_name)
if created:
self.log_success(f"Group '{group_name}' created.")
else:
self.log_info(f"Group '{group_name}' already exists.")
# Process the uploaded CSV file
try:
csv_data = csv_file.read().decode('utf-8').splitlines()
reader = csv.DictReader(csv_data)
for row in reader:
# Read necessary columns from the CSV
permission_name = row.get('Permission')
groups = row.get('Groups', '').split(", ")
app_label = row.get('app_label')
model = row.get('model')
# Configure the 'actions' field as a list with the permission name
actions = [permission_name] if permission_name else ['view']
# Get the corresponding content type
try:
content_type = ContentType.objects.get(app_label=app_label, model=model)
# Create or update the permission
permission, created = ObjectPermission.objects.get_or_create(
name=f"{permission_name.capitalize()} {model.capitalize()}",
defaults={
'description': f"Automatically generated permission: {permission_name}",
'enabled': True,
'actions': actions
}
)
# Assign content types and groups only if the permission was newly created
if created:
permission.object_types.set([content_type])
for group_name in groups:
try:
group = Group.objects.get(name=group_name)
permission.groups.add(group)
except Group.DoesNotExist:
self.log_warning(f"Group '{group_name}' does not exist. Skipping...")
self.log_success(f"Permission '{permission_name}' created or updated for the model '{model}'.")
except ContentType.DoesNotExist:
self.log_warning(f"ContentType '{app_label} > {model}' does not exist; skipping permission creation.")
except Exception as e:
self.log_error(f"Error processing the CSV file: {e}")