def create_predefined_roles(sender, **kwargs): """ This takes care of defining and creating set of predefined roles like partner_role """ from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from cloudapp.defaults import AppDefaults from users.models import Roles if ContentType.objects.filter( app_label='auth', model='group').exists() and ContentType.objects.filter( app_label='users', model='roles').exists(): predefined_roles = AppDefaults.get_predefined_roles() for role_alias, role_name in predefined_roles.items(): group_model = ContentType.objects.filter( app_label='auth', model='group')[0].model_class() # Creates new role if not created before if not group_model.objects.filter(name=role_name).exists(): access_specifiers = AppDefaults.get_predefined_role_access_specifiers( role_alias=role_alias) allowed_permissions_sets = [ AppDefaults.get_access_specifier_permissions(specifier)[0] for specifier in access_specifiers ] allowed_permissions = list( set([ item for sublist in allowed_permissions_sets for item in sublist ])) # Creating Group group_instance = group_model.objects.create(name=role_name) group_instance.permissions = Permission.objects.filter( id__in=allowed_permissions) if group_instance.save() is None: print( '\033[0;37;42m Generated new role "%s", Applying details... \033[0m' % role_alias) # Creating Role details role_instance = Roles.objects.create( group=group_instance, alias=role_alias, accesses=','.join(access_specifiers), description='Predefined role for %s' % role_alias) if role_instance.save() is None: print( '\033[0;37;42m Details applied for role: %s \033[0m' % role_alias) else: print('---- Error while generating predefined roles ---') print(' -Either auth.group or users.roles model does not exists !!!')
def jwt_response_payload_handler(token, user=None, request=None): """ Modifying jwt login response details """ user_details = UsersSerializer(user, context={'request': request}).data """ Fetching assigned accesses for the use """ user_details['accesses'] = list() if user.is_superuser: user_details[ 'accesses'] = AppDefaults.get_predefined_role_access_specifiers( 'Admin') else: access_joined = user.groups.all().values_list('details__accesses', flat=True) for string in access_joined: if string is not None: user_details['accesses'] += string.split(',') user_details['accesses'] = list(set(user_details['accesses'])) user_details['accesses'] = sorted(user_details['accesses']) return {'token': token, 'user': user_details}