Example #1
0
    def setUp(self):
        User = get_user_model()
        self.user1 = User.objects.create(username="******",
                                         email="*****@*****.**")
        self.user2 = User.objects.create(username="******",
                                         email="*****@*****.**")
        self.user3 = User.objects.create(username="******",
                                         email="*****@*****.**")
        self.owner = User.objects.create(username="******")

        self.public = get_anonymous_user()
        self.group = Group.objects.create(name="Test group")

        self.collection = Collection.objects.create(contributor=self.owner,
                                                    name="Test collection 1")
        self.collection.set_permission(Permission.OWNER, self.owner)

        self.process = Process.objects.create(
            name="Test process",
            contributor=self.owner,
        )

        self.resource_name = "collection"
        self.viewset = CollectionViewSet

        super().setUp()
Example #2
0
def get_user(user: User) -> User:
    """Get the same user or anonymous one when user is not authenticated.

    :raises django.core.exceptions.ObjectDoesNotExist: when user is not
        authenticated and anonymous user could not be found.
    """
    if user.is_authenticated:
        return user
    else:
        return get_anonymous_user()
Example #3
0
    def filter_private(self, queryset, name, value):
        """Return only elements that are not public (explicitly shared with me)."""

        public_filter = Q(
            permission_group__permissions__user=get_anonymous_user())

        # Exclude public elements if filter value is True
        if value:
            return queryset.exclude(public_filter)
        else:
            return queryset.filter(public_filter)
Example #4
0
    def setUp(self):
        """Custom initilization of :class:`~ProcessTestCase`."""
        super().setUp()

        # Force reading anonymous user from the database for every test.
        resolwe.permissions.models.ANONYMOUS_USER = None

        self.collection = Collection.objects.create(name="Collection",
                                                    contributor=self.admin)
        self.collection.set_permission(Permission.VIEW, get_anonymous_user())
        self.process = self.create_process()
Example #5
0
    def setUp(self):
        super().setUp()

        self.admin.delete()
        self.user1 = get_user_model().objects.create(username="******")
        self.user2 = get_user_model().objects.create(username="******")
        self.group1 = Group.objects.create(name="Test group 1")
        self.group2 = Group.objects.create(name="Test group 2")
        self.anonymous = get_anonymous_user()

        self.collection = Collection.objects.create(
            contributor=self.user1,
            name="Test collection",
        )
Example #6
0
    def test_get_parent_schema(self):
        """Test access to parent object schema.

        Even when user has no permission to access the process of the parent
        data object.
        """
        anonymous_user = get_anonymous_user()
        main_process = Process.objects.get(slug="parent-process-schema")
        main_process.set_permission(Permission.VIEW, anonymous_user)
        input_process = Process.objects.get(
            slug="test-python-process-requirements")
        input_process.set_permission(Permission.NONE, anonymous_user)

        inputs = {
            "input1": self.run_process(input_process.slug).id,
            "input2": self.run_process(input_process.slug).id,
        }
        self.run_process(main_process.slug, inputs, contributor=anonymous_user)
Example #7
0
def get_identity(user_group: Union[Group, User]) -> Tuple[UserOrGroup, str]:
    """Return the tuple (user_or_group, name).

    The user_or_group is user or group and name is either 'user' or 'group'.

    :raises RuntimeError: when parameter is neither user nor group instance.
    """
    if isinstance(user_group, AnonymousUser):
        return get_anonymous_user(), "user"

    UserModel = get_user_model()
    if isinstance(user_group, UserModel):
        return user_group, "user"

    if isinstance(user_group, Group):
        return user_group, "group"

    raise RuntimeError("Parameter is not user or group instance.")
Example #8
0
 def set_public_permissions():
     """Set public permissions."""
     if "public" in data:
         apply_perm(data["public"], get_anonymous_user())
Example #9
0
 def _resolve_user(self, user):
     """Resolve user instance from request."""
     return get_anonymous_user() if user.is_anonymous else user
Example #10
0
def get_object_perms(
    obj: models.Model,
    user: Optional[User] = None,
    mock_superuser_permissions: bool = False,
) -> List[Dict]:
    """Return permissions for given object in Resolwe specific format.

    Function returns permissions for given object ``obj`` in the following
    format::

       {
           "type": "group"/"user"/"public",
           "id": <group_or_user_id>,
           "name": <group_or_user_name>,
           "permissions": [<first_permission>, <second_permission>,...]
       }

    For ``public`` type ``id`` and ``name`` keys are omitted.

    If ``user`` parameter is given, permissions are limited only to
    given user, groups he belongs to and public permissions.

    This function should be only used from Resolwe views: since permissions
    for the current user (users when user has share permission on the given
    object) are prefetched, we only iterate through objects here and filter
    them in Python. Using filter method would result in a new database query.

    :param obj: Resolwe's DB model's instance
    :param user: Django user
    :param mock_superuser_permissions: when True return all permissions for
        users that are superusers
    :return: list of permissions object in described format

    """
    perms_list = []
    public_permissions = []
    anonymous_user = get_anonymous_user()

    # Request only permissions for the given user.
    if user is not None:
        if user.is_authenticated:
            user_permissions, groups_permissions = get_user_group_perms(user, obj)
            if mock_superuser_permissions and user.is_superuser:
                user_permissions = list(Permission.highest())
        else:
            user_permissions, groups_permissions = [], []

        if user_permissions:
            perms_list.append(
                {
                    "type": "user",
                    "id": user.pk,
                    "name": user.get_full_name() or user.username,
                    "username": user.username,
                    "permissions": [str(permission) for permission in user_permissions],
                }
            )

        if groups_permissions:
            for group_id, group_name, permissions in groups_permissions:
                perms_list.append(
                    {
                        "type": "group",
                        "id": group_id,
                        "name": group_name,
                        "permissions": [str(permission) for permission in permissions],
                    }
                )
    else:
        for user, permissions in _get_users_with_perms(obj).items():
            if user == anonymous_user:
                # public user permissions are considered bellow
                public_permissions = permissions
                continue
            perms_list.append(
                {
                    "type": "user",
                    "id": user.pk,
                    "name": user.get_full_name() or user.username,
                    "username": user.username,
                    "permissions": [str(permission) for permission in permissions],
                }
            )

        for group, permissions in _get_groups_with_perms(obj).items():
            perms_list.append(
                {
                    "type": "group",
                    "id": group.pk,
                    "name": group.name,
                    "permissions": [str(permission) for permission in permissions],
                }
            )
    # Retrieve public permissions only if they are not set.
    # if not public_permissions:
    public_permissions = get_user_group_perms(anonymous_user, obj)[0]

    if public_permissions:
        perms_list.append(
            {
                "type": "public",
                "permissions": [str(permission) for permission in public_permissions],
            }
        )

    return perms_list