|
1 |
| -from django.contrib.auth.models import Permission |
| 1 | +import re |
2 | 2 |
|
| 3 | +from django.apps import apps |
| 4 | +from django.conf import settings |
| 5 | +from django.contrib.auth.models import Group, Permission |
| 6 | +from django.contrib.contenttypes.models import ContentType |
3 | 7 |
|
4 |
| -def assign_perm(perm, group): |
| 8 | +permissions_app_name = None |
| 9 | +perm_desc_regex = re.compile(r"(?P<app>\w+)\.(?P<codename>\w+)(?P<wild>\.\*)?") |
| 10 | + |
| 11 | + |
| 12 | +def get_permissions_app_name(): |
| 13 | + """ |
| 14 | + Gets the app after which smartmin permissions should be installed. This can be specified by PERMISSIONS_APP in the |
| 15 | + Django settings or defaults to the last app with models |
| 16 | + """ |
| 17 | + global permissions_app_name |
| 18 | + |
| 19 | + if not permissions_app_name: |
| 20 | + permissions_app_name = getattr(settings, "PERMISSIONS_APP", None) |
| 21 | + |
| 22 | + if not permissions_app_name: |
| 23 | + app_names_with_models = [a.name for a in apps.get_app_configs() if a.models_module is not None] |
| 24 | + if app_names_with_models: |
| 25 | + permissions_app_name = app_names_with_models[-1] |
| 26 | + |
| 27 | + return permissions_app_name |
| 28 | + |
| 29 | + |
| 30 | +def is_permissions_app(app_config): |
| 31 | + """ |
| 32 | + Returns whether this is the app after which permissions should be installed. |
| 33 | + """ |
| 34 | + return app_config.name == get_permissions_app_name() |
| 35 | + |
| 36 | + |
| 37 | +def update_group_permissions(group, permissions: list): |
| 38 | + """ |
| 39 | + Checks the the passed in role (can be user, group or AnonymousUser) has all the passed |
| 40 | + in permissions, granting them if necessary. |
| 41 | + """ |
| 42 | + |
| 43 | + new_permissions = [] |
| 44 | + |
| 45 | + for perm_desc in permissions: |
| 46 | + app_label, codename, wild = _parse_perm_desc(perm_desc) |
| 47 | + |
| 48 | + if wild: |
| 49 | + codenames = Permission.objects.filter( |
| 50 | + content_type__app_label=app_label, codename__startswith=f"{codename}_" |
| 51 | + ).values_list("codename", flat=True) |
| 52 | + else: |
| 53 | + codenames = [codename] |
| 54 | + |
| 55 | + perms = [] |
| 56 | + for codename in codenames: |
| 57 | + try: |
| 58 | + perms.append(Permission.objects.get(content_type__app_label=app_label, codename=codename)) |
| 59 | + except Permission.DoesNotExist: |
| 60 | + raise ValueError(f"Cannot grant permission {app_label}.{codename} as it does not exist.") |
| 61 | + |
| 62 | + new_permissions.append((app_label, codename)) |
| 63 | + |
| 64 | + group.permissions.add(*perms) |
| 65 | + |
| 66 | + # remove any that are extra |
| 67 | + for perm in group.permissions.select_related("content_type").all(): |
| 68 | + if (perm.content_type.app_label, perm.codename) not in new_permissions: |
| 69 | + group.permissions.remove(perm) |
| 70 | + |
| 71 | + |
| 72 | +def sync_permissions(sender, **kwargs): |
| 73 | + """ |
| 74 | + 1. Ensures all permissions decribed by the PERMISSIONS setting exist in the database. |
| 75 | + 2. Ensures all permissions granted by the GROUP_PERMISSIONS setting are granted to the appropriate groups. |
| 76 | + """ |
| 77 | + |
| 78 | + if not is_permissions_app(sender): |
| 79 | + return |
| 80 | + |
| 81 | + # for each of our items |
| 82 | + for natural_key, permissions in getattr(settings, "PERMISSIONS", {}).items(): |
| 83 | + # if the natural key '*' then that means add to all objects |
| 84 | + if natural_key == "*": |
| 85 | + # for each of our content types |
| 86 | + for content_type in ContentType.objects.all(): |
| 87 | + for permission in permissions: |
| 88 | + _ensure_permission_exists(content_type, permission) |
| 89 | + |
| 90 | + # otherwise, this is on a specific content type, add for each of those |
| 91 | + else: |
| 92 | + app, model = natural_key.split(".") |
| 93 | + try: |
| 94 | + content_type = ContentType.objects.get_by_natural_key(app, model) |
| 95 | + except ContentType.DoesNotExist: |
| 96 | + continue |
| 97 | + |
| 98 | + # add each permission |
| 99 | + for permission in permissions: |
| 100 | + _ensure_permission_exists(content_type, permission) |
| 101 | + |
| 102 | + # for each of our items |
| 103 | + for name, permissions in getattr(settings, "GROUP_PERMISSIONS", {}).items(): |
| 104 | + # get or create the group |
| 105 | + (group, created) = Group.objects.get_or_create(name=name) |
| 106 | + if created: |
| 107 | + pass |
| 108 | + |
| 109 | + update_group_permissions(group, permissions) |
| 110 | + |
| 111 | + |
| 112 | +def _parse_perm_desc(desc: str) -> tuple: |
5 | 113 | """
|
6 |
| - Assigns a permission to a group |
| 114 | + Parses a permission descriptor into its app_label, model and permission parts, e.g. |
| 115 | + app.model.* => app, model, True |
| 116 | + app.model_perm => app, model_perm, False |
7 | 117 | """
|
8 |
| - if not isinstance(perm, Permission): |
9 |
| - try: |
10 |
| - app_label, codename = perm.split(".", 1) |
11 |
| - except ValueError: |
12 |
| - raise ValueError( |
13 |
| - "For global permissions, first argument must be in" " format: 'app_label.codename' (is %r)" % perm |
14 |
| - ) |
15 |
| - perm = Permission.objects.get(content_type__app_label=app_label, codename=codename) |
16 | 118 |
|
17 |
| - group.permissions.add(perm) |
18 |
| - return perm |
| 119 | + match = perm_desc_regex.match(desc) |
| 120 | + if not match: |
| 121 | + raise ValueError(f"Invalid permission descriptor: {desc}") |
19 | 122 |
|
| 123 | + return match.group("app"), match.group("codename"), bool(match.group("wild")) |
20 | 124 |
|
21 |
| -def remove_perm(perm, group): |
| 125 | + |
| 126 | +def _ensure_permission_exists(content_type: str, permission: str): |
22 | 127 | """
|
23 |
| - Removes a permission from a group |
| 128 | + Adds the passed in permission to that content type. Note that the permission passed |
| 129 | + in should be a single word, or verb. The proper 'codename' will be generated from that. |
24 | 130 | """
|
25 |
| - if not isinstance(perm, Permission): |
26 |
| - try: |
27 |
| - app_label, codename = perm.split(".", 1) |
28 |
| - except ValueError: |
29 |
| - raise ValueError( |
30 |
| - "For global permissions, first argument must be in" " format: 'app_label.codename' (is %r)" % perm |
31 |
| - ) |
32 |
| - perm = Permission.objects.get(content_type__app_label=app_label, codename=codename) |
33 | 131 |
|
34 |
| - group.permissions.remove(perm) |
35 |
| - return |
| 132 | + codename = f"{content_type.model}_{permission}" # build our permission slug |
| 133 | + |
| 134 | + Permission.objects.get_or_create( |
| 135 | + content_type=content_type, codename=codename, defaults={"name": f"Can {permission} {content_type.name}"} |
| 136 | + ) |
0 commit comments