Python django.conf.settings.ANONYMOUS_USER_ID Examples

The following are 15 code examples of django.conf.settings.ANONYMOUS_USER_ID(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(AssignOrgAdmin, self).__init__(*args, **kwargs)
        role = kwargs.get('instance')
        if role is not None:
            old_admins = role.organization.get_staffs
            old_admins_id = [admin[0] for admin in old_admins]
            old_admins_id.append(settings.ANONYMOUS_USER_ID)
            if hasattr(self.request, "organization"):
                if self.request.organization:
                    users = User.objects.filter(user_profile__organization=self.request.organization, is_active=True).\
                        filter(id__in=old_admins_id)
                else:
                    users = User.objects.filter(is_active=True).exclude(id__in=old_admins_id)
            else:
                users = User.objects.filter(is_active=True).exclude(id__in=old_admins_id)
            self.fields['user'].queryset = users
            self.fields['organization'].choices = old_admins 
Example #2
Source File: object_permission.py    From kpi with GNU Affero General Public License v3.0 6 votes vote down vote up
def _filter_anonymous_perms(self, unfiltered_set):
        """
        Restrict a set of tuples in the format (user_id, permission_id) to
        only those permissions that apply to the content_type of this object
        and are listed in settings.ALLOWED_ANONYMOUS_PERMISSIONS.
        """
        content_type = ContentType.objects.get_for_model(self)
        # Translate settings.ALLOWED_ANONYMOUS_PERMISSIONS to primary keys
        codenames = set()
        for perm in settings.ALLOWED_ANONYMOUS_PERMISSIONS:
            app_label, codename = perm_parse(perm)
            if app_label == content_type.app_label:
                codenames.add(codename)
        allowed_permission_ids = Permission.objects.filter(
            content_type_id=content_type.pk, codename__in=codenames
        ).values_list('pk', flat=True)
        filtered_set = copy.copy(unfiltered_set)
        for user_id, permission_id in unfiltered_set:
            if user_id == settings.ANONYMOUS_USER_ID:
                if permission_id not in allowed_permission_ids:
                    filtered_set.remove((user_id, permission_id))
        return filtered_set 
Example #3
Source File: anonymous_user_mixin.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_queryset(self):
        """Set AnonymousUser from the database to allow object permissions."""
        if self.request and self.request.user.is_anonymous():
            self.request.user = get_object_or_404(
                User, pk=settings.ANONYMOUS_USER_ID)

        return super(AnonymousUserMixin, self).get_queryset() 
Example #4
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(UserRoleForm, self).__init__(*args, **kwargs)
        self.fields['group'].empty_label = None
        self.fields['user'].empty_label = None
        users = User.objects.filter().exclude(id=settings.ANONYMOUS_USER_ID)
        self.fields['user'].choices = [(user.pk, user.username) for user in users] 
Example #5
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(SetProjectManagerForm, self).__init__(*args, **kwargs)
        role = kwargs.get('instance')
        if role is not None:
            old_admins = role.project.get_staffs_id
            users = User.objects.filter().exclude(id=settings.ANONYMOUS_USER_ID).exclude(id__in=old_admins)
            if hasattr(self.request, "organization"):
                if self.request.organization:
                    users = users.filter(user_profile__organization=self.request.organization)
            self.fields['user'].queryset = users 
Example #6
Source File: forms.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        super(SetSupervisorForm, self).__init__(*args, **kwargs)
        role = kwargs.get('instance')
        if role is not None:
            old_pm = role.site.get_supervisor_id
            users = User.objects.filter().exclude(id=settings.ANONYMOUS_USER_ID).exclude(id__in=old_pm)
            if hasattr(self.request, "organization"):
                if self.request.organization:
                    users = users.filter(user_profile__organization=self.request.organization)
            self.fields['user'].queryset = users 
Example #7
Source File: backends.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def _translate_anonymous_user(user_obj):
        """
        Returns user_obj, is_anonymous, where user_obj is always a real
        User object (translated from AnonymousUser if necessary), and
        is_anonymous is True if the user is anonymous
        """
        is_anonymous = False
        if isinstance(user_obj, AnonymousUser):
            is_anonymous = True
            user_obj = get_anonymous_user()
        elif user_obj.pk == settings.ANONYMOUS_USER_ID:
            is_anonymous = True
        return user_obj, is_anonymous 
Example #8
Source File: filters.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def filter_queryset(self, request, queryset, view):
        # TODO: omit objects for which the user has only a deny permission
        user = request.user
        if isinstance(request.user, AnonymousUser):
            user = get_anonymous_user()
        if user.is_superuser:
            # Superuser sees all
            return queryset
        if user.pk == settings.ANONYMOUS_USER_ID:
            # Hide permissions from anonymous users
            return queryset.none()
        """
        A regular user sees permissions for objects to which they have access.
        For example, if Alana has view access to an object owned by Richard,
        she should see all permissions for that object, including those
        assigned to other users.
        """
        possible_content_types = ContentType.objects.get_for_models(
            *get_models_with_object_permissions()
        ).values()
        result = queryset.none()
        for content_type in possible_content_types:
            # Find all the permissions assigned to the user
            permissions_assigned_to_user = ObjectPermission.objects.filter(
                content_type=content_type,
                user=user,
            )
            # Find all the objects associated with those permissions, and then
            # find all the permissions applied to all of those objects
            result |= ObjectPermission.objects.filter(
                content_type=content_type,
                object_id__in=permissions_assigned_to_user.values(
                    'object_id'
                ).distinct()
            )
        return result 
Example #9
Source File: object_permission_helper.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_user_permission_assignments_queryset(cls, affected_object, user):
        """
        Returns a queryset to fetch `affected_object`'s permission assignments
        that `user` is allowed to see.

        Args:
            affected_object (Collection|Asset)
            user (User)
        Returns:
             QuerySet

        """

        # `affected_object.permissions` is a `GenericRelation(ObjectPermission)`
        # Don't Prefetch `content_object`.
        # See `AssetPermissionAssignmentSerializer.to_representation()`
        queryset = affected_object.permissions.filter(deny=False).select_related(
            'permission', 'user'
        ).order_by(
                'user__username', 'permission__codename'
        ).exclude(permission__codename=PERM_FROM_KC_ONLY).all()

        # Filtering is done in `get_queryset` instead of FilteredBackend class
        # because it's specific to `ObjectPermission`.
        if not user or user.is_anonymous:
            queryset = queryset.filter(user_id=affected_object.owner_id)
        elif not cls.user_can_share(affected_object, user):
            # Display only users' permissions if they are not allowed to modify
            # others' permissions
            queryset = queryset.filter(user_id__in=[user.pk,
                                                    affected_object.owner_id,
                                                    settings.ANONYMOUS_USER_ID])

        return queryset 
Example #10
Source File: object_permission_helper.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_user_permission_assignments(cls, affected_object, user,
                                        object_permission_assignments):
        """
        Works like `get_user_permission_assignments_queryset` but returns
        a list instead of a queryset. It also needs a list of all
        `affected_object`'s permission assignments to search for assignments
        `user` is allowed to see.

        Args:
            affected_object (Collection|Asset)
            user (User)
            object_permission_assignments (list):
        Returns:
             list

        """
        user_permission_assignments = []
        filtered_user_ids = None

        if not user or user.is_anonymous:
            filtered_user_ids = [affected_object.owner_id]
        elif not cls.user_can_share(affected_object, user):
            # Display only users' permissions if they are not allowed to modify
            # others' permissions
            filtered_user_ids = [affected_object.owner_id,
                                 user.pk,
                                 settings.ANONYMOUS_USER_ID]

        for permission_assignment in object_permission_assignments:
            if (filtered_user_ids is None or
                    permission_assignment.user_id in filtered_user_ids):
                user_permission_assignments.append(permission_assignment)

        return user_permission_assignments 
Example #11
Source File: object_permission.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def has_perm(self, user_obj, perm):
        """ Does user_obj have perm on this object? (True/False) """
        app_label, codename = perm_parse(perm, self)
        is_anonymous = False
        if isinstance(user_obj, AnonymousUser):
            # Get the User database representation for AnonymousUser
            user_obj = get_anonymous_user()
        if user_obj.pk == settings.ANONYMOUS_USER_ID:
            is_anonymous = True
        # Treat superusers the way django.contrib.auth does
        if user_obj.is_active and user_obj.is_superuser:
            return True
        # Look for matching permissions
        result = len(self._get_effective_perms(
            user=user_obj,
            codename=codename
        )) == 1
        if not result and not is_anonymous:
            # The user-specific test failed, but does the public have access?
            result = self.has_perm(AnonymousUser(), perm)
        if result and is_anonymous:
            # Is an anonymous user allowed to have this permission?
            fq_permission = '{}.{}'.format(app_label, codename)
            if fq_permission not in settings.ALLOWED_ANONYMOUS_PERMISSIONS:
                return False
        return result 
Example #12
Source File: kobocat_backend.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def __kobocat_proxy_request(kc_request, user=None):
        """
        Send `kc_request`, which must specify `method` and `url` at a minimum.
        If the incoming request to be proxied is authenticated,
        logged-in user's API token will be added to `kc_request.headers`

        :param kc_request: requests.models.Request
        :param user: User
        :return: requests.models.Response
        """
        if not user.is_anonymous and user.pk != settings.ANONYMOUS_USER_ID:
            token, created = Token.objects.get_or_create(user=user)
            kc_request.headers['Authorization'] = 'Token %s' % token.key
        session = requests.Session()
        return session.send(kc_request.prepare()) 
Example #13
Source File: utils.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def assign_applicable_kc_permissions(obj, user, kpi_codenames):
    r"""
        Assign the `user` the applicable KC permissions to `obj`, if any
        exists, given one KPI permission codename as a single string or many
        codenames as an iterable. If `obj` is not a :py:class:`Asset` or does
        not have a deployment, take no action.
        :param obj: Any Django model instance
        :type user: :py:class:`User` or :py:class:`AnonymousUser`
        :type kpi_codenames: str or list(str)
    """
    if not obj._meta.model_name == 'asset':
        return
    permissions = _get_applicable_kc_permissions(obj, kpi_codenames)
    if not permissions:
        return
    xform_id = _get_xform_id_for_asset(obj)
    if not xform_id:
        return
    if user.is_anonymous or user.pk == settings.ANONYMOUS_USER_ID:
        return set_kc_anonymous_permissions_xform_flags(
            obj, kpi_codenames, xform_id)
    xform_content_type = KobocatContentType.objects.get(
        **obj.KC_CONTENT_TYPE_KWARGS)
    kc_permissions_already_assigned = KobocatUserObjectPermission.objects.filter(
        user=user, permission__in=permissions, object_pk=xform_id,
    ).values_list('permission__codename', flat=True)
    permissions_to_create = []
    for permission in permissions:
        if permission.codename in kc_permissions_already_assigned:
            continue
        permissions_to_create.append(KobocatUserObjectPermission(
            user=user, permission=permission, object_pk=xform_id,
            content_type=xform_content_type
        ))
    KobocatUserObjectPermission.objects.bulk_create(permissions_to_create) 
Example #14
Source File: permissions.py    From kpi with GNU Affero General Public License v3.0 4 votes vote down vote up
def grant_all_model_level_perms(
        user, models_or_content_types, permissions_manager=Permission.objects,
        content_type_manager=ContentType.objects):
    """
    Utility function that gives `user` unrestricted model-level access
    to everything listed in `models_or_content_types`. Without this, actions on
    individual instances are immediately denied and object-level permissions
    are never considered.

    Args:
        user (instance of User model)
        models_or_content_types (django.db.models.Model,
            django.contrib.contenttypes.models.ContentType, or iterable of
            either)
        permissions_manager (django.db.models.Manager)
        content_type_manager (django.db.models.Manager)
    """
    from kpi.models.object_permission import perm_parse

    try:
        iter(models_or_content_types)
    except TypeError:
        # models_or_content_types is a single item, not an iterable
        models_or_content_types = [models_or_content_types]

    content_types = []
    for item in models_or_content_types:
        if isinstance(item, content_type_manager.model):
            content_types.append(item)
        else:
            content_types.append(content_type_manager.get_for_model(item))

    permissions_to_assign = permissions_manager.filter(
        content_type__in=content_types)

    if content_types and not permissions_to_assign.exists():
        raise Exception('No permissions found! You may need to migrate your '
                        'database. Searched for content types {}.'.format(
                            content_types))

    if user.pk == settings.ANONYMOUS_USER_ID:
        # The user is anonymous, so pare down the permissions to only those
        # that the configuration allows for anonymous users
        q_query = Q()
        for allowed_permission in settings.ALLOWED_ANONYMOUS_PERMISSIONS:
            app_label, codename = perm_parse(allowed_permission)
            q_query |= Q(content_type__app_label=app_label, codename=codename)
        permissions_to_assign = permissions_to_assign.filter(q_query)

    user.user_permissions.add(*permissions_to_assign) 
Example #15
Source File: object_permission.py    From kpi with GNU Affero General Public License v3.0 4 votes vote down vote up
def __get_object_permissions(self, deny, user=None, codename=None):
        """
        Returns a set of user ids and object permission ids related to
        object `self`.

        Args:
            deny (bool): If `True`, returns denied permissions
            user (User)
            codename (str)

        Returns:
            set: [(User's pk, Permission's pk)]
        """

        def build_dict(user_id_, object_permissions_):
            perms_ = []
            if object_permissions_:
                for permission_id, codename_, deny_ in object_permissions_:
                    if (deny_ is not deny or
                            codename is not None and
                            codename != codename_):
                        continue
                    perms_.append((user_id_, permission_id))
            return perms_

        perms = []
        object_content_type_id = ContentType.objects.get_for_model(self).pk
        # If User is not none, retrieve all permissions for this user
        # grouped by object ids, otherwise, retrieve all permissions for this object
        # grouped by user ids.
        if user is not None:
            user_id = user.pk if not user.is_anonymous \
                else settings.ANONYMOUS_USER_ID
            all_object_permissions = self.__get_all_user_permissions(
                content_type_id=object_content_type_id,
                user_id=user_id)
            perms = build_dict(user_id, all_object_permissions.get(self.pk))

            if not perms:
                # Try AnonymousUser's permissions in case user does not have any.
                all_object_permissions = self.__get_all_user_permissions(
                    content_type_id=object_content_type_id,
                    user_id=settings.ANONYMOUS_USER_ID)
                perms = build_dict(user_id, all_object_permissions.get(self.pk))
        else:
            all_object_permissions = self.__get_all_object_permissions(
                content_type_id=object_content_type_id,
                object_id=self.pk)
            for user_id, object_permissions in all_object_permissions.items():
                perms += build_dict(user_id, object_permissions)

        return set(perms)