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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
# Generated by Django 2.2.28 on 2024-11-04 16:52
from django.db import migrations
def clean_groups(profile_type):
# raw copy of the admin code
owns, full = {}, []
# get all permissions
for group in profile_type.groups.all():
permissions = []
own, gen = False, False
q = group.permissions
if not q.count():
continue
for permission in q.all():
if "_own_" in permission.codename:
own = True
else:
gen = True
parts = permission.codename.split("_")
permissions.append(f"{parts[0]}_{parts[-1]}")
if own and gen:
# group has "own" and "generic" permissions: do nothing
continue
permissions = tuple(sorted(permissions))
if own:
owns[permissions] = group
else:
full.append(permissions)
# clean
for permissions in owns.keys():
if len(permissions) == 1:
for full_permissions in full:
for full_permission in full_permissions:
if full_permission == permissions[0]:
profile_type.groups.remove(owns[permissions])
break
else:
if permissions in full:
profile_type.groups.remove(owns[permissions])
def migrate_permission(apps, __):
# clean delete permissions
Permission = apps.get_model("auth", "permission")
Group = apps.get_model("auth", "group")
ProfileType = apps.get_model("ishtar_common", "profiletype")
print()
for modif_group in Group.objects.filter(
name__endswith="modification/suppression").all():
name = modif_group.name.replace("/suppression", "")
modif_group.name = name
modif_group.save()
delete_permissions = []
for permission in modif_group.permissions.filter(
codename__startswith="change_").all():
codename = permission.codename.replace("change_", "delete_")
try:
delete_permission = Permission.objects.get(
content_type=permission.content_type,
codename=codename
)
delete_permissions.append(delete_permission)
if delete_permission in list(modif_group.permissions.all()):
modif_group.permissions.remove(delete_permission)
except Permission.DoesNotExist:
print(f"Permission {codename} does not exist")
if not delete_permissions:
continue
delete_group = Group.objects.create(
name=name.replace("modification", "suppression")
)
print(f"* New group: {delete_group.name}")
for delete_permission in delete_permissions:
delete_group.permissions.add(delete_permission)
for profile_type in ProfileType.objects.filter(groups__pk=modif_group.pk).all():
profile_type.groups.add(delete_group)
print(f"\t- profile type {profile_type.label} updated")
# clean groups
ProfileType = apps.get_model("ishtar_common", "ProfileType")
for pt in ProfileType.objects.all():
clean_groups(pt)
class Migration(migrations.Migration):
dependencies = [
('ishtar_common', '0254_permissionrequests'),
]
operations = [
migrations.RunPython(migrate_permission)
]
|