def test_beta_user_to_user(self): """ A user who was a beta user is now a user """ profile = model_access.get_profile('betaraybill') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() groups = profile.user.groups.values_list('name', flat=True) self.assertEqual(profile.highest_role(), 'USER') self.assertTrue('BETA_USER' in groups) auth_data = { 'dn': 'BetaRayBill betaraybill', 'cn': 'Beta Ray Bill', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Miniluv', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False, 'is_beta_user': False, } self.assertTrue(self.auth.authorization_update('betaraybill', auth_data, method='test_user_to_beta_user')) profile = model_access.get_profile('betaraybill') groups = profile.user.groups.values_list('name', flat=True) self.assertFalse('BETA_USER' in groups) self.assertEqual(profile.highest_role(), 'USER')
def test_apps_mall_steward_to_org_steward(self): """ A user who was an apps mall steward is now an org steward """ profile = model_access.get_profile('bigbrother') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('APPS_MALL_STEWARD' in groups) self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD') auth_data = { 'dn': 'Big Brother bigbrother', 'cn': 'Big Brother', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Minitrue', 'is_org_steward': True, 'is_apps_mall_steward': False, 'is_metrics_user': False, 'is_beta_user': False } self.auth.authorization_update('bigbrother', auth_data, method='test_org_steward_to_apps_mall_steward') profile = model_access.get_profile('bigbrother') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('ORG_STEWARD' in groups) self.assertEqual(profile.highest_role(), 'ORG_STEWARD')
def test_beta_user_apps_mall_steward_to_apps_mall_steward(self): """ A apps mall steward who was a beta user is now a apps mall steward """ profile = model_access.get_profile('bettafish') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('BETA_USER' in groups) self.assertEqual(len(groups), 2) auth_data = { 'dn': 'Bettafish bettafish', 'cn': 'Betta Fish', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Miniluv', 'is_org_steward': False, 'is_apps_mall_steward': True, 'is_metrics_user': False, 'is_beta_user': False, } self.auth.authorization_update('betaraybill', auth_data, method='test_beta_user_apps_mall_steward_to_apps_mall_steward') profile = model_access.get_profile('betaraybill') groups = profile.user.groups.values_list('name', flat=True) self.assertFalse('BETA_USER' in groups) self.assertEqual(len(groups), 1) self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD')
def test_org_steward_to_user(self): """ A user who was an org steward is now a regular user """ profile = model_access.get_profile('wsmith') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() stewarded_orgs = profile.stewarded_organizations.values_list('title', flat=True) self.assertTrue('Ministry of Truth' in stewarded_orgs) self.assertEqual(profile.highest_role(), 'ORG_STEWARD') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('ORG_STEWARD' in groups) auth_data = { 'dn': 'Winston Smith wsmith', 'cn': 'Winston Smith', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Minitrue', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False, 'is_beta_user': False } self.auth.authorization_update('wsmith', auth_data, method='test_org_steward_to_user') profile = model_access.get_profile('wsmith') stewarded_orgs = profile.stewarded_organizations.values_list('title', flat=True) self.assertEqual(len(stewarded_orgs), 0) groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('USER' in groups) self.assertEqual(len(groups), 1) self.assertEqual(profile.highest_role(), 'USER')
def test_beta_user_to_user(self): """ A user who was a beta user is now a user """ profile = model_access.get_profile('betaraybill') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() groups = profile.user.groups.values_list('name', flat=True) self.assertEqual(profile.highest_role(), 'USER') self.assertTrue('BETA_USER' in groups) auth_data = { 'dn': 'BetaRayBill betaraybill', 'cn': 'Beta Ray Bill', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Miniluv', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False, 'is_beta_user': False, } self.assertTrue( self.auth.authorization_update('betaraybill', auth_data, method='test_user_to_beta_user')) profile = model_access.get_profile('betaraybill') groups = profile.user.groups.values_list('name', flat=True) self.assertFalse('BETA_USER' in groups) self.assertEqual(profile.highest_role(), 'USER')
def test_delete_review(self): # test_delete_review air_mail_id = models.Listing.objects.get(title='Air Mail').id url = '/api/listing/{0!s}/review/'.format(air_mail_id) data = {'rate': 4, 'text': 'winston test review'} user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) review_id = response.data['id'] # trying to delete it as a different user should fail... url = '/api/listing/{0!s}/review/{1!s}/'.format(air_mail_id, review_id) user = generic_model_access.get_profile('jones').user self.client.force_authenticate(user=user) response = self.client.delete(url, format='json') self.assertEqual(response.data, ExceptionUnitTestHelper.permission_denied("Cannot update another user's review")) # ... unless that user is an org steward or apps mall steward user = generic_model_access.get_profile('julia').user self.client.force_authenticate(user=user) response = self.client.delete(url, format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # Check listing history url = '/api/listing/{0!s}/'.format(air_mail_id) response = APITestHelper.request(self, url, 'GET', username='******', status_code=200) data = response.data self.assertEqual(validate_listing_map_keys(data), []) self.assertEqual(data['last_activity']['author']['user']['username'], 'julia') self.assertEqual(data['last_activity']['action'], 'REVIEW_DELETED') self.assertEqual(data['last_activity']['listing']['id'], air_mail_id)
def test_update_cache(self): if not settings.OZP['USE_AUTH_SERVER']: return profile = model_access.get_profile('jones') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() auth_data = { 'dn': 'Jones jones', 'cn': 'Jones', 'clearances': ['U', 'C', 'S'], 'formal_accesses': [], 'visas': ['NOVEMBER'], 'duty_org': 'Minitrue', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False } a = auth.authorization_update('jones', auth_data) self.assertEqual(a, True) # auth_expires should be rest to ~1 day from now profile = model_access.get_profile('jones') auth_expires_in = profile.auth_expires - datetime.datetime.now(pytz.utc) # 86,400 seconds in a day min_sec = int(settings.OZP['OZP_AUTHORIZATION']['SECONDS_TO_CACHE_DATA']) - 2 self.assertTrue(min_sec < auth_expires_in.seconds < 86400)
def test_get_self_notification_ordering(self): url = '/api/self/notification/' # get default user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) response = self.client.get(url, format='json') default_ids = [record['id'] for record in response.data] self.assertEqual(default_ids, [5, 2, 1]) self.assertEqual(response.status_code, status.HTTP_200_OK) url = '/api/self/notification/?ordering=-created_date' # get reversed order user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) response = self.client.get(url, format='json') reverse_order_ids = [record['id'] for record in response.data] self.assertEqual(reverse_order_ids, default_ids) self.assertEqual(response.status_code, status.HTTP_200_OK) url = '/api/self/notification/?ordering=created_date' # get ascending order user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) response = self.client.get(url, format='json') order_ids = [record['id'] for record in response.data] self.assertEqual(reverse_order_ids, list(reversed(order_ids))) self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_org_change(self): """ A user's agency (organization) changes """ if not settings.OZP['USE_AUTH_SERVER']: return profile = model_access.get_profile('rutherford') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() org = profile.organizations.values_list('title', flat=True)[0] self.assertEqual(org, 'Ministry of Plenty') auth_data = { 'dn': 'Rutherford rutherford', 'cn': 'Rutherford', 'clearances': ['U', 'C', 'S'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Miniluv', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False } a = auth.authorization_update('rutherford', auth_data) profile = model_access.get_profile('rutherford') org = profile.organizations.values_list('title', flat=True)[0] self.assertEqual(org, 'Ministry of Love')
def test_apps_mall_steward_to_user(self): """ A user who was an apps mall steward is now a regular user """ if not settings.OZP['USE_AUTH_SERVER']: return profile = model_access.get_profile('bigbrother') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('APPS_MALL_STEWARD' in groups) self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD') auth_data = { 'dn': 'Big Brother bigbrother', 'cn': 'Big Brother', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Minitrue', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False } a = auth.authorization_update('bigbrother', auth_data) profile = model_access.get_profile('bigbrother') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('USER' in groups) self.assertTrue(len(groups) == 1) self.assertEqual(profile.highest_role(), 'USER')
def to_representation(self, data): ret = super(ListingSerializer, self).to_representation(data) anonymize_identifiable_data = system_anonymize_identifiable_data(self.context['request'].user.username) request_user = generic_model_access.get_profile(self.context['request'].user) # TODO: Get the profile from view request instead of getting it from db again if anonymize_identifiable_data: ret['contacts'] = [] check_failed = [] # owners if 'owners' in ret and not anonymize_identifiable_data: for owner in ret['owners']: user_dict = owner.get('user') user_username = None if user_dict is None else user_dict.get('username') # if not user_username: # raise serializers.ValidationError('Owner field requires correct format') owner_profile = generic_model_access.get_profile(user_username) # if not owner_profile: # raise serializers.ValidationError('Owner Profile not found') # Don't allow user to select a security marking that is above # their own access level\ try: if system_has_access_control(owner_profile.user.username, ret.get('security_marking')) is False: check_failed.append(owner_profile.user.username) # raise serializers.ValidationError(owner_profile.user.username + 'User certificate is invalid') except Exception: check_failed.append(owner_profile.user.username) ret['cert_issues'] = check_failed ret['feedback'] = self._feedback(request_user, data) ret['is_bookmarked'] = self._is_bookmarked(request_user, data) return ret
def test_beta_user_apps_mall_steward_to_apps_mall_steward(self): """ A apps mall steward who was a beta user is now a apps mall steward """ profile = model_access.get_profile('bettafish') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('BETA_USER' in groups) self.assertEqual(len(groups), 2) auth_data = { 'dn': 'Bettafish bettafish', 'cn': 'Betta Fish', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Miniluv', 'is_org_steward': False, 'is_apps_mall_steward': True, 'is_metrics_user': False, 'is_beta_user': False, } self.auth.authorization_update( 'betaraybill', auth_data, method='test_beta_user_apps_mall_steward_to_apps_mall_steward') profile = model_access.get_profile('betaraybill') groups = profile.user.groups.values_list('name', flat=True) self.assertFalse('BETA_USER' in groups) self.assertEqual(len(groups), 1) self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD')
def test_org_steward_to_apps_mall_steward(self): """ A user who was an org steward is now also an apps mall steward """ if not settings.OZP['USE_AUTH_SERVER']: return profile = model_access.get_profile('wsmith') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() stewarded_orgs = profile.stewarded_organizations.values_list('title', flat=True) self.assertTrue('Ministry of Truth' in stewarded_orgs) self.assertEqual(profile.highest_role(), 'ORG_STEWARD') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('ORG_STEWARD' in groups) auth_data = { 'dn': 'Winston Smith wsmith', 'cn': 'Winston Smith', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Minitrue', 'is_org_steward': True, 'is_apps_mall_steward': True, 'is_metrics_user': False } a = auth.authorization_update('wsmith', auth_data) profile = model_access.get_profile('wsmith') stewarded_orgs = profile.stewarded_organizations.values_list('title', flat=True) self.assertTrue('Ministry of Truth' in stewarded_orgs) groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('APPS_MALL_STEWARD' in groups) self.assertTrue('ORG_STEWARD' in groups) self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD')
def test_update_cache(self): profile = model_access.get_profile('jones') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() auth_data = { 'dn': 'Jones jones', 'cn': 'Jones', 'clearances': ['U', 'C', 'S'], 'formal_accesses': [], 'visas': ['NOVEMBER'], 'duty_org': 'Minitrue', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False, 'is_beta_user': False } a = self.auth.authorization_update('jones', auth_data, method='test_update_cache') self.assertEqual(a, True) # auth_expires should be rest to ~1 day from now profile = model_access.get_profile('jones') auth_expires_in = profile.auth_expires - datetime.datetime.now( pytz.utc) # 86,400 seconds in a day min_sec = int( settings.OZP['OZP_AUTHORIZATION']['SECONDS_TO_CACHE_DATA']) - 2 self.assertTrue(min_sec < auth_expires_in.seconds < 86400)
def test_org_change(self): """ A user's agency (organization) changes """ profile = model_access.get_profile('rutherford') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() org = profile.organizations.values_list('title', flat=True)[0] self.assertEqual(org, 'Ministry of Plenty') auth_data = { 'dn': 'Rutherford rutherford', 'cn': 'Rutherford', 'clearances': ['U', 'C', 'S'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Miniluv', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False, 'is_beta_user': False } self.auth.authorization_update('rutherford', auth_data, method='test_org_change') profile = model_access.get_profile('rutherford') org = profile.organizations.values_list('title', flat=True)[0] self.assertEqual(org, 'Ministry of Love')
def test_apps_mall_steward_to_org_steward(self): """ A user who was an apps mall steward is now an org steward """ profile = model_access.get_profile('bigbrother') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('APPS_MALL_STEWARD' in groups) self.assertEqual(profile.highest_role(), 'APPS_MALL_STEWARD') auth_data = { 'dn': 'Big Brother bigbrother', 'cn': 'Big Brother', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Minitrue', 'is_org_steward': True, 'is_apps_mall_steward': False, 'is_metrics_user': False, 'is_beta_user': False } self.auth.authorization_update( 'bigbrother', auth_data, method='test_org_steward_to_apps_mall_steward') profile = model_access.get_profile('bigbrother') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('ORG_STEWARD' in groups) self.assertEqual(profile.highest_role(), 'ORG_STEWARD')
def test_get_self_library_when_listing_disabled_enabled(self): """ GET /self/library """ user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' response = self.client.get(url, format='json') listing_ids = [record['listing']['id'] for record in response.data] first_listing_id = listing_ids[0] # Should be 2 self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(listing_ids, [2, 1], 'Comparing Ids #1') # Get Library for current user after listing was disabled self._edit_listing(first_listing_id, {'is_enabled': False}) user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' response = self.client.get(url, format='json') listing_ids = [record['listing']['id'] for record in response.data] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(listing_ids, [1], 'Comparing Ids #2') # Get Library for current user after listing was Enable self._edit_listing(first_listing_id, {'is_enabled': True}) user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' response = self.client.get(url, format='json') listing_ids = [record['listing']['id'] for record in response.data] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(listing_ids, [2, 1], 'Comparings Ids #3')
def test_org_steward_to_user(self): """ A user who was an org steward is now a regular user """ profile = model_access.get_profile('wsmith') profile.auth_expires = datetime.datetime.now(pytz.utc) profile.save() stewarded_orgs = profile.stewarded_organizations.values_list('title', flat=True) self.assertTrue('Ministry of Truth' in stewarded_orgs) self.assertEqual(profile.highest_role(), 'ORG_STEWARD') groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('ORG_STEWARD' in groups) auth_data = { 'dn': 'Winston Smith wsmith', 'cn': 'Winston Smith', 'clearances': ['U', 'C', 'S', 'TS'], 'formal_accesses': [], 'visas': [], 'duty_org': 'Minitrue', 'is_org_steward': False, 'is_apps_mall_steward': False, 'is_metrics_user': False } self.auth.authorization_update('wsmith', auth_data, method='test_org_steward_to_user') profile = model_access.get_profile('wsmith') stewarded_orgs = profile.stewarded_organizations.values_list('title', flat=True) self.assertTrue(len(stewarded_orgs) == 0) groups = profile.user.groups.values_list('name', flat=True) self.assertTrue('USER' in groups) self.assertTrue(len(groups) == 1) self.assertEqual(profile.highest_role(), 'USER')
def test_get_library_self_when_listing_disabled_enabled(self): """ GET /self/library """ user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' response = self.client.get(url, format='json') listing_ids = [record['listing']['id'] for record in response.data] first_listing_id = listing_ids[0] # Should be 2 self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(listing_ids, [2, 1], 'Comparing Ids #1') # Get Library for current user after listing was disabled _edit_listing(self, first_listing_id, {'is_enabled': False}) user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' response = self.client.get(url, format='json') listing_ids = [record['listing']['id'] for record in response.data] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(listing_ids, [1], 'Comparing Ids #2') # Get Library for current user after listing was Enable _edit_listing(self, first_listing_id, {'is_enabled': True}) user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' response = self.client.get(url, format='json') listing_ids = [record['listing']['id'] for record in response.data] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(listing_ids, [2, 1], 'Comparings Ids #3')
def test_create_library(self): """ POST to /self/library """ # Listing is Enabled user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' data = {'listing': {'id': '1'}, 'folder': ''} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['listing']['id'], 1) # Disable Listing self._edit_listing(1, {'is_enabled': False}, 'wsmith') # POST to /self/library after listing disabled user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' data = {'listing': {'id': '1'}, 'folder': ''} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) # Enabled Listing self._edit_listing(1, {'is_enabled': True}, 'wsmith') # POST to /self/library after listing disabled user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' data = {'listing': {'id': '1'}, 'folder': ''} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['listing']['id'], 1)
def test_gave_single_user_feedback_listing(self): """ betafish user """ # Create a positive feedback url = '/api/listing/1/feedback/' data = {"feedback": 1} user = generic_model_access.get_profile('bettafish').user self.client.force_authenticate(user=user) response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) url = '/api/listing/1/feedback/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 1) url = '/api/listing/1/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 1) self.assertEqual(response.data['feedback_score'], 1) # Login as betaraybill (no feedback given to listing #1) user = generic_model_access.get_profile('betaraybill').user self.client.force_authenticate(user=user) url = '/api/listing/1/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 0) self.assertEqual(response.data['feedback_score'], 1)
def test_feedback_score_positive_then_negative(self): """ betafish user """ user = generic_model_access.get_profile('bettafish').user self.client.force_authenticate(user=user) # Create a positive feedback url = '/api/listing/1/feedback/' data = {"feedback": 1} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) url = '/api/listing/1/feedback/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 1) url = '/api/listing/1/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 1) self.assertEqual(response.data['feedback_score'], 1) # Login as betaraybill user = generic_model_access.get_profile('betaraybill').user self.client.force_authenticate(user=user) # Create a negative feedback url = '/api/listing/1/feedback/' data = {"feedback": -1} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) url = '/api/listing/1/feedback/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], -1) url = '/api/listing/1/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], -1) self.assertEqual(response.data['feedback_score'], 0) # Login as bettafish again user = generic_model_access.get_profile('bettafish').user self.client.force_authenticate(user=user) # Create a negative feedback url = '/api/listing/1/feedback/' data = {"feedback": -1} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) url = '/api/listing/1/feedback/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], -1) url = '/api/listing/1/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], -1) self.assertEqual(response.data['feedback_score'], -2)
def test_listing_508_compliant_true(self): LISTING_ID = 11 USER_NAME = 'bigbrother' request_profile = generic_model_access.get_profile(USER_NAME) user = generic_model_access.get_profile(USER_NAME).user self.client.force_authenticate(user=user) APITestHelper.edit_listing(self, LISTING_ID, {'is_508_compliant': True}, USER_NAME) url = '/api/listing/{0!s}/'.format(LISTING_ID) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['is_508_compliant'], True)
def edit_listing(test_case_instance, id, input_data, default_user='******'): """ Helper Method to modify a listing Args: test_case_instance id input_data default_user(optional) Return: response """ url = '/api/listing/{0!s}/'.format(id) user = generic_model_access.get_profile(default_user).user test_case_instance.client.force_authenticate(user=user) data = test_case_instance.client.get(url, format='json').data for current_key in input_data: if current_key in data: data[current_key] = input_data[current_key] # PUT the Modification response = test_case_instance.client.put(url, data, format='json') test_case_instance.assertEqual(response.status_code, status.HTTP_200_OK) return response
def ApplicationView(request, id='0'): """ Single application """ if not hal.validate_version(request.META.get('HTTP_ACCEPT')): return Response('Invalid version requested', status=status.HTTP_406_NOT_ACCEPTABLE) listing_root_url = hal.get_abs_url_for_iwc(request) profile = model_access.get_profile(request.user.username) # TODO: only include the fields that are necessary for IWC. This will also # allow us to sever ties with ozpcenter.api.listing.serializers # This minimal definition of what a Listing object must have should be # advertised so that others can use IWC with their own systems queryset = listing_model_access.get_listing_by_id(profile.user.username, id) if not queryset: return Response(status=status.HTTP_404_NOT_FOUND) serializer = listing_serializers.ListingSerializer(queryset, context={'request': request}) data = serializer.data data = hal.add_hal_structure(data, request, hal.generate_content_type( request.accepted_media_type)) return Response(data)
def create_base_structure(request, type='application/json'): """ Creates the initial HAL structure for a given request """ root_url = request.build_absolute_uri( '/' ) # flake8: noqa TODO: Is Necessary? - Variable not being used in method profile = model_access.get_profile( request.user.username ) # flake8: noqa TODO: Is Necessary? - Variable not being used in method data = { "_links": { "curies": { "href": "http://ozoneplatform.org/docs/rels/{rel}", "name": "ozp", "templated": True }, "self": { "href": '{0!s}'.format(request.build_absolute_uri(request.path)), "type": type } }, "_embedded": {} } return data
def create(self, validated_data): """ Create BookmarkPermission entry Required Fields: pass """ username = self.context['request'].user.username request_profile = self.context['request'].user.profile bookmark_entry = self.context['bookmark_entry'] user_type = validated_data.get('user_type') target_username = validated_data.get('profile', {}).get('user', {}).get('username') if not target_username: raise errors.ValidationException('Valid Username is Required') target_profile = generic_model_access.get_profile(target_username) if not target_profile: raise errors.ValidationException('Valid User is Required') return model_access.share_bookmark_entry(request_profile, bookmark_entry, target_profile, None, user_type)
def _get_profile_url_for_username(self, username, postfix=None): """ Get Profile Url """ postfix = postfix or '' user_id = generic_model_access.get_profile(username).user.id return '/api/profile/{}/{}'.format(user_id, postfix)
def update_subscription(request_username, subscription_instance, entity_type, entity_id): """ Update Subscription's entity Args: Subscription_instance (Subscription): Subscription_instance author_username (str): Username of author Return: Subscription: Updated Subscription """ request_profile = generic_model_access.get_profile(request_username) # TODO: Check if user exist, if not throw Exception Error ? # Why does 'request_profile is not subscription_instance.target_profile' not work??? if request_profile.highest_role() not in ['APPS_MALL_STEWARD', 'ORG_STEWARD']: if request_profile.user.id is not subscription_instance.target_profile.user.id: raise Exception('Can not update a subscription that you do not own') subscription_ids = Subscription.objects.filter(target_profile=subscription_instance.target_profile, entity_type=entity_type, entity_id=entity_id).values_list("id", flat=True) # If subscription_ids >= 1 if means that there is already that subscription that exist if len(subscription_ids) >= 1: if subscription_instance.id in subscription_ids: return subscription_instance else: raise Exception('Can not update a subscription that already exist') subscription_instance.entity_type = entity_type subscription_instance.entity_id = entity_id subscription_instance.save() return subscription_instance
def test_counts_in_listings(self): """ Supported query params: org (agency title), approval_status, enabled """ user = generic_model_access.get_profile('julia').user self.client.force_authenticate(user=user) url = '/api/listing/' response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.data last_item = data[-1] expected_item = {"counts": { "organizations": { "4": 0, "2": 0, "1": 100, "3": 10 }, "REJECTED": 0, "enabled": 110, "APPROVED_ORG": 0, "total": 110, "APPROVED": 110, "PENDING": 0, "IN_PROGRESS": 0, "DELETED": 0 } } self.assertEquals(last_item, expected_item)
def test_feedback_score_after_feedback_delete(self): """ betafish user """ user = generic_model_access.get_profile('bettafish').user self.client.force_authenticate(user=user) # Create a positive feedback url = '/api/listing/1/feedback/' data = {"feedback": 1} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) url = '/api/listing/1/feedback/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 1) url = '/api/listing/1/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 1) self.assertEqual(response.data['feedback_score'], 1) url = '/api/listing/1/feedback/1/' response = self.client.delete(url, format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) url = '/api/listing/1/' response = self.client.get(url, format='json') self.assertEqual(response.data['feedback'], 0) self.assertEqual(response.data['feedback_score'], 0)
def test_log_listing_modification(self): author = generic_model_access.get_profile('wsmith') air_mail = models.Listing.objects.for_user(author.user.username).get( title='Air Mail') # fields to change change_details = [ {'old_value': '', 'new_value': 'lots of things', 'field_name': 'what_is_new'}, {'old_value': 'Ministry of Truth', 'new_value': 'Ministry of Love', 'field_name': 'agency'} ] model_access.log_listing_modification(author, air_mail, change_details) listing_activities = air_mail.listing_activities.filter( action=models.ListingActivity.MODIFIED) modified_activity = listing_activities[0] self.assertEqual(modified_activity.author.user.username, author.user.username) change_details = modified_activity.change_details.all() self.assertEqual(len(change_details), 2) air_mail = models.Listing.objects.for_user(author.user.username).get( title='Air Mail') self.assertEqual(air_mail.last_activity, modified_activity)
def test_dismiss_self_notification(self): url = '/api/self/notification/' # test authorized user user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) response = self.client.get(url, format='json') notification_ids = [] for i in response.data: notification_ids.append(i['id']) self.assertEqual(2, len(notification_ids)) # now dismiss the first notification dismissed_notification_id = notification_ids[0] url = url + str(dismissed_notification_id) + '/' response = self.client.delete(url, format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # now get our notifications again, make sure the one was removed url = '/api/self/notification/' # test authorized user response = self.client.get(url, format='json') notification_ids = [] for i in response.data: notification_ids.append(i['id']) self.assertEqual(1, len(notification_ids)) self.assertTrue(notification_ids[0] != dismissed_notification_id)
def _request_helper(self, url, method, data=None, username='******', status_code=200): """ Request Helper """ user = generic_model_access.get_profile(username).user self.client.force_authenticate(user=user) response = None if method.upper() == 'GET': response = self.client.get(url, format='json') elif method.upper() == 'POST': response = self.client.post(url, data, format='json') elif method.upper() == 'PUT': response = self.client.put(url, data, format='json') elif method.upper() == 'DELETE': response = self.client.delete(url, format='json') else: raise Exception('method is not supported') if response: if status_code == 200: self.assertEqual(response.status_code, status.HTTP_200_OK) elif status_code == 201: self.assertEqual(response.status_code, status.HTTP_201_CREATED) elif status_code == 204: self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) else: raise Exception('status code is not supported') return response
def create_listing_review(username, listing, rating, text=None): """ Create a new review for a listing Args: username (str): author's username rating (int): rating, 1-5 text (Optional(str)): review text Returns: { "rate": rate, "text": text, "author": author.id, "listing": listing.id, "id": review.id } """ author = generic_model_access.get_profile(username) review = models.Review(listing=listing, author=author, rate=rating, text=text) review.save() # update this listing's rating _update_rating(username, listing) resp = { "rate": rating, "text": text, "author": author.id, "listing": listing.id, "id": review.id } return resp
def get_recommendation_feedback(username, listing): """ Get recommendation feedback entry for listing """ target_profile = generic_model_access.get_profile(username) return models.RecommendationFeedback.objects.for_user(username).filter( target_profile=target_profile, target_listing=listing).first()
def test_disabled_profile(self): profile = model_access.get_profile('jones') profile.user.is_active = False profile.user.save() profile = pkiauth._get_profile_by_dn('Jones jones') self.assertEqual(profile, None)
def delete_listing(username, listing): """ TODO: need a way to keep track of this listing as being deleted. for now just remove """ user = generic_model_access.get_profile(username) app_owners = [i.user.username for i in listing.owners.all()] # ensure user is the author of this review, or that user is an org # steward or apps mall steward priv_roles = ['APPS_MALL_STEWARD', 'ORG_STEWARD'] if user.highest_role() in priv_roles: pass elif username not in app_owners: raise errors.PermissionDenied() if listing.is_deleted: raise errors.PermissionDenied('The listing has already been deleted') listing = _add_listing_activity(user, listing, models.ListingActivity.DELETED) listing.is_deleted = True listing.is_enabled = False listing.approval_status = models.Listing.DELETED # TODO Delete the values of other field # Keep lisiting as shell listing for history listing.save()
def test_create_peer_bookmark_notification_app_mall_steward(self): url = '/api/notification/' user = generic_model_access.get_profile('bigbrother').user self.client.force_authenticate(user=user) now = datetime.datetime.now(pytz.utc) data = { "expires_date": str(now), "message": "A Simple Peer to Peer Notification", "peer": { "user": { "username": "******" }, "folder_name": "folder" } } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(response.data['message'], 'A Simple Peer to Peer Notification') self.assertEqual(response.data['notification_type'], 'PEER') self.assertEqual(response.data['agency'], None) self.assertEqual(response.data['listing'], None) self.assertTrue('expires_date' in data)
def test_update_library(self): user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) url = '/api/self/library/' response = self.client.get(url, format='json') put_data = [] position_count = 0 for i in response.data: position_count = position_count + 1 data = { 'id': i['id'], 'folder': 'test', 'listing': { 'id': i['listing']['id'] }, 'position': position_count } put_data.append(data) url = '/api/self/library/update_all/' response = self.client.put(url, put_data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_users_based_on_roles_for_all_access_control_levels(self, mock_request): """ Testing GET /api/profile/?roles={role} endpoint """ settings.OZP['USE_AUTH_SERVER'] = True roles_combos = {'APPS_MALL_STEWARD': [1, 0, 0], 'ORG_STEWARD': [0, 1, 0], 'USER': [0, 0, 1]} user_list = ['bigbrother', 'wsmith', 'jones'] for role in roles_combos: combo = roles_combos[role] for current_username in user_list: # Get all '{role}' profiles at '{current_username}' access control level user = generic_model_access.get_profile(current_username).user self.client.force_authenticate(user=user) url = '/api/profile/?role={0!s}'.format(role) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) usernames = [i['user']['username'] for i in response.data] self.assertEquals('bigbrother' in usernames, bool(combo[0]), 'bigbrother role [{0!s}] in {1!s}'.format(role, bool(combo[0]))) self.assertEquals('julia' in usernames, bool(combo[1])) self.assertEquals('jones' in usernames, bool(combo[2])) displaynames = [i['display_name'] for i in response.data] self.assertEqual(displaynames, sorted(displaynames))
def test_log_listing_modification(self): author = generic_model_access.get_profile('wsmith') air_mail = models.Listing.objects.for_user( author.user.username).get(title='Air Mail') # fields to change change_details = [{ 'old_value': '', 'new_value': 'lots of things', 'field_name': 'what_is_new' }, { 'old_value': 'Ministry of Truth', 'new_value': 'Ministry of Love', 'field_name': 'agency' }] model_access.log_listing_modification(author, air_mail, change_details) listing_activities = air_mail.listing_activities.filter( action=models.ListingActivity.MODIFIED) modified_activity = listing_activities[0] self.assertEqual(modified_activity.author.user.username, author.user.username) change_details = modified_activity.change_details.all() self.assertEqual(len(change_details), 2) air_mail = models.Listing.objects.for_user( author.user.username).get(title='Air Mail') self.assertEqual(air_mail.last_activity, modified_activity)
def create_self_user_library_entry(username, listing_id, folder_name=None): """ Create ApplicationLibrary Entry Args: username (str): the username to create a library entry for (Bookmark) listing_id (str): the id of the listing folder_name (str) optional: the name of the folder Return: ApplicationLibrary: New Entry of ApplicationLibrary Raise: Exception: if profile was not found based on username or or listing was not found based on listing_id """ listing = listing_model_access.get_listing_by_id(username, listing_id) owner = generic_model_access.get_profile(username) if not listing or not owner: raise Exception('Listing or user not found') logger.debug('Adding bookmark for listing[{0!s}], user[{1!s}]'.format(listing.title, username), extra={'user': username}) entry = models.ApplicationLibraryEntry(listing=listing, owner=owner, folder=folder_name) entry.save() return entry
def create(self, validated_data): """ Create BookmarkPermission entry Required Fields: pass """ username = self.context['request'].user.username request_profile = self.context['request'].user.profile bookmark_entry = self.context['bookmark_entry'] user_type = validated_data.get('user_type') target_username = validated_data.get('profile', {}).get('user', {}).get('username') if not target_username: raise errors.ValidationException('Valid Username is Required') target_profile = generic_model_access.get_profile(target_username) if not target_profile: raise errors.ValidationException('Valid User is Required') return model_access.share_bookmark_entry( request_profile, bookmark_entry, target_profile, None, user_type)
def get_agency_pending_notifications(username): """ Gets all notifications that are regarding a listing in this user's agencies Includes * Agency Notifications Does not include * System Notifications * Listing Notifications Args: username (str): current username to get notifications Returns: django.db.models.query.QuerySet(models.Notification): List of user's agencies pending notifications """ user_agency = generic_model_access.get_profile( username).organizations.all() unexpired_agency_notifications = models.Notification.objects.filter( expires_date__gt=datetime.datetime.now(pytz.utc), agency__pk_in=user_agency, listing__isnull=True) return unexpired_agency_notifications
def test_update_review(self): """ Also tests the listing/<id>/activity endpoint """ # create a new review user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) air_mail_id = models.Listing.objects.get(title='Air Mail').id url = '/api/listing/{0!s}/review/'.format(air_mail_id) data = {'rate': 4, 'text': 'winston test review'} response = self.client.post(url, data, format='json') review_id = response.data['id'] self.assertEqual(response.status_code, status.HTTP_201_CREATED) # now update it url = '/api/listing/{0!s}/review/{1!s}/'.format(air_mail_id, review_id) data = {'rate': 4, 'text': 'winston test review'} response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(4, response.data['rate']) # test the listing/<id>/activity endpoint url = '/api/listing/{0!s}/activity/'.format(air_mail_id) response = self.client.get(url, format='json') activiy_actions = [i['action'] for i in response.data] self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue(models.ListingActivity.REVIEW_EDITED in activiy_actions) # try to edit a review from another user - should fail url = '/api/listing/{0!s}/review/1/'.format(air_mail_id) data = {'rate': 4, 'text': 'winston test review'} response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_get_reviews(self): user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) air_mail_id = models.Listing.objects.get(title='Air Mail').id url = '/api/listing/{0!s}/review/'.format(air_mail_id) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK)
def update_notification(author_username, notification_instance, expires_date): """ Update Notification Args: notification_instance (models.Notification): notification_instance author_username (str): Username of author Return: models.Notification: Updated Notification """ notification_action = NotificationActionEnum.UPDATE notification_type = NotificationTypeEnum.SYSTEM if notification_instance.listing is not None: notification_type = NotificationTypeEnum.LISTING elif notification_instance.agency is not None: notification_type = NotificationTypeEnum.AGENCY user = generic_model_access.get_profile(author_username) # TODO: Check if user exist, if not throw Exception Error ? user_role_type = UserRoleType(user.highest_role()) _check_profile_permission( user_role_type, notification_action, notification_type)() notification_instance.expires_date = expires_date notification_instance.save() return notification_instance
def test_get_users_based_on_roles_for_all_access_control_levels( self, mock_request): """ Testing GET /api/profile/?roles={role} endpoint """ settings.OZP['USE_AUTH_SERVER'] = True roles_combos = { 'APPS_MALL_STEWARD': [1, 0, 0], 'ORG_STEWARD': [0, 1, 0], 'USER': [0, 0, 1] } user_list = ['bigbrother', 'wsmith', 'jones'] for role in roles_combos: combo = roles_combos[role] for current_username in user_list: # Get all '{role}' profiles at '{current_username}' access control level user = generic_model_access.get_profile(current_username).user self.client.force_authenticate(user=user) url = '/api/profile/?role={0!s}'.format(role) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) usernames = [i['user']['username'] for i in response.data] self.assertEquals( 'bigbrother' in usernames, bool(combo[0]), 'bigbrother role [{0!s}] in {1!s}'.format( role, bool(combo[0]))) self.assertEquals('julia' in usernames, bool(combo[1])) self.assertEquals('jones' in usernames, bool(combo[2])) displaynames = [i['display_name'] for i in response.data] self.assertEqual(displaynames, sorted(displaynames))
def test_dismiss_self_notification(self): url = '/api/self/notification/' user = generic_model_access.get_profile('wsmith').user self.client.force_authenticate(user=user) response = self.client.get(url, format='json') notification_ids = [] for i in response.data: notification_ids.append(i['id']) self.assertEqual(3, len(notification_ids)) # now dismiss the first notification dismissed_notification_id = notification_ids[0] url = url + str(dismissed_notification_id) + '/' response = self.client.delete(url, format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) # now get our notifications again, make sure the one was removed url = '/api/self/notification/' response = self.client.get(url, format='json') notification_ids = [] for i in response.data: notification_ids.append(i['id']) self.assertEqual(2, len(notification_ids)) self.assertTrue(notification_ids[0] != dismissed_notification_id)
def IntentView(request, id='0'): """ Single intent """ if not hal.validate_version(request.META.get('HTTP_ACCEPT')): return Response('Invalid version requested', status=status.HTTP_406_NOT_ACCEPTABLE) root_url = hal.get_abs_url_for_iwc( request ) # flake8: noqa TODO: Is Necessary? - Variable not being used in method profile = model_access.get_profile( request.user.username ) # flake8: noqa TODO: Is Necessary? - Variable not being used in method queryset = intent_model_access.get_intent_by_id(id) if not queryset: return Response(status=status.HTTP_404_NOT_FOUND) serializer = intent_serializers.IntentSerializer( queryset, context={'request': request}) data = serializer.data data = hal.add_hal_structure( data, request, hal.generate_content_type(request.accepted_media_type)) return Response(data)
def to_representation(self, data): ret = super(StorefrontListingSerializer, self).to_representation(data) request_user = generic_model_access.get_profile(self.context['request'].user) # TODO: Get the profile from view request instead of getting it from db again ret['feedback'] = self._feedback(request_user, data) ret['is_bookmarked'] = self._is_bookmarked(request_user, data) return ret
def test_update_storefront_customizations(self, mock_request): settings.OZP['USE_AUTH_SERVER'] = True user = generic_model_access.get_profile('bigbrother').user self.client.force_authenticate(user=user) url = '/api/self/profile/' data = { "storefront_customizations": [ {"section": "FEATURED", "is_hidden": True}, {"section": "RECOMMENDED", "position": 1}, {"section": "RECENTLY_ADDED", "position": 2, "is_hidden": False}, {"section": "MOST_POPULAR", "position": 3, "is_hidden": True}, {"section": "FREQUENTLY_VISITED"}, {"section": "UPDATES", "is_hidden": False}, {"section": "MY_LISTINGS", "position": 4, "is_hidden": False}, ] } response = self.client.put(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) expected_results = [] for item in data['storefront_customizations']: expected_item = { "section": item['section'], "position": item['position'] if 'position' in item else 0, "is_hidden": item['is_hidden'] if 'is_hidden' in item else False, "size": item['size'] if 'size' in item else None, } expected_results.append(expected_item) results = sorted(response.data.get('storefront_customizations'), key=lambda x: x['section']) expected_results = sorted(expected_results, key=lambda x: x['section']) self.assertEqual(results, expected_results)