Exemplo n.º 1
0
 def side_effect(authz_token, group_id):
     if group_id == "group2":
         return GroupModel(id="group2", name="Group 2")
     elif group_id == "group3":
         return GroupModel(id="group3", name="Group 3")
     else:
         raise Exception("Unexpected group id: " + group_id)
Exemplo n.º 2
0
 def test_multiple_groups(self):
     group1 = GroupModel(id="abc123", name="Test Group")
     group2 = GroupModel(id="group2", name="Group 2")
     user_added_to_group.send(None,
                              user=self.user,
                              groups=[group1, group2],
                              request=self.request)
     self.assertEqual(len(mail.outbox), 1)
     msg = mail.outbox[0]
     self._assert_common_email_attributes(msg)
     self.assertEqual(msg.subject,
                      f"You've been added to groups "
                      f"[{group1.name}] and [{group2.name}] "
                      f"in {PORTAL_TITLE}")
     self.assertIn("groups Test Group and Group 2", msg.body)
Exemplo n.º 3
0
    def update(self, instance, validated_data):
        # Compute lists of ids to grant/revoke READ/WRITE
        existing_user_permissions = {
            user['user'].airavataInternalUserId: user['permissionType']
            for user in instance['userPermissions']
        }
        new_user_permissions = {
            user['user']['airavataInternalUserId']: user['permissionType']
            for user in validated_data['userPermissions']
        }

        (user_grant_read_permission, user_grant_write_permission,
         user_revoke_read_permission, user_revoke_write_permission) = \
            self._compute_all_revokes_and_grants(existing_user_permissions,
                                                 new_user_permissions)

        existing_group_permissions = {
            group['group'].id: group['permissionType']
            for group in instance['groupPermissions']
        }
        new_group_permissions = {
            group['group']['id']: group['permissionType']
            for group in validated_data['groupPermissions']
        }

        (group_grant_read_permission, group_grant_write_permission,
         group_revoke_read_permission, group_revoke_write_permission) = \
            self._compute_all_revokes_and_grants(existing_group_permissions,
                                                 new_group_permissions)

        instance['_user_grant_read_permission'] = user_grant_read_permission
        instance['_user_grant_write_permission'] = user_grant_write_permission
        instance['_user_revoke_read_permission'] = user_revoke_read_permission
        instance[
            '_user_revoke_write_permission'] = user_revoke_write_permission
        instance['_group_grant_read_permission'] = group_grant_read_permission
        instance[
            '_group_grant_write_permission'] = group_grant_write_permission
        instance[
            '_group_revoke_read_permission'] = group_revoke_read_permission
        instance[
            '_group_revoke_write_permission'] = group_revoke_write_permission
        instance['userPermissions'] = [{
            'user': UserProfile(**data['user']),
            'permissionType': data['permissionType']
        } for data in validated_data.get('userPermissions',
                                         instance['userPermissions'])]
        instance['groupPermissions'] = [{
            'group':
            GroupModel(**data['group']),
            'permissionType':
            data['permissionType']
        } for data in validated_data.get('groupPermissions',
                                         instance['groupPermissions'])]
        return instance
Exemplo n.º 4
0
 def test(self):
     group = GroupModel(id="abc123", name="Test Group")
     user_added_to_group.send(None,
                              user=self.user,
                              groups=[group],
                              request=self.request)
     self.assertEqual(len(mail.outbox), 1)
     msg = mail.outbox[0]
     self._assert_common_email_attributes(msg)
     self.assertEqual(msg.subject,
                      f"You've been added to group "
                      f"[{group.name}] in {PORTAL_TITLE}")
def create_group():
    try:
        group_model = GroupModel()
        group_model.id = "testing_group"
        group_model.name = "testing_group_name"
        group_model.ownerId = "default-admin"
        group_model.description = "This group is used for testing users"

        users = ['default-admin']

        group_model.members = users
        group_model.admins = users

        created_group = client.create_group(token, group_model)
        print(created_group)
    except TException:
        logger.exception("Exception occurred")
Exemplo n.º 6
0
    def test_update_group_sends_user_added_to_group_signal(self):
        url = reverse('django_airavata_api:group-detail',
                      kwargs={'group_id': 'abc123'})
        data = {
            "id":
            "abc123",
            "name":
            "test",
            "description":
            None,
            "members": [
                f"{self.user.username}@{GATEWAY_ID}",  # owner
                f"testuser1@{GATEWAY_ID}",  # existing member
                f"testuser3@{GATEWAY_ID}"
            ],  # new member
            "admins": []
        }
        request = self.factory.put(url, data)
        force_authenticate(request, self.user)

        # Mock api clients
        group_manager_mock = MagicMock(name='group_manager')
        user_profile_mock = MagicMock(name='user_profile')
        request.profile_service = {
            'group_manager': group_manager_mock,
            'user_profile': user_profile_mock,
        }
        request.airavata_client = MagicMock(name="airavata_client")
        request.airavata_client.getGatewayGroups.return_value = GatewayGroups(
            gatewayId=GATEWAY_ID,
            adminsGroupId="adminsGroupId",
            readOnlyAdminsGroupId="readOnlyAdminsGroupId",
            defaultGatewayUsersGroupId="defaultGatewayUsersGroupId")
        request.authz_token = "dummy"
        request.session = {}

        # mock getGroup
        group = GroupModel(
            id="abc123",
            name="My Group",
            ownerId=f"{self.user.username}@{GATEWAY_ID}",
            members=[
                f"{self.user.username}@{GATEWAY_ID}",  # owner
                f"testuser1@{GATEWAY_ID}",  # existing member
                f"testuser2@{GATEWAY_ID}",  # new member
            ],
            admins=[])
        group_manager_mock.getGroup.return_value = group

        # Only user added is testuser3, so getUserProfileById will be called
        # for that user
        user_profile = UserProfile(
            airavataInternalUserId=f"testuser3@{GATEWAY_ID}",
            userId="testuser3",
            firstName="Test",
            lastName="User3",
            emails=["*****@*****.**"])
        user_profile_mock.getUserProfileById.return_value = user_profile

        # Mock signal handler to verify 'user_added_to_group' signal is sent
        user_added_to_group_handler = MagicMock()
        signals.user_added_to_group.connect(user_added_to_group_handler,
                                            sender=views.GroupViewSet)
        group_update = views.GroupViewSet.as_view({'put': 'update'})
        response = group_update(request, group_id="abc123")
        self.assertEquals(200, response.status_code)
        self.assertEquals("abc123", response.data['id'])

        # verify addUsersToGroup
        group_manager_mock.addUsersToGroup.assert_called_once()
        args, kwargs = group_manager_mock.addUsersToGroup.call_args
        self.assertEqual(args[1], [f"testuser3@{GATEWAY_ID}"])

        # verify removeUsersFromGroup
        group_manager_mock.removeUsersFromGroup.assert_called_once()
        args, kwargs = group_manager_mock.removeUsersFromGroup.call_args
        self.assertEqual(args[1], [f"testuser2@{GATEWAY_ID}"])

        # verify updateGroup
        group_manager_mock.updateGroup.assert_called_once()

        user_added_to_group_handler.assert_called_once()
        args, kwargs = user_added_to_group_handler.call_args
        self.assertEquals("abc123", kwargs["groups"][0].id)
        self.assertIs(user_profile, kwargs["user"])
Exemplo n.º 7
0
    def test_update_that_does_not_add_user_to_groups(self, iam_admin_client):

        username = "******"
        url = reverse('django_airavata_api:iam-user-profile-detail',
                      kwargs={'user_id': username})
        data = {
            "airavataInternalUserId": f"{username}@{GATEWAY_ID}",
            "userId": username,
            "gatewayId": GATEWAY_ID,
            "email": "*****@*****.**",
            "firstName": "Test",
            "lastName": "User1",
            "airavataUserProfileExists": True,
            "enabled": True,
            "emailVerified": True,
            "groups": [
                {
                    "id": "group1",
                    "name": "Group 1"
                },
            ]
        }
        request = self.factory.put(url, data)
        force_authenticate(request, self.user)
        request.is_gateway_admin = True

        # Mock api clients
        iam_user_profile = UserProfile(
            airavataInternalUserId=f"testuser1@{GATEWAY_ID}",
            userId="testuser1",
            firstName="Test",
            lastName="User1",
            emails=["*****@*****.**"])
        iam_admin_client.get_user.return_value = iam_user_profile
        group_manager_mock = MagicMock(name='group_manager')
        user_profile_mock = MagicMock(name='user_profile')
        request.profile_service = {
            'group_manager': group_manager_mock,
            'user_profile': user_profile_mock,
        }
        request.authz_token = "dummy"
        user_profile_mock.doesUserExist.return_value = True
        user_profile = UserProfile(
            airavataInternalUserId=f"testuser1@{GATEWAY_ID}",
            userId="testuser1",
            firstName="Test",
            lastName="User1",
            emails=["*****@*****.**"])
        user_profile_mock.getUserProfileById.return_value = user_profile
        group_manager_mock.getAllGroupsUserBelongs.return_value = [
            GroupModel(id="group1")
        ]

        request.airavata_client = MagicMock(name="airavata_client")
        request.airavata_client.getGatewayGroups.return_value = GatewayGroups(
            gatewayId=GATEWAY_ID,
            adminsGroupId="adminsGroupId",
            readOnlyAdminsGroupId="readOnlyAdminsGroupId",
            defaultGatewayUsersGroupId="defaultGatewayUsersGroupId")
        request.session = {}

        # Mock signal handler to verify 'user_added_to_group' signal is sent
        user_added_to_group_handler = MagicMock(
            name="user_added_to_group_handler")
        signals.user_added_to_group.connect(user_added_to_group_handler,
                                            sender=views.IAMUserViewSet)
        iam_user_update = views.IAMUserViewSet.as_view({'put': 'update'})
        response = iam_user_update(request, user_id=username)
        self.assertEquals(200, response.status_code)

        user_profile_mock.doesUserExist.assert_called_once()
        group_manager_mock.getAllGroupsUserBelongs.assert_called_once()

        # Since user wasn't added to a group, these all should not have been
        # called
        user_profile_mock.getUserProfileById.assert_not_called()
        group_manager_mock.getGroup.assert_not_called()
        group_manager_mock.addUsersToGroup.assert_not_called()
        user_added_to_group_handler.assert_not_called()
Exemplo n.º 8
0
    def test_update_that_adds_user_to_multiple_groups(self, iam_admin_client):

        username = "******"
        url = reverse('django_airavata_api:iam-user-profile-detail',
                      kwargs={'user_id': username})
        data = {
            "airavataInternalUserId":
            f"{username}@{GATEWAY_ID}",
            "userId":
            username,
            "gatewayId":
            GATEWAY_ID,
            "email":
            "*****@*****.**",
            "firstName":
            "Test",
            "lastName":
            "User1",
            "airavataUserProfileExists":
            True,
            "enabled":
            True,
            "emailVerified":
            True,
            "groups": [
                {
                    "id": "group1",
                    "name": "Group 1"
                },
                {
                    "id": "group2",
                    "name": "Group 2"
                },
                {
                    "id": "group3",
                    "name": "Group 3"
                },
            ]
        }
        request = self.factory.put(url, data)
        force_authenticate(request, self.user)
        request.is_gateway_admin = True

        # Mock api clients
        iam_user_profile = UserProfile(
            airavataInternalUserId=f"testuser1@{GATEWAY_ID}",
            userId="testuser1",
            firstName="Test",
            lastName="User1",
            emails=["*****@*****.**"])
        iam_admin_client.get_user.return_value = iam_user_profile
        group_manager_mock = MagicMock(name='group_manager')
        user_profile_mock = MagicMock(name='user_profile')
        request.profile_service = {
            'group_manager': group_manager_mock,
            'user_profile': user_profile_mock,
        }
        request.authz_token = "dummy"
        user_profile_mock.doesUserExist.return_value = True
        user_profile = UserProfile(
            airavataInternalUserId=f"testuser1@{GATEWAY_ID}",
            userId="testuser1",
            firstName="Test",
            lastName="User1",
            emails=["*****@*****.**"])
        user_profile_mock.getUserProfileById.return_value = user_profile
        group_manager_mock.getAllGroupsUserBelongs.return_value = [
            GroupModel(id="group1")
        ]

        def side_effect(authz_token, group_id):
            if group_id == "group2":
                return GroupModel(id="group2", name="Group 2")
            elif group_id == "group3":
                return GroupModel(id="group3", name="Group 3")
            else:
                raise Exception("Unexpected group id: " + group_id)

        group_manager_mock.getGroup.side_effect = side_effect
        request.airavata_client = MagicMock(name="airavata_client")
        request.airavata_client.getGatewayGroups.return_value = GatewayGroups(
            gatewayId=GATEWAY_ID,
            adminsGroupId="adminsGroupId",
            readOnlyAdminsGroupId="readOnlyAdminsGroupId",
            defaultGatewayUsersGroupId="defaultGatewayUsersGroupId")
        request.session = {}

        # Mock signal handler to verify 'user_added_to_group' signal is sent
        user_added_to_group_handler = MagicMock(
            name="user_added_to_group_handler")
        signals.user_added_to_group.connect(user_added_to_group_handler,
                                            sender=views.IAMUserViewSet)
        iam_user_update = views.IAMUserViewSet.as_view({'put': 'update'})
        response = iam_user_update(request, user_id=username)
        self.assertEquals(200, response.status_code)

        user_profile_mock.doesUserExist.assert_called_once()
        group_manager_mock.getAllGroupsUserBelongs.assert_called_once()

        user_profile_mock.getUserProfileById.assert_called_once()
        args, kwargs = user_profile_mock.getUserProfileById.call_args
        self.assertSequenceEqual(
            args, [request.authz_token, "testuser1", GATEWAY_ID])

        group_manager_mock.getGroup.assert_has_calls([
            call(request.authz_token, "group2"),
            call(request.authz_token, "group3")
        ],
                                                     any_order=True)

        group_manager_mock.addUsersToGroup.assert_has_calls([
            call(request.authz_token, [f"testuser1@{GATEWAY_ID}"], "group2"),
            call(request.authz_token, [f"testuser1@{GATEWAY_ID}"], "group3"),
        ],
                                                            any_order=True)

        # user_added_to_group signal should only be called once, with both
        # groups passed to it
        user_added_to_group_handler.assert_called_once()
        args, kwargs = user_added_to_group_handler.call_args
        self.assertEqual(kwargs["sender"], views.IAMUserViewSet)
        self.assertEqual(kwargs["user"], user_profile)
        self.assertSetEqual({"group2", "group3"},
                            {g.id
                             for g in kwargs["groups"]})
Exemplo n.º 9
0
 def create(self, validated_data):
     validated_data['ownerId'] = self.context['request'].user.username + "@" + settings.GATEWAY_ID
     return GroupModel(**validated_data)