I threw together this Python function to check if a User has a certain Permission.
First of all, Permissions have this kind of format:
and can also include wildcards like this:
All the permissions a User has are stored in a list, so for example:
["app.cat1.*", "app.cat2.do.something", "app.cat2.cat3.*"]
You can then use the function below to check if a User has a certain Permission in his list:
def check_permission(needed_permission, permissions): #normalise needed permissions ending with a "." dot, convert filter to list again! needed_permissions_list = list(filter(None, needed_permission.split("."))) #loop over the permissions the user has, check if each matches the needed one until we find one and return True for permission in permissions: #permission is the permission the user already has and we are working on #permission_list is the list representation of the permission mentioned above permission_list = permission.split(".") #if the needed permission is exactly the same as the one we are working on, return True. E.g. needed: app.*, in list: app.* if permission_list == needed_permissions_list: return True #needed permission nearly matches, not the same because of wildcard. Return True if permission_list[-1] == "*" and (permission_list[:-1] == needed_permissions_list): return True #zip the to lists together to iterate zipped = zip(permission_list, needed_permissions_list) #iterate over the two lists simultaneousley for item, item2 in zipped: #whoa, an item doesn't match, time for further checks if item != item2: if item == "*": #it's not matching because it's a wildcard, so return True return True else: #it's not a wildcard, so it's definetely not the permission we are looking for break return True #nothing matched, return False. Permission we're looking for not in the list return False permissions = ["app.cat1.*", "app.cat2.do.something", "app.cat2.cat3.*"] assert check_permission("app.cat2.do.something", permissions) == True assert check_permission("app.cat2.do.something.special", permissions) == False assert check_permission("app.cat1.some.task", permissions) == True assert check_permission("app.cat2.cat4", permissions) == False assert check_permission("app.cat2.cat3.do.something.special", permissions) == True assert check_permission("something.completely.different", permissions) == False