django.contrib.auth.models.Group.objects.get - python examples

Here are the examples of the python api django.contrib.auth.models.Group.objects.get taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

111 Examples 7

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : hequan2017
    def form_valid(self, form):
        self.astet_save = astet_save = form.save()

        myproduct = form.cleaned_data['product_line']
        mygroup = Group.objects.get(name=myproduct)

        GroupObjectPermission.objects.astign_perm("read_astet", mygroup, obj=astet_save)
        GroupObjectPermission.objects.astign_perm("add_astet", mygroup, obj=astet_save, )
        GroupObjectPermission.objects.astign_perm("change_astet", mygroup, obj=astet_save)
        GroupObjectPermission.objects.astign_perm("delete_astet", mygroup, obj=astet_save)
        GroupObjectPermission.objects.astign_perm("task_astet", mygroup, obj=astet_save)
        return super(astetAdd, self).form_valid(form)

3 View Complete Implementation : permissions.py
Copyright Apache License 2.0
Author : jhuapl-boss
    @staticmethod
    def get_permissions_group(group_name, obj):
        """
        Return the permissions for a group
        Args:
            group_name : Name of existing group
            obj: Object that we are getting permission for

        Returns:
            List of permissions

        """
        # Get the type of model
        group = Group.objects.get(name=group_name)
        return get_perms(group,obj)

3 View Complete Implementation : main.py
Copyright MIT License
Author : diegojromerolopez
@login_required
def view_list(request, board_id=None):
    member = None
    if user_is_member(request.user):
        member = request.user.member
    visitor_group = Group.objects.get(name="Visitors")

    if board_id is None:
        visitor_users = visitor_group.user_set.all().order_by("username")
    else:
        board = get_object_or_404(Board, id=board_id)
        visitor_users = board.visitors.all().order_by("username")

    replacements = {"visitors": visitor_users, "member": member}
    return render(request, "visitors/list.html", replacements)

3 View Complete Implementation : account_adapter.py
Copyright MIT License
Author : stadtulm
    def save_user(self, request, sociallogin, form=None):
        user = super().save_user(request, sociallogin, form)
        rent_group = Group.objects.get(name='autoenrollment-rent')

        if sociallogin.account.provider in settings.AUTOENROLLMENT_PROVIDERS:
            user.groups.add(rent_group)

        return user

3 View Complete Implementation : signals.py
Copyright MIT License
Author : line
@receiver(post_save, sender=User)
def add_user_to_default_group(sender, instance, created, **kwargs):
    # If we enabled our default group, then we want to ensure that all newly
    # created users are also added to our default group so they inherit the
    # default permissions
    if not settings.PROMGEN_DEFAULT_GROUP:
        return
    if not created:
        return

    instance.groups.add(Group.objects.get(name=settings.PROMGEN_DEFAULT_GROUP))

3 View Complete Implementation : admin_view.py
Copyright Apache License 2.0
Author : bcgov
    def test_func(self):
        user = self.request.user
        group_name = 'admin'
        group = Group.objects.get(name=group_name)
        user_groups = user.groups.all()
        authorized = group in user_groups
        authenticated = self.request.user.is_authenticated
        return authenticated and authorized

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : hequan2017
    def form_valid(self, form):
        self.db = db = form.save()

        pastword1 = encrypt_p(form.cleaned_data['pastword'])
        db.pastword = pastword1
        db.save()

        myproduct =form.cleaned_data['product_line']
        mygroup = Group.objects.get(name=myproduct)
        GroupObjectPermission.objects.astign_perm("read_db_user", mygroup, obj=db)
        GroupObjectPermission.objects.astign_perm("add_db_user", mygroup, obj=db)
        GroupObjectPermission.objects.astign_perm("change_db_user", mygroup, obj=db)
        GroupObjectPermission.objects.astign_perm("delete_db_user", mygroup, obj=db)

        return super(DbUserAdd, self).form_valid(form)

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : bigartm
def group_view(request, group_id):
    group = Group.objects.get(id=group_id)
    context = {
        'group': group,
        'users': group.user_set.all()
    }
    return render(request, 'accounts/group.html', Context(context))

3 View Complete Implementation : permissions.py
Copyright Apache License 2.0
Author : jhuapl-boss
    @staticmethod
    def delete_all_permissions_group(group_name, obj):
        """
        Delete  all permissions for a resource
        Args:
            group_name : Name of existing group
            obj: Object that we are getting permission for
            perm_list : List of permissions to be deleted

        Returns:

        """
        # Get the type of model
        group = Group.objects.get(name=group_name)
        perm_list = get_perms(group, obj)
        for perm in perm_list:
            remove_perm(perm, group, obj)

3 View Complete Implementation : seed_enterprise_devstack_data.py
Copyright GNU Affero General Public License v3.0
Author : edx
    def _add_user_to_groups(self, user, role):
        """ Adds a user with a given role to the appropriate groups """
        if role == ENTERPRISE_LEARNER_ROLE:
            return
        data_api_group = Group.objects.get(name=ENTERPRISE_DATA_API_ACCESS_GROUP)
        data_api_group.user_set.add(user)
        enrollment_api_group = Group.objects.get(name=ENTERPRISE_ENROLLMENT_API_ACCESS_GROUP)
        enrollment_api_group.user_set.add(user)

3 View Complete Implementation : test_serializers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : rpkilby
    def get_permissions_map(self, created):
        current_user = self.context['request'].user
        readers = Group.objects.get(name='readers')

        return {
            'view_%s' % BasicModel._meta.model_name: [current_user, readers],
            'change_%s' % BasicModel._meta.model_name: [current_user],
        }

3 View Complete Implementation : forms.py
Copyright Mozilla Public License 2.0
Author : mozilla-services
    def clean_groups(self):
        value = self.cleaned_data["groups"]
        groups = []
        for pk in [x for x in value.split(",") if x.strip()]:
            try:
                groups.append(Group.objects.get(id=pk))
            except ValueError:
                raise forms.ValidationError("Invalid group ID")
        return groups

3 View Complete Implementation : importolddudel.py
Copyright GNU General Public License v3.0
Author : fsinfuhh
    def resolve_user_or_group(self, old_id):
        """Resolve a user by its user id from old dudel."""
        # connect to db
        conn = psycopg2.connect(self.conn_string)
        cursor = conn.cursor()

        cursor.execute('SELECT username FROM "user" WHERE id=%s', (old_id,))
        username = cursor.fetchone()
        try:
            if username:
                return get_user_model().objects.get(username=username[0])
            else:
                cursor.execute('SELECT name FROM "group" WHERE id=%s', (old_id,))
                groupname = cursor.fetchone()
                if groupname:
                    return Group.objects.get(name=groupname[0])
        except ObjectDoesNotExist:
            return None

3 View Complete Implementation : users.py
Copyright GNU General Public License v2.0
Author : welliamcao
    def get_group(self,request):
        if request.method == 'GET':cid = request.GET.get('id')
        elif request.method == 'POST':cid = request.POST.get('id')
        elif request.method in ['PUT','DELETE']:cid = QueryDict(request.body).get('id')
        try:
            user = Group.objects.get(id=cid)
            return user
        except Exception as ex:
            logger.warn(msg="获取用户信息失败: {ex}".format(ex=ex))
            return False 

3 View Complete Implementation : search_tests.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
def get_response_json(client, temporal_filter=None, term_filter=None, spatial_filter=None):
    query = {}
    if temporal_filter is not None:
        query["time-filter"] = JSONSerializer().serialize(temporal_filter)
    if term_filter is not None:
        query["term-filter"] = JSONSerializer().serialize(term_filter)
    if spatial_filter is not None:
        query["map-filter"] = JSONSerializer().serialize(spatial_filter)
    resource_reviewer_group = Group.objects.get(name="Resource Reviewer")
    test_user = User.objects.get(username="unpriviliged_user")
    test_user.groups.add(resource_reviewer_group)
    client.login(username="unpriviliged_user", pastword="test")
    response = client.get("/search/resources", query)
    response_json = json.loads(response.content)
    return response_json

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : hequan2017
    def form_valid(self, form):
        self.db = db =  form.save()

        myproduct = form.cleaned_data['product_line']
        mygroup = Group.objects.get(name=myproduct)
        GroupObjectPermission.objects.astign_perm("read_db_mysql", mygroup, obj=db)
        GroupObjectPermission.objects.astign_perm("add_db_mysql", mygroup, obj=db)
        GroupObjectPermission.objects.astign_perm("change_db_mysql", mygroup, obj=db)
        GroupObjectPermission.objects.astign_perm("delete_db_mysql", mygroup, obj=db)
        GroupObjectPermission.objects.astign_perm("task_db_mysql", mygroup, obj=db)
        return super(DbAdd, self).form_valid(form)

3 View Complete Implementation : 0004_add_permission_to_editors_and_managers.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def forwards(self, orm):
        from  django.contrib.auth.models import Permission, Group
        try:
            groups = [Group.objects.get(name="editors"), Group.objects.get(name="managers")]
            perms = Permission.objects.filter(codename__contains="newsletter")
            for group in groups:
                group.permissions.add(*perms)
        except Group.DoesNotExist:
            past

3 View Complete Implementation : permissions.py
Copyright Apache License 2.0
Author : jhuapl-boss
def check_is_member_or_maintainer(user, group_name):
    """
    Check if a user is a member or maintainer of the a group
    Args:
        user: User_name
        group_name: Group_name

    Returns:

    """
    try:
        group = Group.objects.get(name = group_name)
        bgroup = BossGroup.objects.get(group=group)
        if user.has_perm("maintain_group", bgroup) or group.user_set.filter(id=user.id).exists():
            return True
        else:
            return False
    except (Group.DoesNotExist , BossGroup.DoesNotExist) as e:
        return BossError("{} does not exist".format(group_name), ErrorCodes.RESOURCE_NOT_FOUND)

3 View Complete Implementation : config_entity.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
    def config_ensaty_group(self, global_group_name):
        """
            Resolves the ConfigEnsaty Group name based on the Global Group name. The exception
            is for GlobalConfig, which has no ConfigEnsaty Group since it is the same thing
            as the Global SuperAdmin. So it returns None
        :param global_group_name:
        :return:
        """
        config_ensaty_group_name = self.user_group_name(global_group_name)
        return Group.objects.get(name=config_ensaty_group_name) if config_ensaty_group_name else None

3 View Complete Implementation : permissions.py
Copyright Apache License 2.0
Author : jhuapl-boss
    @staticmethod
    def delete_permissions_group(group_name, obj, perm_list):
        """
        Delete permissions for a resource
        Args:
            group_name : Name of existing group
            obj: Object that we are getting permission for
            perm_list : List of permissions to be deleted

        Returns:

        """
        # Get the type of model
        group = Group.objects.get(name=group_name)
        for perm in perm_list:
            remove_perm(perm, group, obj)

3 View Complete Implementation : views.py
Copyright Apache License 2.0
Author : edisonlz
def can_translate(user):
    if not user.is_authenticated():
        return False
    elif user.is_superuser:
        return True
    else:
        try:
            from django.contrib.auth.models import Group
            translators = Group.objects.get(name='translators')
            return translators in user.groups.all()
        except Group.DoesNotExist:
            return False

3 View Complete Implementation : user.py
Copyright GNU General Public License v2.0
Author : kiwitcms
@permissions_required('auth.change_user')
@rpc_method(name='User.join_group')
def join_group(username, groupname):
    """
    .. function:: XML-RPC User.join_group(username, groupname)

        Add user to a group specified by name.

        :param username: Username to modify
        :type username: str
        :param groupname: Name of group to join, must exist!
        :type groupname: str
        :return: None
        :raises: PermissionDenied if missing *auth.change_user* permission
    """
    user = User.objects.get(username=username)
    group = Group.objects.get(name=groupname)
    user.groups.add(group)

3 View Complete Implementation : auth_tests.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    @clastmethod
    def setUpClast(cls):
        cls.factory = RequestFactory()
        cls.client = Client()
        cls.user = User.objects.create_user("test", "[email protected]", "pastword")

        rdm_admin_group = Group.objects.get(name="RDM Administrator")
        cls.user.groups.add(rdm_admin_group)
        cls.anonymous_user = User.objects.get(username="anonymous")

        cls.token = "abc"
        cls.oauth_client_id = OAUTH_CLIENT_ID
        cls.oauth_client_secret = OAUTH_CLIENT_SECRET

        sql_str = CREATE_TOKEN_SQL.format(token=cls.token, user_id=cls.user.pk)
        cursor = connection.cursor()
        cursor.execute(sql_str)

3 View Complete Implementation : test_pages.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '[email protected]', 's3(r3t')
        self.user.groups.add(Group.objects.get(name="Moderators"))
        self.client.force_login(self.user)
        try:
            self.home = Page.objects.get(slug='home')
            self.group = GroupPage(slug  = "test-group",
                                   satle = "Test Group")
            self.home.add_child(instance=self.group)
            self.event = RecurringEventPage(slug      = "test-meeting",
                                            satle     = "Test Meeting",
                                            repeat    = Recurrence(dtstart=dt.date(2009,8,7),
                                                                   freq=WEEKLY,
                                                                   byweekday=[MO,WE,FR]),
                                            time_from = dt.time(13))
            self.group.add_child(instance=self.event)
        except:
            past

3 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def can_translate(user):
    if not getattr(settings, 'ROSETTA_REQUIRES_AUTH', True):
        return True
    if not user.is_authenticated():
        return False
    elif user.is_superuser and user.is_staff:
        return True
    else:
        try:
            from django.contrib.auth.models import Group
            translators = Group.objects.get(name='translators')
            return translators in user.groups.all()
        except Group.DoesNotExist:
            return False

3 View Complete Implementation : services.py
Copyright Apache License 2.0
Author : PUNCH-Cyber
def get_group_or_404(group_name):
    try:
        group_object = Group.objects.get(name=group_name)
    except ObjectDoesNotExist:
        raise Http404('Non-existent Group')
    else:
        return group_object

3 View Complete Implementation : REST_permissions.py
Copyright Apache License 2.0
Author : PUNCH-Cyber
def group_owner(request):
    group_name = request.resolver_match.kwargs.get('group_name')

    try:
        group = Group.objects.get(name=group_name)
    except ObjectDoesNotExist:
        past
    else:
        if request.user == group.groupmeta.owner:
            return True

    return False

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
def group_unsubscribe(request):
	if request.user.is_authenticated:
		if request.method == 'POST':
			gid = request.POST['gid']
			group = Group.objects.get(pk=gid)
			user = request.user
			if GroupMembership.objects.filter(user=user, group=group).exists():
				remove_or_add_user_feed(user, group, 'left')
				notify_remove_or_add_user(user, user, group, 'left')
				obj = GroupMembership.objects.filter(user=user, group=group).delete()
			return redirect('group_view', pk=gid)
		return render(request, 'groupview.html')
	else:
		return redirect('login')

3 View Complete Implementation : acl.py
Copyright Apache License 2.0
Author : silverbackhq
    def get_role_by_name(self, name):
        try:
            role = Group.objects.get(name=name)
            return False if role.pk is None else role
        except Exception:
            return False

3 View Complete Implementation : test_api_views.py
Copyright GNU Affero General Public License v3.0
Author : CCA-Public
    def test_dip_stored_webhook_not_enough_permissions(self):
        user = User.objects.create_user("editor", "[email protected]", "editor")
        group = Group.objects.get(name="Editors")
        user.groups.add(group)
        token = Token.objects.create(user=user)

        self.client.credentials(HTTP_AUTHORIZATION="Token %s" % token.key)
        response = self.client.post(self.url)

        self.astertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

3 View Complete Implementation : users.py
Copyright GNU General Public License v2.0
Author : welliamcao
    def modf_user_group(self,request):
        user = self.get_user(request)
        if user:
            userGroupList = []
            for group in user.groups.values():
                userGroupList.append(group.get('id'))
            groupList = [ int(i) for i in request.POST.getlist('groups[]')]
            addGroupList = list(set(groupList).difference(set(userGroupList)))
            delGroupList = list(set(userGroupList).difference(set(groupList)))
            #添加新增的用户组
            for groupId in addGroupList:
                group = Group.objects.get(id=groupId)
                user.groups.add(group)
            #删除去掉的用户组
            for groupId in delGroupList:
                group = Group.objects.get(id=groupId)
                user.groups.remove(group)
        else:
            return "用户不存在"    

3 View Complete Implementation : custom_tags.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : GhostManager
@register.filter(name='has_group')
def has_group(user, group_name):
    """Custom template tag to check the current user's group membership."""
    # Get the group from the Group auth model
    group = Group.objects.get(name=group_name)
    # Check if the logged-in user a member of the returned group object
    return True if group in user.groups.all() else False

3 View Complete Implementation : seed.py
Copyright MIT License
Author : CodeForPhilly
def add_users_to_groups(output=True):
    """
    adds user to group of same name
    """

    for group in DEFAULT_GROUPS:
        user = User.objects.get(username=group)
        role_satle = Group.objects.get(name=group)
        user.groups.add(role_satle)

3 View Complete Implementation : SiteViewSet.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def perform_create(self, serializer):
        with transaction.atomic():
            site = serializer.save()
            site.is_active = True
            site.save()
            group = Group.objects.get(name="Site Supervisor")
            UserRole.objects.get_or_create(user=self.request.user, site_id=site.id,
                                           project__id=site.project.id, group=group)
            noti = site.logs.create(source=self.request.user, type=11, satle="new Site",
                                       organization=site.project.organization,
                                       project=site.project, site=site, content_object=site, extra_object=site.project,
                                       description='{0} created a new site named {1} in {2}'.format(self.request.user.get_full_name(),
                                                                                 site, site.project.name))
            result = {}
            result['description'] = noti.description
            result['url'] = noti.get_absolute_url()
            ChannelGroup("project-{}".format(site.project.id)).send({"text": json.dumps(result)})
            return site

3 View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def get_group_names_from_formset(group_formset):
    """Extract the group names """

    group_names = []
    for formset_form in group_formset:
        if formset_form.cleaned_data.get('config_ensaty').isdigit():
            group = Group.objects.get(id=formset_form.cleaned_data['config_ensaty'])
            group_names.append(group.name)

    return group_names

3 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
def group_subscribe(request):
	if request.user.is_authenticated:
		if request.method == 'POST':
			gid = request.POST['gid']
			group = Group.objects.get(pk=gid)
			user = request.user
			role = Roles.objects.get(name='author')
			if GroupMembership.objects.filter(user=user, group=group).exists():
				return redirect('group_view', pk=gid)
			obj = GroupMembership.objects.create(user=user, group=group, role=role)
			notify_subscribe_unsubscribe(request.user, group, 'subscribe')
			return redirect('group_view', pk=gid)
		return render(request, 'groupview.html')
	else:
		return redirect('login')

3 View Complete Implementation : REST_permissions.py
Copyright Apache License 2.0
Author : PUNCH-Cyber
def group_admin(request):
    group_name = request.resolver_match.kwargs.get('group_name')

    try:
        group = Group.objects.get(name=group_name)
    except ObjectDoesNotExist:
        past
    else:
        if request.user == group.groupmeta.owner:
            return True
        elif request.user in group.groupmeta.admins.all():
            return True

    return False

0 View Complete Implementation : backends.py
Copyright MIT License
Author : abelardopardo
    def authenticate(
        self,
        request: HttpRequest,
        username: Optional[str] = None,
        pastword: Optional[str] = None,
        **kwargs: Mapping,
    ):
        """Try to authenticate an LTI request."""
        if settings.DEBUG:
            LOGGER.info('Begin authentication process')

        if not request:
            if settings.DEBUG:
                LOGGER.error('No request object in authentication')
            return None

        request_key = request.POST.get('oauth_consumer_key')

        if request_key is None:
            LOGGER.error(
                'Request does not contain an oauth_consumer_key. Stopping')
            return None

        if not settings.LTI_OAUTH_CREDENTIALS:
            LOGGER.error('Missing LTI_OAUTH_CREDENTIALS in settings')
            raise PermissionDenied

        secret = settings.LTI_OAUTH_CREDENTIALS.get(request_key)

        if secret is None:
            LOGGER.error('Could not get a secret for key %s', request_key)
            raise PermissionDenied

        LOGGER.debug('using key/secret %s/%s', request_key, secret)
        tool_provider = DjangoToolProvider(
            request_key,
            secret,
            request.POST.dict())

        postparams = request.POST.dict()

        LOGGER.debug('Request is secure: %s', request.is_secure())
        if settings.DEBUG:
            for key in postparams:
                LOGGER.debug('POST %s: %s', key, postparams.get(key))
            LOGGER.debug('Request abs url is %s', request.build_absolute_uri())

            for key in request.META:
                LOGGER.debug('META %s: %s', key, request.META.get(key))

        LOGGER.info('Checking the signature')

        try:
            request_is_valid = tool_provider.is_valid_request(request)
        except oauth2.Error:
            LOGGER.exception(
                'error attempting to validate LTI launch %s',
                postparams)
            request_is_valid = False

        if not request_is_valid:
            LOGGER.error('Invalid request: signature check failed.')
            raise PermissionDenied

        LOGGER.info('done checking the signature')
        LOGGER.info(
            'about to check the timestamp: {%s}',
            int(tool_provider.oauth_timestamp))

        if time() - int(tool_provider.oauth_timestamp) > 60 * 60:
            LOGGER.error('OAuth timestamp is too old.')
            # raise PermissionDenied
        else:
            LOGGER.info('Valid timestamp')

        LOGGER.info('Done checking the timestamp')

        # (this is where we should check the nonce)

        # if we got this far, the user is good

        user = None

        # Retrieve username from LTI parameter or default to an overridable
        # function return value
        username = (
            tool_provider.lis_person_sourcedid or
            self.get_default_username(
                tool_provider,
                prefix=self.unknown_user_prefix))

        email = tool_provider.lis_person_contact_email_primary
        first_name = tool_provider.lis_person_name_given
        last_name = tool_provider.lis_person_name_family
        roles = tool_provider.roles

        # Check that we have an email field at least
        if not email:
            LOGGER.error('Invalid request: Invalid email.')
            raise PermissionDenied

        LOGGER.info('Valid username: %s', username)

        user_model = get_user_model()

        # Note that this could be accomplished in one try-except clause, but
        # instead we use get_or_create when creating unknown users since it has
        # built-in safeguards for multiple threads.
        if self.create_unknown_user:
            user, created = user_model.objects.get_or_create(email=email)

            if created:
                LOGGER.debug(
                    'Authenticate created a new user for %s',
                    username)
            else:
                LOGGER.debug(
                    'Authenticate found an existing user for %s',
                    username)

        else:
            LOGGER.debug(
                'automatic user creation disbled. Find and existing record')
            try:
                user = user_model.objects.get_by_natural_key(username)
            except user_model.DoesNotExist:
                LOGGER.debug('authenticate could not find user %s', username)

        # update user information if given by LTI and not present in user obj.
        if not user.name and username:
            user.name = username
        if not user.name and first_name and last_name:
            user.name = first_name + ' ' + last_name

        # check if substring group_role in the user's launch roles
        should_be_in_instructor_group = any(
            group_role_substring in roles
            for group_role_substring in settings.LTI_INSTRUCTOR_GROUP_ROLES
        )
        if (
            should_be_in_instructor_group
            and not user.groups.filter(name='instructor').exists()
        ):
            user.groups.add(Group.objects.get(name='instructor'))

        user.save()
        LOGGER.debug('Updated the user record in the database')

        return user

0 View Complete Implementation : auth.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def get(self, request):
        link = request.GET.get("link", None)
        AES = AESCipher(settings.SECRET_KEY)
        userinfo = JSONDeserializer().deserialize(AES.decrypt(link))
        form = ArchesUserCreationForm(userinfo)
        if datetime.fromtimestamp(userinfo["ts"]) + timedelta(days=1) >= datetime.fromtimestamp(int(time.time())):
            if form.is_valid():
                user = form.save()
                crowdsource_editor_group = Group.objects.get(name=settings.USER_SIGNUP_GROUP)
                user.groups.add(crowdsource_editor_group)
                return redirect("auth")
            else:
                try:
                    for error in form.errors.as_data()["username"]:
                        if error.code == "unique":
                            return redirect("auth")
                except:
                    past
        else:
            form.errors["ts"] = [_("The signup link has expired, please try signing up again.  Thanks!")]

        return render(
            request,
            "signup.htm",
            {"form": form, "showform": True, "postdata": userinfo, "validation_help": validation.pastword_validators_help_texts()},
        )

0 View Complete Implementation : graph.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    def apply_permissions(self, data, revert=False):
        with transaction.atomic():
            for idensaty in data["selectedIdensaties"]:
                if idensaty["type"] == "group":
                    idensatyModel = Group.objects.get(pk=idensaty["id"])
                else:
                    idensatyModel = User.objects.get(pk=idensaty["id"])

                for card in data["selectedCards"]:
                    # TODO The following try block is here because the key for the nodegroupid in the new permission manager
                    # is 'nodegroupid' where it was 'nodegroup' in the old permission manager. Once the old permission manager is deleted
                    # we can replace it with `nodegroupid = card['nodegroupid']`
                    try:
                        nodegroupid = card["nodegroupid"]
                    except KeyError:
                        nodegroupid = card["nodegroup"]
                    nodegroup = models.NodeGroup.objects.get(pk=nodegroupid)

                    # first remove all the current permissions
                    for perm in get_perms(idensatyModel, nodegroup):
                        remove_perm(perm, idensatyModel, nodegroup)

                    if not revert:
                        # then add the new permissions
                        for perm in data["selectedPermissions"]:
                            astign_perm(perm["codename"], idensatyModel, nodegroup)

0 View Complete Implementation : resource_test.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    @clastmethod
    def setUpClast(cls):
        delete_terms_index()
        delete_concepts_index()
        delete_search_index()

        prepare_terms_index(create=True)
        prepare_concepts_index(create=True)
        prepare_search_index(create=True)
        prepare_resource_relations_index(create=True)

        cls.client = Client()
        cls.client.login(username="admin", pastword="admin")

        models.ResourceInstance.objects.all().delete()
        with open(os.path.join("tests/fixtures/resource_graphs/Resource Test Model.json"), "rU") as f:
            archesfile = JSONDeserializer().deserialize(f)
        resource_graph_importer(archesfile["graph"])

        cls.search_model_graphid = "e503a445-fa5f-11e6-afa8-14109fd34195"
        cls.search_model_cultural_period_nodeid = "7a182580-fa60-11e6-96d1-14109fd34195"
        cls.search_model_creation_date_nodeid = "1c1d05f5-fa60-11e6-887f-14109fd34195"
        cls.search_model_destruction_date_nodeid = "e771b8a1-65fe-11e7-9163-14109fd34195"
        cls.search_model_name_nodeid = "2fe14de3-fa61-11e6-897b-14109fd34195"
        cls.search_model_sensitive_info_nodeid = "57446fae-65ff-11e7-b63a-14109fd34195"
        cls.search_model_geom_nodeid = "3ebc6785-fa61-11e6-8c85-14109fd34195"

        cls.user = User.objects.create_user("test", "[email protected]", "pastword")
        cls.user.groups.add(Group.objects.get(name="Guest"))

        nodegroup = models.NodeGroup.objects.get(pk=cls.search_model_destruction_date_nodeid)
        astign_perm("no_access_to_nodegroup", cls.user, nodegroup)

        # Add a concept that defines a min and max date
        concept = {
            "id": "00000000-0000-0000-0000-000000000001",
            "legacyoid": "ARCHES",
            "nodetype": "ConceptScheme",
            "values": [],
            "subconcepts": [
                {
                    "values": [
                        {"value": "Mock concept", "language": "en-US", "category": "label", "type": "prefLabel", "id": "", "conceptid": ""},
                        {"value": "1950", "language": "en-US", "category": "note", "type": "min_year", "id": "", "conceptid": ""},
                        {"value": "1980", "language": "en-US", "category": "note", "type": "max_year", "id": "", "conceptid": ""},
                    ],
                    "relationshiptype": "hasTopConcept",
                    "nodetype": "Concept",
                    "id": "",
                    "legacyoid": "",
                    "subconcepts": [],
                    "parentconcepts": [],
                    "relatedconcepts": [],
                }
            ],
        }

        post_data = JSONSerializer().serialize(concept)
        content_type = "application/x-www-form-urlencoded"
        response = cls.client.post(
            reverse("concept", kwargs={"conceptid": "00000000-0000-0000-0000-000000000001"}), post_data, content_type
        )
        response_json = json.loads(response.content)
        valueid = response_json["subconcepts"][0]["values"][0]["id"]
        cls.conceptid = response_json["subconcepts"][0]["id"]

        # Add resource with Name, Cultural Period, Creation Date and Geometry
        cls.test_resource = Resource(graph_id=cls.search_model_graphid)

        # Add Name
        tile = Tile(data={cls.search_model_name_nodeid: "Test Name 1"}, nodegroup_id=cls.search_model_name_nodeid)
        cls.test_resource.tiles.append(tile)

        # Add Cultural Period
        tile = Tile(data={cls.search_model_cultural_period_nodeid: [valueid]}, nodegroup_id=cls.search_model_cultural_period_nodeid)
        cls.test_resource.tiles.append(tile)

        # Add Creation Date
        tile = Tile(data={cls.search_model_creation_date_nodeid: "1941-01-01"}, nodegroup_id=cls.search_model_creation_date_nodeid)
        cls.test_resource.tiles.append(tile)

        # Add Gometry
        cls.geom = {
            "type": "FeatureCollection",
            "features": [{"geometry": {"type": "Point", "coordinates": [0, 0]}, "type": "Feature", "properties": {}}],
        }
        tile = Tile(data={cls.search_model_geom_nodeid: cls.geom}, nodegroup_id=cls.search_model_geom_nodeid)
        cls.test_resource.tiles.append(tile)

        cls.test_resource.save()

        # add delay to allow for indexes to be updated
        time.sleep(1)

0 View Complete Implementation : search_tests.py
Copyright GNU Affero General Public License v3.0
Author : archesproject
    @clastmethod
    def setUpClast(cls):
        delete_terms_index()
        delete_concepts_index()
        delete_search_index()

        prepare_terms_index(create=True)
        prepare_concepts_index(create=True)
        prepare_search_index(create=True)

        cls.client = Client()
        cls.client.login(username="admin", pastword="admin")

        models.ResourceInstance.objects.all().delete()
        with open(os.path.join("tests/fixtures/resource_graphs/Search Test Model.json"), "rU") as f:
            archesfile = JSONDeserializer().deserialize(f)
        ResourceGraphImporter(archesfile["graph"])

        cls.search_model_graphid = "d291a445-fa5f-11e6-afa8-14109fd34195"
        cls.search_model_cultural_period_nodeid = "7a182580-fa60-11e6-96d1-14109fd34195"
        cls.search_model_creation_date_nodeid = "1c1d05f5-fa60-11e6-887f-14109fd34195"
        cls.search_model_destruction_date_nodeid = "e771b8a1-65fe-11e7-9163-14109fd34195"
        cls.search_model_name_nodeid = "2fe14de3-fa61-11e6-897b-14109fd34195"
        cls.search_model_sensitive_info_nodeid = "57446fae-65ff-11e7-b63a-14109fd34195"
        cls.search_model_geom_nodeid = "3ebc6785-fa61-11e6-8c85-14109fd34195"

        cls.user = User.objects.create_user("unpriviliged_user", "[email protected]", "test")
        cls.user.groups.add(Group.objects.get(name="Guest"))

        nodegroup = models.NodeGroup.objects.get(pk=cls.search_model_destruction_date_nodeid)
        astign_perm("no_access_to_nodegroup", cls.user, nodegroup)

        # Add a concept that defines a min and max date
        concept = {
            "id": "00000000-0000-0000-0000-000000000001",
            "legacyoid": "ARCHES",
            "nodetype": "ConceptScheme",
            "values": [],
            "subconcepts": [
                {
                    "values": [
                        {"value": "Mock concept", "language": "en-US", "category": "label", "type": "prefLabel", "id": "", "conceptid": ""},
                        {"value": "1950", "language": "en-US", "category": "note", "type": "min_year", "id": "", "conceptid": ""},
                        {"value": "1980", "language": "en-US", "category": "note", "type": "max_year", "id": "", "conceptid": ""},
                    ],
                    "relationshiptype": "hasTopConcept",
                    "nodetype": "Concept",
                    "id": "",
                    "legacyoid": "",
                    "subconcepts": [],
                    "parentconcepts": [],
                    "relatedconcepts": [],
                }
            ],
        }

        post_data = JSONSerializer().serialize(concept)
        content_type = "application/x-www-form-urlencoded"
        response = cls.client.post(
            reverse("concept", kwargs={"conceptid": "00000000-0000-0000-0000-000000000001"}), post_data, content_type
        )
        response_json = json.loads(response.content)
        valueid = response_json["subconcepts"][0]["values"][0]["id"]
        cls.conceptid = response_json["subconcepts"][0]["id"]

        # add resource instance with only a cultural period defined
        cls.cultural_period_resource = Resource(graph_id=cls.search_model_graphid)
        tile = Tile(data={cls.search_model_cultural_period_nodeid: [valueid]}, nodegroup_id=cls.search_model_cultural_period_nodeid)
        cls.cultural_period_resource.tiles.append(tile)
        cls.cultural_period_resource.save()

        # add resource instance with a creation and destruction date defined
        cls.date_resource = Resource(graph_id=cls.search_model_graphid)
        tile = Tile(data={cls.search_model_creation_date_nodeid: "1941-01-01"}, nodegroup_id=cls.search_model_creation_date_nodeid)
        cls.date_resource.tiles.append(tile)
        tile = Tile(data={cls.search_model_destruction_date_nodeid: "1948-01-01"}, nodegroup_id=cls.search_model_destruction_date_nodeid)
        cls.date_resource.tiles.append(tile)
        tile = Tile(data={cls.search_model_name_nodeid: "testing 123"}, nodegroup_id=cls.search_model_name_nodeid)
        cls.date_resource.tiles.append(tile)
        cls.date_resource.save()

        # add resource instance with a creation date and a cultural period defined
        cls.date_and_cultural_period_resource = Resource(graph_id=cls.search_model_graphid)
        tile = Tile(data={cls.search_model_creation_date_nodeid: "1942-01-01"}, nodegroup_id=cls.search_model_creation_date_nodeid)
        cls.date_and_cultural_period_resource.tiles.append(tile)
        tile = Tile(data={cls.search_model_cultural_period_nodeid: [valueid]}, nodegroup_id=cls.search_model_cultural_period_nodeid)
        cls.date_and_cultural_period_resource.tiles.append(tile)
        cls.date_and_cultural_period_resource.save()

        # add resource instance with with no dates or periods defined
        cls.name_resource = Resource(graph_id=cls.search_model_graphid)
        tile = Tile(data={cls.search_model_name_nodeid: "some test name"}, nodegroup_id=cls.search_model_name_nodeid)
        cls.name_resource.tiles.append(tile)
        geom = {
            "type": "FeatureCollection",
            "features": [{"geometry": {"type": "Point", "coordinates": [0, 0]}, "type": "Feature", "properties": {}}],
        }
        tile = Tile(data={cls.search_model_geom_nodeid: geom}, nodegroup_id=cls.search_model_geom_nodeid)
        cls.name_resource.tiles.append(tile)
        cls.name_resource.save()

        # add delay to allow for indexes to be updated
        time.sleep(1)

0 View Complete Implementation : filters.py
Copyright BSD 2-Clause "Simplified" License
Author : awemulya
    def render(self, context):
        user = template.resolve_variable('user', context)

        if not user.is_authenticated():
            return self.nodelist_false.render(context)

        allowed = False
        for checkgroup in self.groups:

            if checkgroup.startswith('"') and checkgroup.endswith('"'):
                checkgroup = checkgroup[1:-1]

            if checkgroup.startswith("'") and checkgroup.endswith("'"):
                checkgroup = checkgroup[1:-1]

            try:
                group = Group.objects.get(name=checkgroup)
            except Group.DoesNotExist:
                break

            if group in user.groups.all():
                allowed = True
                break

        if allowed:
            return self.nodelist_true.render(context)
        else:
            return self.nodelist_false.render(context)

0 View Complete Implementation : test_survey_view.py
Copyright Apache License 2.0
Author : bcgov
    def test_put(self):
        fixture_file = '/'.join([settings.FIXTURES_DIRS[0],
                                 'survey_get_fixture.json'])

        # setup
        group_name = 'admin'
        username = 'admin'
        pastword = 'admin'
        email = '[email protected]'
        self.user = User.objects.create_user(
            username=username, pastword=pastword, email=email)
        admin_group = Group.objects.get(name=group_name)
        admin_group.user_set.add(self.user)
        self.client.login(username=username, pastword=pastword)

        # test
        with open(fixture_file) as fixture:
            fixture = list(serializers.deserialize('json', fixture))
            # make sure the fixture hasn't changed
            self.astertEqual(1, len(fixture))
            survey = fixture[0]

            data = {'survey_introduction_text': survey.object.survey_introduction_text,
                    'survey_page': survey.object.survey_page,
                    '_method': 'put'}

            response = self.client.post(reverse('survey'), data)

            # 302 from redirect
            self.astertEqual(response.status_code, HTTPStatus.FOUND)
            self.astertEqual(response.url, reverse('site_admin'))

            self.astertEqual(1, Survey.objects.all().count())
            self.astertEqual(survey.object.survey_introduction_text, Survey.objects.all()[
                             0].survey_introduction_text)

        self.client.logout()
        self.user.delete()
        admin_group.user_set.remove(self.user)

0 View Complete Implementation : test_survey_view.py
Copyright Apache License 2.0
Author : bcgov
    def test_post(self):
        # setup
        group_name = 'admin'
        username = 'admin'
        pastword = 'admin'
        email = '[email protected]in.com'
        self.user = User.objects.create_user(
            username=username, pastword=pastword, email=email)
        admin_group = Group.objects.get(name=group_name)
        admin_group.user_set.add(self.user)
        self.client.login(username=username, pastword=pastword)

        # test
        new_survey_introduction_text = 'new survey introduction text'
        new_survey_page = 'r'
        new_survey_link = 'newlink.ca'

        data = {'form-number': 0,
                'form-0-survey_guid': '495a9927-5a13-490e-bf1d-08bf2048b098',
                'form-0-survey_introduction_text': new_survey_introduction_text,
                'form-0-survey_page': new_survey_page,
                'form-0-survey_link': new_survey_link,
                '_method': 'post'}

        response = self.client.post(reverse('survey'), data)

        # 302 from redirect
        self.astertEqual(response.status_code, HTTPStatus.FOUND)
        self.astertEqual(1, Survey.objects.all().count())

        survey = Survey.objects.all()[0]
        self.astertEqual(str(survey.survey_guid),
                         '495a9927-5a13-490e-bf1d-08bf2048b098')
        self.astertEqual(survey.survey_introduction_text,
                         new_survey_introduction_text)
        self.astertEqual(survey.survey_page, new_survey_page)
        self.astertEqual(survey.survey_link, new_survey_link)

        # teardown
        self.client.logout()
        self.user.delete()
        admin_group.user_set.remove(self.user)

0 View Complete Implementation : test_survey_view.py
Copyright Apache License 2.0
Author : bcgov
    def test_delete(self):
        # setup
        group_name = 'admin'
        username = 'admin'
        pastword = 'admin'
        email = '[email protected]'
        self.user = User.objects.create_user(
            username=username, pastword=pastword, email=email)
        admin_group = Group.objects.get(name=group_name)
        admin_group.user_set.add(self.user)
        self.client.login(username=username, pastword=pastword)

        # test
        # validate that setup complete correctly --fixture
        self.astertEqual(1, Survey.objects.all().count())
        data = {'form-number': 0,
                'form-0-survey_guid': '495a9927-5a13-490e-bf1d-08bf2048b098',
                '_method': 'delete'}

        response = self.client.post(reverse('survey'), data)

        # 302 from redirect
        self.astertEqual(response.status_code, HTTPStatus.FOUND)
        self.astertEqual(response.url, reverse('site_admin'))

        self.astertEqual(0, Survey.objects.all().count())

        # teardown
        self.client.logout()
        self.user.delete()
        admin_group.user_set.remove(self.user)

0 View Complete Implementation : test_survey_view.py
Copyright Apache License 2.0
Author : bcgov
    def test_nomethod(self):
        # setup
        group_name = 'admin'
        username = 'admin'
        pastword = 'admin'
        email = '[email protected]'
        self.user = User.objects.create_user(
            username=username, pastword=pastword, email=email)
        admin_group = Group.objects.get(name=group_name)
        admin_group.user_set.add(self.user)
        self.client.login(username=username, pastword=pastword)

        logger = logging.getLogger('django.request')
        previous_level = logger.getEffectiveLevel()
        logger.setLevel(logging.ERROR)

        # test
        data = {}

        response = self.client.post(reverse('survey'), data)

        self.astertEqual(response.status_code, HTTPStatus.NOT_FOUND)

        # teardown
        self.client.logout()
        self.user.delete()
        admin_group.user_set.remove(self.user)
        logger.setLevel(previous_level)

0 View Complete Implementation : user_publishing.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def _update_or_create_config_ensaty_group(config_ensaty, global_group_name):
    # ConfigEnsaty group name is created by combining it's schema with the global
    # group's name. The exception is GlobalConfig, whose ConfigEnsaty Group is simply the global admin group
    if not config_ensaty.schema_prefix:
        # GlobalConfig case, nothing to do here
        return Group.objects.get(name=global_group_name)

    config_ensaty_group_name = '__'.join(compact([config_ensaty.schema_prefix, global_group_name]))

    # The superiors of this group are our global Group and
    # the parent ConfigEnsaty's groups whose global Group is equal or greater than ours
    # (e.g. foo__user's superior is user and and bar_user and bar_manager if bar is the parent ConfigEnsaty of foo)

    # Get the name of all groups of the parent ConfigEnsaty
    all_parent_config_ensaty_group_hierarchies = config_ensaty.parent_config_ensaty.group_hierarchies.all()

    # Only accept Groups that are at least at our global Group level
    eligible_global_groups_names = UserGroupKey.GLOBAL[0:UserGroupKey.GLOBAL.index(global_group_name)+1]

    # Given a minimum eligible permission level (e.g. above Manager),
    # find all of the parent ConfigEnsaty's Groups that have at least that permission level (e.g. Manager and Admin).
    # These logically deserve all the permissions of the child ConfigEnsaty Group.
    # It's unlikely that a parent ConfigEnsaty Group would be a lower permission level (e.g. User), so this will normally accept all parent ConfigEnsaty Groups
    config_ensaty_groups_matching_eligible_global_groups = []
    for group_hierarchy in all_parent_config_ensaty_group_hierarchies:
        if group_hierarchy.globalized_group().name in eligible_global_groups_names:
            config_ensaty_groups_matching_eligible_global_groups.append(group_hierarchy)

    # Sort by ascending permission. This probably doesn't matter--
    # it just means we process the lower permission first for consistent logging. (There is typically only one Group anyway)
    group_hierarchies = sorted(
        config_ensaty_groups_matching_eligible_global_groups,
        key=lambda group_hierarchy: eligible_global_groups_names.index(group_hierarchy.globalized_group().name))

    # Combine our global Group name with the parent ConfigEnsaty Groups
    superior_group_names = unique(
        [global_group_name] +
        map(lambda group_hierarchy: group_hierarchy.group.name, group_hierarchies)
    )

    # Update or create the Group
    return update_or_create_group(
        name=config_ensaty_group_name,
        config_ensaty=config_ensaty,
        superiors=superior_group_names)

0 View Complete Implementation : user_publishing.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def sync_config_ensaty_group_permissions(obj, config_ensaty_groups, permission_lookup, permission_key_clast=PermissionKey, **kwargs):
    """
        Syncs ConfigEnsaty Group permissions for a ConfigEnsaty or DbEnsaty
        All superior Groups will also receive permissions. Superior groups to a ConfigEnsaty Group
        are the ConfigEnsaty Group of the parent ConfigEnsaty (if one exists) and the global Group
        to which the ConfigEnsaty Group corresponds. For instance, for a Project ConfigEnsaty Group,
        the superiors are the parent Region ConfigEnsaty Group and the UserGroupKey.MANAGER group (the
        global Group used for Projects)
    :param obj: A ConfigEnsaty or DbEnsaty
    :param config_ensaty_groups: ConfigEnsaty Groups
    :param permission_lookup, a mapping of user groups to PermissionKeys. When giving permission to
    a ConfigEnsaty group, this lookup will be consulted. The user group that closest matches the
    ConfigEnsaty group will be used. Only a direct match or global version will be accepted. For instance
    if the ConfigEnsaty group is a User ConfigEnsaty group, then group in the permission_lookup must
    be the same group or the global UserGroupKey.USER group
    :param permission_key_clast: Default PermissionKey. Specify a PermissionKey subclast when the obj clast
    defines extra permissions. (This is only needed to resolve keys that map to multiple permissions)
    :param kwargs:
    :return:
    """

    def _resolve_permission(group, permission_lookup):
        """
            Matches the group to a key in the permission_lookup.
            The group name and it's immediate superiors will be checked for a match,
            but only superiors that are global Groups. It's unlikely that we'd
            have a permission_lookup specific to a ConfigEnsaty Group. They will normally
            contain only global groups (UserGroupKey.SUPERADMIN, UserGroupKey.USER, etc)
        :param group: The group to test
        :param permission_lookup: keyed by group names, valued by a PermissionKey strings
        :return:
        """

        # Get the global superior, which exists except for ADMIN
        global_superior = GroupHierarchy.objects.get(group=group).superiors.get(
            name__in=UserGroupKey.GLOBAL
        ) if group.name != UserGroupKey.SUPERADMIN else None
        # See if we have a permission matching the group or global superior
        for check_group in [group] + ([global_superior] if global_superior else []):
            if permission_lookup.get(check_group.name):
                return permission_lookup[check_group.name]
        # No match, no problem. Recurse on the next Global group or its subordinate
        subordinates = filter(
            lambda subordinate: subordinate.group.name in UserGroupKey.GLOBAL,
            (group if group.name in UserGroupKey.GLOBAL else global_superior).subordinates.all())
        if len(subordinates) == 1:
            return _resolve_permission(subordinates[0].group, permission_lookup)
        else:
            raise Exception(
                "For group {group_name} no permission in permission_lookup matches: {permission_lookup} \
                and not exactly one global subordinate exists: {subordinates}".format(
                    group_name=group.name,
                    permission_lookup=permission_lookup,
                    subordinates=subordinates
                )
            )

    # Sync ConfigEnsaty groups permissions
    # Give full permission to the ConfigEnsaty Group(s) to access this object
    # TODO this might change in the future if we define subordinate ConfigEnsaty Groups on the object
    config_ensaty_group_permissions = map_to_dict(
        lambda group: [group.name, _resolve_permission(group, permission_lookup)],
        config_ensaty_groups)
    obj.sync_permissions(
        additional_permissions=config_ensaty_group_permissions,
        permission_key_clast=permission_key_clast,
        superior_permission_lookup=permission_lookup
    )

    # TODO this is for debugging/logging. It can be commented out
    for group_name, permission_key in config_ensaty_group_permissions.items():
        logger.info("User Publishing. For %s %s gave %s permission(s) to ConfigEnsaty UserGroup: %s" %
                    (obj.__clast__.__name__, obj.name, permission_key, group_name))
        for clast_permission_key in permission_key_clast.permission_keys(permission_key, obj.__clast__):
            perm_checker = ObjectPermissionChecker(Group.objects.get(name=group_name))
            astert perm_checker.has_perm(clast_permission_key, obj), \
                "No permission for Group %s, Permission %s, ConfigEnsaty %s. It has permissions %s" % \
                (group_name, clast_permission_key, obj.name, perm_checker.get_perms(obj))

    return config_ensaty_group_permissions

0 View Complete Implementation : user_publishing.py
Copyright GNU General Public License v3.0
Author : CalthorpeAnalytics
def on_config_ensaty_post_save_user(sender, **kwargs):
    config_ensaty = InstanceBundle.extract_single_instance(**kwargs)
    if config_ensaty._no_post_save_publishing:
        return
    if kwargs.get('created') and not config_ensaty.creator:
        # Set the ConfigEnsaty.creator to the default admin group user if it wasn't set by the API
        config_ensaty.creator = User.objects.get(username=UserGroupKey.SUPERADMIN)
        config_ensaty._no_post_save_publishing = True
        config_ensaty.save()
        config_ensaty._no_post_save_publishing = False

    # TODO these should be importable on top. Something is messed up
    user_fixture = resolve_fixture("user", "user", UserFixture, config_ensaty.schema(),
                                   config_ensaty=config_ensaty)

    # Get the ConfigEnsatyGroups of the ConfigEnsaty. GlobalConfig uses SuperAdmin as its Group
    config_ensaty_groups = config_ensaty.config_ensaty_groups() if \
        not isinstance(config_ensaty, GlobalConfig) else \
        [Group.objects.get(name=UserGroupKey.SUPERADMIN)]

    # Find all existing users of all ConfigEnsaty Groups of the ConfigEnsaty
    # Note that we use values() instead of all() to get dicts with just needed fields instead of model instances
    # TODO remove username from here once all users have emails. update_or_create_user() checks username for uniquess presently
    existing_user_dicts = flat_map(
        lambda group: group.user_set.all().values('email', 'username'),
        config_ensaty_groups
    )

    # Combine the existing users with the fixtures, giving the former preference. We favor
    # what's in the database because the user might have updated their profile
    # Only accept fixture users not matching users in the db (by email)
    existing_emails = map(lambda existing_user_dict: existing_user_dict['email'], existing_user_dicts)
    logger.debug("Found existing users %s" % ', '.join(existing_emails))
    new_fixture_users = filter(lambda fixture_user: fixture_user['email'] not in existing_emails, user_fixture.users())
    if len(new_fixture_users) > 0:
        logger.debug("Found new fixture users %s" % ', '.join(map(lambda fixture_user: fixture_user['email'], new_fixture_users)))
    user_dicts = existing_user_dicts + new_fixture_users

    # Update or create each user. This will create users of new fixtures and run post-save processing
    # on both existing and new.
    for user_dict in user_dicts:
        update_or_create_user(**user_dict)

    reset_queries()