def obj_update(self, bundle, skip_errors=False, **kwargs): from tastypie.serializers import Serializer from models import ProgramFeature serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize(bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json')) except Exception: deserialized = None if deserialized is None: return ImmediateHttpResponse(response = http.HttpBadRequest('Empty update data')) time_difference = datetime.strptime(deserialized['new_end_time'], "%Y-%m-%d %H:%M:%S") - datetime.strptime(deserialized['old_end_time'], "%Y-%m-%d %H:%M:%S") Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(startTime=F('startTime') + time_difference) Presentation.objects.filter(startTime__gte=deserialized['old_end_time']).update(endTime=F('endTime') + time_difference) later_presentations = Presentation.objects.filter(startTime__gte=deserialized['old_end_time']) changed_presentation = Presentation.objects.get(startTime=deserialized['old_start_time']) changed_presentation.startTime = deserialized['new_start_time'] changed_presentation.endTime = deserialized['new_end_time'] changed_presentation.save()
def obj_update(self, bundle, skip_errors=False, **kwargs): """ Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned as acceptable exceptions which get transformed into a CREATE operation. We don't want such a behavior. So we catch does exceptions and throw an BadRequest message """ from tastypie.serializers import Serializer try: serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize(bundle.request.raw_post_data, format=bundle.request.META.get('CONTENT_TYPE', 'application/json')) except Exception: deserialized = None del serdes if deserialized is None: return ImmediateHttpResponse(response = http.HttpBadRequest()) if 'unregister_c2dm' in deserialized and deserialized['unregister_c2dm'] == True: bundle.data['c2dm_id'] = None updated_bundle = super(UserResource, self).obj_update(bundle, skip_errors=skip_errors, **kwargs) return updated_bundle except (NotFound, MultipleObjectsReturned): raise ImmediateHttpResponse(response = http.HttpBadRequest())
def obj_update(self, bundle, skip_errors=False, **kwargs): """ Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned as acceptable exceptions which get transformed into a CREATE operation. We don't want such a behavior. So we catch does exceptions and throw an BadRequest message """ from tastypie.serializers import Serializer try: serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize( bundle.request.raw_post_data, format=bundle.request.META.get('CONTENT_TYPE', 'application/json')) except Exception: deserialized = None del serdes if deserialized is None: return ImmediateHttpResponse(response=http.HttpBadRequest()) if 'unregister_c2dm' in deserialized and deserialized[ 'unregister_c2dm'] == True: bundle.data['c2dm_id'] = None updated_bundle = super(UserResource, self).obj_update(bundle, skip_errors=skip_errors, **kwargs) return updated_bundle except (NotFound, MultipleObjectsReturned): raise ImmediateHttpResponse(response=http.HttpBadRequest())
def send_invitation(request): """ Send an invitation to another person via email. NOT TESTED YET """ if request.user.is_authenticated() and request.user.is_active: if 'email' in request.POST: email = request.POST['email'] else: return HttpResponseBadRequest('Mandatory email parameter not provided.') if 'message' in request.POST: message = request.POST['message'] else: message = 'Tritt score.it bei und sehe deine Handballergebnisse online!' profile = None if 'profile' in request.POST: serializer = Serializer() profile = serializer.deserialize(request.POST['profile']) subject = '{0} {1} lädt dich zu Score.it ein!'.format(request.user.first_name, request.user.last_name) if profile: profile_link = 'http://score-it.de/?a=invite&p={0}'.format(profile.id) body = '{0} {1} hat ein Spielerprofil bei Score.it für dich erstellt. Melde dich jetzt bei Score.it an, um deine Handballergebnisse online abzurufen! Zum anmelden, klicke einfach folgenden Link: {3}'.format(request.user.first_name, request.user.last_name, profile_link) else: body = '{0} {1} hat dir eine Einladung zu der Sportplatform Score.it geschickt:<br>{2}Um dich anzumelden, besuche einfach http://score-it.de/!'.format(request.user.first_name, request.user.last_name, message) sender = '*****@*****.**' recipients = [email] send_mail(subject, body, sender, recipients) return HttpResponse('') else: return HttpUnauthorized('Authentication through active user required.')
def update_detail(self, object_list, bundle): from features.conference_role.models import ChairRoleCredential if hasattr(bundle.request, 'user') and not bundle.request.user.is_anonymous(): ''' User must be checked in at environment for which this feature is defined ''' confrole_obj = bundle.obj if confrole_obj is None: raise Unauthorized( "Non-existent conference role resource access.") env_obj = confrole_obj.environment area_obj = confrole_obj.area user_profile = bundle.request.user.get_profile( ) # # will be an instance of UserProfile => available context if not is_checked_in(user_profile, env_obj, area_obj): raise Unauthorized( "Users not checked-in cannot delete their conference role." ) ''' Deserialize data payload and check if trying to set role to `session_chair` value. In that case, a chair_password is required ''' serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize( bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json')) except Exception: raise Unauthorized("Update data unreadable.") if deserialized is None: raise Unauthorized("Empty update data not allowed.") if "role" in deserialized and deserialized[ 'role'] == "session_chair": print "Attempting to become session_chair", chair_password = deserialized.get("chair_password", None) if not chair_password: raise Unauthorized( "Cannot alter conference role to `session_chair` without credentials." ) ''' check with the chair password recorded for this user ''' try: chair = ChairRoleCredential.objects.get( user_profile=user_profile) if not chair.check_password(chair_password): raise Unauthorized( "Incorrect credentials for attempt to set `session_chair` conference role." ) except Exception, ex: print ex raise Unauthorized( "User is not listed as a `session_chair`.") return True
class ProjectResourceTest(TestCase): fixtures = ['data.json'] def setUp(self): super(ProjectResourceTest, self).setUp() self.username = '******' self.password = '******' #self.user = User.objects.create_user(self.username, '*****@*****.**', self.password) #self.api = slumber.API("http://localhost:5000/api/v1/", auth=(self.username, self.password)) self.post_data = { 'title': 'testTitle', 'description': 'testDescription', 'user' : '/api/v1/user/4ea9c4fdbb69337f8e000002/', 'tasks': [] } self.serializer = Serializer() def test_post_project(self): format = self.serializer.content_types.get('json') serialized_data = self.serializer.serialize(self.post_data, format='application/json') self.assertEqual(Project.objects.count(), 1) resp = self.client.post('/api/v1/project/', data = serialized_data, content_type='application/json') self.assertEqual(resp.status_code, 201) self.assertEqual(Project.objects.count(), 2) def test_put_project(self): format = self.serializer.content_types.get('json') project_data = self.post_data project_data['title'] = 'changedTitle' serialized_data = self.serializer.serialize(project_data, format='application/json') resp = self.client.put('/api/v1/project/4ea9c4fdbb69337f8e000001/', data = serialized_data, content_type='application/json') self.assertEqual(resp.status_code, 204) resp = self.client.get('/api/v1/project/') self.assertEqual("changedTitle", self.serializer.deserialize(resp.content)['objects'][0]['title']) def test_get_projects(self): resp = self.client.get('/api/v1/project/') self.assertEqual(resp.status_code, 200) self.assertTrue(resp['Content-Type'].startswith('application/json')) self.serializer.from_json(resp.content) self.assertEqual(len(self.serializer.deserialize(resp.content)['objects']), 1) assert True """def test_get_tasks(self):
def obj_update(self, bundle, skip_errors=False, **kwargs): """ Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned as acceptable exceptions which get transformed into a CREATE operation. We don't want such a behavior. So we catch does exceptions and throw an BadRequest message """ from tastypie.serializers import Serializer from models import ConferenceRole try: serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize( bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json')) except Exception: deserialized = None if deserialized is None: return ImmediateHttpResponse( response=http.HttpBadRequest('Empty update data')) ''' Check for the existence of the role parameter in the deserialized data ''' if not 'role' in deserialized: return ImmediateHttpResponse(response=http.HttpBadRequest( 'Missing conference role data')) if not deserialized['role'] in ConferenceRole.ROLE_TYPES: return ImmediateHttpResponse(response=http.HttpBadRequest( 'Conference role data not in accepted list')) updated_bundle = super(ConferenceRoleResource, self).obj_update(bundle, skip_errors=skip_errors, **kwargs) # create ConferenceRole entry user_profile = bundle.request.user.get_profile() role = deserialized['role'] confrole = ConferenceRole(conference=updated_bundle.obj, user_profile=user_profile, role=role) confrole.save() return updated_bundle except (NotFound, MultipleObjectsReturned), ex: raise ImmediateHttpResponse(response=http.HttpBadRequest())
def update_detail(self, object_list, bundle): from features.conference_role.models import ChairRoleCredential if hasattr(bundle.request, 'user') and not bundle.request.user.is_anonymous(): ''' User must be checked in at environment for which this feature is defined ''' confrole_obj = bundle.obj if confrole_obj is None: raise Unauthorized("Non-existent conference role resource access.") env_obj = confrole_obj.environment area_obj = confrole_obj.area user_profile = bundle.request.user.get_profile() # # will be an instance of UserProfile => available context if not is_checked_in(user_profile, env_obj, area_obj): raise Unauthorized("Users not checked-in cannot delete their conference role.") ''' Deserialize data payload and check if trying to set role to `session_chair` value. In that case, a chair_password is required ''' serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize(bundle.request.body, format=bundle.request.META.get('CONTENT_TYPE', 'application/json')) except Exception: raise Unauthorized("Update data unreadable.") if deserialized is None: raise Unauthorized("Empty update data not allowed.") if "role" in deserialized and deserialized['role'] == "session_chair": print "Attempting to become session_chair", chair_password = deserialized.get("chair_password", None) if not chair_password: raise Unauthorized("Cannot alter conference role to `session_chair` without credentials.") ''' check with the chair password recorded for this user ''' try: chair = ChairRoleCredential.objects.get(user_profile=user_profile) if not chair.check_password(chair_password): raise Unauthorized("Incorrect credentials for attempt to set `session_chair` conference role.") except Exception, ex: print ex raise Unauthorized("User is not listed as a `session_chair`.") return True
def obj_update(self, bundle, skip_errors=False, **kwargs): from tastypie.serializers import Serializer from models import ProgramFeature serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize(bundle.request.body, format=bundle.request.META.get( 'CONTENT_TYPE', 'application/json')) except Exception: deserialized = None if deserialized is None: return ImmediateHttpResponse( response=http.HttpBadRequest('Empty update data')) time_difference = datetime.strptime( deserialized['new_end_time'], "%Y-%m-%d %H:%M:%S") - datetime.strptime( deserialized['old_end_time'], "%Y-%m-%d %H:%M:%S") Presentation.objects.filter( startTime__gte=deserialized['old_end_time']).update( startTime=F('startTime') + time_difference) Presentation.objects.filter( startTime__gte=deserialized['old_end_time']).update( endTime=F('endTime') + time_difference) later_presentations = Presentation.objects.filter( startTime__gte=deserialized['old_end_time']) changed_presentation = Presentation.objects.get( startTime=deserialized['old_start_time']) changed_presentation.startTime = deserialized['new_start_time'] changed_presentation.endTime = deserialized['new_end_time'] changed_presentation.save()
class ResourceTestCase(TestCase): """ A useful base class for the start of testing Tastypie APIs. """ def setUp(self): super(ResourceTestCase, self).setUp() self.serializer = Serializer() self.api_client = TestApiClient() def get_credentials(self): """ A convenience method for the user as a way to shorten up the often repetitious calls to create the same authentication. Raises ``NotImplementedError`` by default. Usage:: class MyResourceTestCase(ResourceTestCase): def get_credentials(self): return self.create_basic('daniel', 'pass') # Then the usual tests... """ raise NotImplementedError("You must return the class for your Resource to test.") def create_basic(self, username, password): """ Creates & returns the HTTP ``Authorization`` header for use with BASIC Auth. """ import base64 return 'Basic %s' % base64.b64encode(':'.join([username, password])) def create_apikey(self, username, api_key): """ Creates & returns the HTTP ``Authorization`` header for use with ``ApiKeyAuthentication``. """ return 'ApiKey %s:%s' % (username, api_key) def create_digest(self, username, api_key, method, uri): """ Creates & returns the HTTP ``Authorization`` header for use with Digest Auth. """ from tastypie.authentication import hmac, sha1, uuid, python_digest new_uuid = uuid.uuid4() opaque = hmac.new(str(new_uuid), digestmod=sha1).hexdigest() return python_digest.build_authorization_request( username, method.upper(), uri, 1, # nonce_count digest_challenge=python_digest.build_digest_challenge(time.time(), getattr(settings, 'SECRET_KEY', ''), 'django-tastypie', opaque, False), password=api_key ) def create_oauth(self, user): """ Creates & returns the HTTP ``Authorization`` header for use with Oauth. """ from oauth_provider.models import Consumer, Token, Resource # Necessary setup for ``oauth_provider``. resource, _ = Resource.objects.get_or_create(url='test', defaults={ 'name': 'Test Resource' }) consumer, _ = Consumer.objects.get_or_create(key='123', defaults={ 'name': 'Test', 'description': 'Testing...' }) token, _ = Token.objects.get_or_create(key='foo', token_type=Token.ACCESS, defaults={ 'consumer': consumer, 'resource': resource, 'secret': '', 'user': user, }) # Then generate the header. oauth_data = { 'oauth_consumer_key': '123', 'oauth_nonce': 'abc', 'oauth_signature': '&', 'oauth_signature_method': 'PLAINTEXT', 'oauth_timestamp': str(int(time.time())), 'oauth_token': 'foo', } return 'OAuth %s' % ','.join([key+'='+value for key, value in oauth_data.items()]) def assertHttpOK(self, resp): """ Ensures the response is returning a HTTP 200. """ return self.assertEqual(resp.status_code, 200) def assertHttpCreated(self, resp): """ Ensures the response is returning a HTTP 201. """ return self.assertEqual(resp.status_code, 201) def assertHttpAccepted(self, resp): """ Ensures the response is returning either a HTTP 202 or a HTTP 204. """ return self.assertTrue(resp.status_code in [202, 204]) def assertHttpMultipleChoices(self, resp): """ Ensures the response is returning a HTTP 300. """ return self.assertEqual(resp.status_code, 300) def assertHttpSeeOther(self, resp): """ Ensures the response is returning a HTTP 303. """ return self.assertEqual(resp.status_code, 303) def assertHttpNotModified(self, resp): """ Ensures the response is returning a HTTP 304. """ return self.assertEqual(resp.status_code, 304) def assertHttpBadRequest(self, resp): """ Ensures the response is returning a HTTP 400. """ return self.assertEqual(resp.status_code, 400) def assertHttpUnauthorized(self, resp): """ Ensures the response is returning a HTTP 401. """ return self.assertEqual(resp.status_code, 401) def assertHttpForbidden(self, resp): """ Ensures the response is returning a HTTP 403. """ return self.assertEqual(resp.status_code, 403) def assertHttpNotFound(self, resp): """ Ensures the response is returning a HTTP 404. """ return self.assertEqual(resp.status_code, 404) def assertHttpMethodNotAllowed(self, resp): """ Ensures the response is returning a HTTP 405. """ return self.assertEqual(resp.status_code, 405) def assertHttpConflict(self, resp): """ Ensures the response is returning a HTTP 409. """ return self.assertEqual(resp.status_code, 409) def assertHttpGone(self, resp): """ Ensures the response is returning a HTTP 410. """ return self.assertEqual(resp.status_code, 410) def assertHttpTooManyRequests(self, resp): """ Ensures the response is returning a HTTP 429. """ return self.assertEqual(resp.status_code, 429) def assertHttpApplicationError(self, resp): """ Ensures the response is returning a HTTP 500. """ return self.assertEqual(resp.status_code, 500) def assertHttpNotImplemented(self, resp): """ Ensures the response is returning a HTTP 501. """ return self.assertEqual(resp.status_code, 501) def assertValidJSON(self, data): """ Given the provided ``data`` as a string, ensures that it is valid JSON & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_json(data) def assertValidXML(self, data): """ Given the provided ``data`` as a string, ensures that it is valid XML & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_xml(data) def assertValidYAML(self, data): """ Given the provided ``data`` as a string, ensures that it is valid YAML & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_yaml(data) def assertValidPlist(self, data): """ Given the provided ``data`` as a string, ensures that it is valid binary plist & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_plist(data) def assertValidJSONResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/json``) * The content is valid JSON """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/json')) self.assertValidJSON(resp.content) def assertValidXMLResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/xml``) * The content is valid XML """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/xml')) self.assertValidXML(resp.content) def assertValidYAMLResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``text/yaml``) * The content is valid YAML """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('text/yaml')) self.assertValidYAML(resp.content) def assertValidPlistResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/x-plist``) * The content is valid binary plist data """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/x-plist')) self.assertValidPlist(resp.content) def deserialize(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, this method checks the ``Content-Type`` header & attempts to deserialize the data based on that. It returns a Python datastructure (typically a ``dict``) of the serialized data. """ return self.serializer.deserialize(resp.content, format=resp['Content-Type']) def serialize(self, data, format='application/json'): """ Given a Python datastructure (typically a ``dict``) & a desired content-type, this method will return a serialized string of that data. """ return self.serializer.serialize(data, format=format) def assertKeys(self, data, expected): """ This method ensures that the keys of the ``data`` match up to the keys of ``expected``. It covers the (extremely) common case where you want to make sure the keys of a response match up to what is expected. This is typically less fragile than testing the full structure, which can be prone to data changes. """ self.assertEqual(sorted(data.keys()), sorted(expected))
class ApiTestCase(DirectSEOTestCase): fixtures = ['seo_views_testdata.json'] def setUp(self): super(ApiTestCase, self).setUp() # Create a test user and an API key for that user. self.user, created = User.objects.create_user(email='*****@*****.**', password='******') self.username = self.user.email self.user.save() self.key = ApiKey(user=self.user) self.key.save() self.api_key = self.key.key self.auth_qs = '?&username=%s&api_key=%s' % (self.username, self.api_key) self.entry_1 = SeoSite.objects.get(group=1) self.detail_url = '/api/v1/seosite/{0}/'.format(self.entry_1.pk) self.serializer = Serializer() def deserialize(self, resp): return self.serializer.deserialize(resp.content, format=resp['Content-Type']) def test_not_authorized(self): """ Test if a user can gain access without an API key """ user, created = User.objects.create_user(email='*****@*****.**', password='******') self.username = self.user.email user.save() resp = self.client.get("api/v1/jobsearch/?format=xml") self.assertEqual(resp.status_code, 404) resp = self.client.get("api/v1/seosite/?format=xml") self.assertEqual(resp.status_code, 404) key = ApiKey(user=self.user) def test_list_xml(self): resp = self.client.get("/api/v1/seosite/?%s&format=xml" % (self.auth_qs)) self.assertEqual(resp.status_code, 200) self.serializer.from_xml(resp.content) def test_list_json(self): resp = self.client.get("/api/v1/seosite/?%s&format=json" % (self.auth_qs)) self.assertEqual(len(self.deserialize(resp)['objects']), 1) self.assertEqual(resp.status_code, 200) self.serializer.from_json(resp.content) def test_get_detail_xml(self): resp = self.client.get("/api/v1/seosite/1/%s&format=xml" % (self.auth_qs)) self.assertEqual(resp.status_code, 200) self.serializer.from_xml(resp.content) def test_nopost(self): """ Ensure that POST requests are rejected. This test can be removed if/when we allow other methods besides GET to our resources. """ jobjson = ("""{"buid": 13543, "city": "Chester",\ "company": "Edward Jones", "country": "United States",\ "date_new": "2012-05-31T11:49:23",\ "mocs": "[\'021\', \'0193\', \'2820\', \'2G000\', \'2G091\',\ \'2R000\', \'2R071\', \'2R090\', \'2R171\', \'2S000\',\ \'2S071\', \'2S091\', \'2T000\', \'2T071\', \'2T091\',\ \'3A000\', \'3A071\', \'3A091\', \'3C000\', \'3C071\',\ \'3C090\', \'3C171\', \'3C191\', \'4A000\', \'4A091\',\ \'4A100\', \'4A191\', \'6F000\', \'6F091\', \'8M000\']",\ "onet": "43101100",\ "resource_uri": "/seo/v1/jobposting/29068157/",\ "state": "Virginia", "title": "Branch Office Administrator -\ Chester, VA - Branch 48113", "uid": "29068157"}""") resp = self.client.post("/api/v1/jobsearch/%s" % self.auth_qs, data=jobjson, content_type="application/json") # HTTP 405 == 'Method Not Allowed' self.assertEqual(resp.status_code, 405)
class ResourceTestCase(IMLUnitTestCase): """ A useful base class for the start of testing Tastypie APIs. """ def setUp(self): super(ResourceTestCase, self).setUp() self.serializer = Serializer() self.api_client = TestApiClient() def get_credentials(self): """ A convenience method for the user as a way to shorten up the often repetitious calls to create the same authentication. Raises ``NotImplementedError`` by default. Usage:: class MyResourceTestCase(ResourceTestCase): def get_credentials(self): return self.create_basic('daniel', 'pass') # Then the usual tests... """ raise NotImplementedError( "You must return the class for your Resource to test.") def create_basic(self, username, password): """ Creates & returns the HTTP ``Authorization`` header for use with BASIC Auth. """ import base64 return "Basic %s" % base64.b64encode(":".join([username, password])) def create_apikey(self, username, api_key): """ Creates & returns the HTTP ``Authorization`` header for use with ``ApiKeyAuthentication``. """ return "ApiKey %s:%s" % (username, api_key) def create_digest(self, username, api_key, method, uri): """ Creates & returns the HTTP ``Authorization`` header for use with Digest Auth. """ from tastypie.authentication import hmac, sha1, uuid, python_digest new_uuid = uuid.uuid4() opaque = hmac.new(str(new_uuid), digestmod=sha1).hexdigest() return python_digest.build_authorization_request( username, method.upper(), uri, 1, # nonce_count digest_challenge=python_digest.build_digest_challenge( time.time(), getattr(settings, "SECRET_KEY", ""), "django-tastypie", opaque, False), password=api_key, ) def create_oauth(self, user): """ Creates & returns the HTTP ``Authorization`` header for use with Oauth. """ from oauth_provider.models import Consumer, Token, Resource # Necessary setup for ``oauth_provider``. resource, _ = Resource.objects.get_or_create( url="test", defaults={"name": "Test Resource"}) consumer, _ = Consumer.objects.get_or_create(key="123", defaults={ "name": "Test", "description": "Testing..." }) token, _ = Token.objects.get_or_create( key="foo", token_type=Token.ACCESS, defaults={ "consumer": consumer, "resource": resource, "secret": "", "user": user }, ) # Then generate the header. oauth_data = { "oauth_consumer_key": "123", "oauth_nonce": "abc", "oauth_signature": "&", "oauth_signature_method": "PLAINTEXT", "oauth_timestamp": str(int(time.time())), "oauth_token": "foo", } return "OAuth %s" % ",".join( [key + "=" + value for key, value in oauth_data.items()]) def assertHttpOK(self, resp): """ Ensures the response is returning a HTTP 200. """ return self.assertEqual(resp.status_code, 200, resp.content) def assertHttpCreated(self, resp): """ Ensures the response is returning a HTTP 201. """ return self.assertEqual(resp.status_code, 201) def assertHttpAccepted(self, resp): """ Ensures the response is returning either a HTTP 202 or a HTTP 204. """ return self.assertTrue( resp.status_code in [202, 204], "Expected 202 or 204 status code, got %s" % resp.status_code) def assertHttpNoContent(self, resp): """ Ensures the response is returning a HTTP 204. """ return self.assertEqual(resp.status_code, 204) def assertHttpMultipleChoices(self, resp): """ Ensures the response is returning a HTTP 300. """ return self.assertEqual(resp.status_code, 300) def assertHttpSeeOther(self, resp): """ Ensures the response is returning a HTTP 303. """ return self.assertEqual(resp.status_code, 303) def assertHttpNotModified(self, resp): """ Ensures the response is returning a HTTP 304. """ return self.assertEqual(resp.status_code, 304) def assertHttpBadRequest(self, resp): """ Ensures the response is returning a HTTP 400. """ return self.assertEqual(resp.status_code, 400) def assertHttpUnauthorized(self, resp): """ Ensures the response is returning a HTTP 401. """ return self.assertEqual(resp.status_code, 401) def assertHttpForbidden(self, resp): """ Ensures the response is returning a HTTP 403. """ return self.assertEqual(resp.status_code, 403) def assertHttpNotFound(self, resp): """ Ensures the response is returning a HTTP 404. """ return self.assertEqual(resp.status_code, 404) def assertHttpMethodNotAllowed(self, resp): """ Ensures the response is returning a HTTP 405. """ return self.assertEqual(resp.status_code, 405) def assertHttpConflict(self, resp): """ Ensures the response is returning a HTTP 409. """ return self.assertEqual(resp.status_code, 409) def assertHttpGone(self, resp): """ Ensures the response is returning a HTTP 410. """ return self.assertEqual(resp.status_code, 410) def assertHttpTooManyRequests(self, resp): """ Ensures the response is returning a HTTP 429. """ return self.assertEqual(resp.status_code, 429) def assertHttpApplicationError(self, resp): """ Ensures the response is returning a HTTP 500. """ return self.assertEqual(resp.status_code, 500) def assertHttpNotImplemented(self, resp): """ Ensures the response is returning a HTTP 501. """ return self.assertEqual(resp.status_code, 501) def assertValidJSON(self, data): """ Given the provided ``data`` as a string, ensures that it is valid JSON & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_json(data) def assertValidXML(self, data): """ Given the provided ``data`` as a string, ensures that it is valid XML & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_xml(data) def assertValidYAML(self, data): """ Given the provided ``data`` as a string, ensures that it is valid YAML & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_yaml(data) def assertValidPlist(self, data): """ Given the provided ``data`` as a string, ensures that it is valid binary plist & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_plist(data) def assertValidJSONResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/json``) * The content is valid JSON """ self.assertHttpOK(resp) self.assertTrue(resp["Content-Type"].startswith("application/json")) self.assertValidJSON(resp.content) def assertValidXMLResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/xml``) * The content is valid XML """ self.assertHttpOK(resp) self.assertTrue(resp["Content-Type"].startswith("application/xml")) self.assertValidXML(resp.content) def assertValidYAMLResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``text/yaml``) * The content is valid YAML """ self.assertHttpOK(resp) self.assertTrue(resp["Content-Type"].startswith("text/yaml")) self.assertValidYAML(resp.content) def assertValidPlistResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/x-plist``) * The content is valid binary plist data """ self.assertHttpOK(resp) self.assertTrue(resp["Content-Type"].startswith("application/x-plist")) self.assertValidPlist(resp.content) def deserialize(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, this method checks the ``Content-Type`` header & attempts to deserialize the data based on that. It returns a Python datastructure (typically a ``dict``) of the serialized data. """ return self.serializer.deserialize(resp.content, format=resp["Content-Type"]) def serialize(self, data, format="application/json"): """ Given a Python datastructure (typically a ``dict``) & a desired content-type, this method will return a serialized string of that data. """ return self.serializer.serialize(data, format=format) def assertKeys(self, data, expected): """ This method ensures that the keys of the ``data`` match up to the keys of ``expected``. It covers the (extremely) common case where you want to make sure the keys of a response match up to what is expected. This is typically less fragile than testing the full structure, which can be prone to data changes. """ self.assertEqual(sorted(data.keys()), sorted(expected)) @contextlib.contextmanager def assertQueries(self, *prefixes): "Assert the correct queries are efficiently executed for a block." debug = connection.use_debug_cursor connection.use_debug_cursor = True count = len(connection.queries) yield if type(prefixes[0]) == int: assert prefixes[0] == len(connection.queries[count:]) else: for prefix, query in itertools.izip_longest( prefixes, connection.queries[count:]): assert prefix and query and query["sql"].startswith(prefix), ( prefix, query) connection.use_debug_cursor = debug
def is_authorized(self, request, object=None): from client.api import EnvironmentResource, AreaResource, AnnotationResource from coresql.models import Environment, Area from coresql.utils import str2bool if hasattr(request, 'user') and not request.user.is_anonymous(): env_obj = None area_obj = None if request.method.upper() == "GET": if 'environment' in request.GET: try: env_obj = Environment.objects.get( pk=request.GET['environment']) except: env_obj = None if 'area' in request.GET: try: area_obj = Area.objects.get(pk=request.GET['area']) except: area_obj = None ''' For GET requests we check if there is a virtual access flag set in the request. If the flag is not set, the default behavior is to assume physical check-in ''' if 'virtual' in request.GET: try: virtual = str2bool(request.GET['virtual']) if virtual and (area_obj or env_obj): ''' if the virtual flag is set to TRUE, then allow access, otherwise, check that the user is actually checked-in where he says he is ''' return True except ValueError: return False elif request.method.upper() == "POST": ''' for the rest of the methods check that the requesting user is actually checked in ''' serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize(request.raw_post_data, format=request.META.get( 'CONTENT_TYPE', 'application/json')) except Exception: return False if deserialized is None: return False if 'environment' in deserialized: try: #env_pk = int(deserialized['env']) env_obj = EnvironmentResource().get_via_uri( deserialized['environment'], request=request) except: env_obj = None if 'area' in deserialized: try: #area_pk = int(deserialized['area']) area_obj = AreaResource().get_via_uri( deserialized['area'], request=request) except: area_obj = None elif request.method.upper() in ["DELETE", "PUT"]: ann_res_uri = request.path try: ann_obj = AnnotationResource().get_via_uri(ann_res_uri, request=request) env_obj = ann_obj.environment area_obj = ann_obj.area #print "[authorization] env_obj: ", env_obj #print "[authorization] area_obj: ", area_obj except Exception: #print "[authorization] exception in getting annotation resource for deletion: ", ex env_obj = None area_obj = None user_profile = request.user.get_profile( ) ## will be an instance of UserProfile => available context return is_checked_in(user_profile, env_obj, area_obj) return False
def process_response(self, request, response): if hasattr(request, 'user') and request.user.is_authenticated(): credentials = request.user.pk else: credentials = -1 serializer = Serializer() format = determine_format( request, serializer, default_format='application/json') # clean POST received from client if request.method in ['POST', 'PUT']: try: cleansed = serializer.deserialize( request.body, format=format) except ValueError: cleansed = request.POST.dict() except UnsupportedFormat: cleansed = 'UNSUPPORTED_FORMAT' except AttributeError: cleansed = 'UNSUPPORTED_STRING' except Exception as e: logger.warning( u"[RESPONSE] %(c)s: %(e)s", {'c': e.__class__, 'e': e}) cleansed = 'STRING' finally: if hasattr(cleansed, 'keys'): cleansed.update( dict( (param, CLEANSED_SUBSTITUTE) for param in SENSITIVE_PARAMS if param in cleansed)) else: cleansed = 'STRING' # clean response sent to client if response.content and settings.FULL_RESPONSE_LOGGING: try: content = response.content except AttributeError: content = 'UNSUPPORTED_STRING' except (UnsupportedFormat, ValueError): content = 'UNSUPPORTED_FORMAT' else: content = 'HIDDEN' # clean headers from client if settings.FULL_HEADER_LOGGING: cleansed_headers = getattr(request, 'META', {}) cleansed_headers.update( dict( (param, CLEANSED_SUBSTITUTE) for param in SENSITIVE_HEADERS if param in cleansed_headers)) else: cleansed_headers = '' if 'HTTP_X_FORWARDED_FOR' in request.META: ip = request.META['HTTP_X_FORWARDED_FOR'].split(",")[0] else: ip = request.META['REMOTE_ADDR'] logger.info( u"[ACCESS] %(h)s %(l)s user=%(u)s - %(t)s \"%(r)s\" status=%(s)s " u"%(b)s - \"%(f)s\" - \"%(a)s\" - data=%(i)s - headers=%(j)s -" u"content=%(o)s", { 'h': ip, 'l': '-', 'u': credentials, 't': datetime.datetime.now(), 'r': '%s %s' % (request.method, request.get_full_path()), 's': response.status_code, 'b': request.META.get('CONTENT_LENGTH', ''), 'f': request.META.get('HTTP_REFERER', ''), 'a': request.META.get( 'HTTP_USER_AGENT', '').decode('utf-8', 'replace'), 'i': cleansed, 'o': content, 'j': cleansed_headers} ) return response
class ApiTestCase(DirectSEOTestCase): fixtures = ['seo_views_testdata.json'] def setUp(self): super(ApiTestCase, self).setUp() # Create a test user and an API key for that user. self.user, created = User.objects.create_user(email='*****@*****.**', password='******') self.username = self.user.email self.user.save() self.key = ApiKey(user=self.user) self.key.save() self.api_key = self.key.key self.auth_qs = '?&username=%s&api_key=%s' % (self.username, self.api_key) self.entry_1 = SeoSite.objects.get(group=1) self.detail_url = '/api/v1/seosite/{0}/'.format(self.entry_1.pk) self.serializer = Serializer() def deserialize(self, resp): return self.serializer.deserialize(resp.content, format=resp['Content-Type']) def test_not_authorized(self): """ Test if a user can gain access without an API key """ user, created = User.objects.create_user(email='*****@*****.**', password='******') self.username = self.user.email user.save() resp = self.client.get("api/v1/jobsearch/?format=xml") self.assertEqual(resp.status_code, 404) resp = self.client.get("api/v1/seosite/?format=xml") self.assertEqual(resp.status_code, 404) key = ApiKey(user=self.user) def test_list_xml(self): resp = self.client.get("/api/v1/seosite/?%s&format=xml" % (self.auth_qs)) self.assertEqual(resp.status_code, 200) self.serializer.from_xml(resp.content) def test_list_json(self): resp = self.client.get("/api/v1/seosite/?%s&format=json" % (self.auth_qs)) self.assertEqual(len(self.deserialize(resp)['objects']), 1) self.assertEqual(resp.status_code, 200) self.serializer.from_json(resp.content) def test_get_detail_xml(self): resp = self.client.get("/api/v1/seosite/1/%s&format=xml" % (self.auth_qs)) self.assertEqual(resp.status_code, 200) self.serializer.from_xml(resp.content) def test_nopost(self): """ Ensure that POST requests are rejected. This test can be removed if/when we allow other methods besides GET to our resources. """ jobjson = ("""{"buid": 13543, "city": "Chester",\ "company": "Edward Jones", "country": "United States",\ "date_new": "2012-05-31T11:49:23",\ "mocs": "[\'021\', \'0193\', \'2820\', \'2G000\', \'2G091\',\ \'2R000\', \'2R071\', \'2R090\', \'2R171\', \'2S000\',\ \'2S071\', \'2S091\', \'2T000\', \'2T071\', \'2T091\',\ \'3A000\', \'3A071\', \'3A091\', \'3C000\', \'3C071\',\ \'3C090\', \'3C171\', \'3C191\', \'4A000\', \'4A091\',\ \'4A100\', \'4A191\', \'6F000\', \'6F091\', \'8M000\']",\ "onet": "43101100",\ "resource_uri": "/seo/v1/jobposting/29068157/",\ "state": "Virginia", "title": "Branch Office Administrator -\ Chester, VA - Branch 48113", "uid": "29068157"}""") resp = self.client.post("/api/v1/jobsearch/%s" % self.auth_qs, data=jobjson, content_type="application/json") # HTTP 405 == 'Method Not Allowed' self.assertEqual(resp.status_code, 405)
def process_response(self, request, response): if hasattr(request, 'user') and request.user.is_authenticated(): credentials = request.user.pk else: credentials = -1 serializer = Serializer() format = determine_format(request, serializer, default_format='application/json') # clean POST received from client if request.method in ['POST', 'PUT']: try: cleansed = serializer.deserialize(request.body, format=format) except ValueError: cleansed = request.POST.dict() except UnsupportedFormat: cleansed = 'UNSUPPORTED_FORMAT' except AttributeError: cleansed = 'UNSUPPORTED_STRING' except Exception as e: logger.warning(u"[RESPONSE] %(c)s: %(e)s", { 'c': e.__class__, 'e': e }) cleansed = 'STRING' finally: if hasattr(cleansed, 'keys'): cleansed.update( dict((param, CLEANSED_SUBSTITUTE) for param in SENSITIVE_PARAMS if param in cleansed)) else: cleansed = 'STRING' # clean response sent to client if response.content and settings.FULL_RESPONSE_LOGGING: try: content = response.content except AttributeError: content = 'UNSUPPORTED_STRING' except (UnsupportedFormat, ValueError): content = 'UNSUPPORTED_FORMAT' else: content = 'HIDDEN' # clean headers from client if settings.FULL_HEADER_LOGGING: cleansed_headers = getattr(request, 'META', {}) cleansed_headers.update( dict((param, CLEANSED_SUBSTITUTE) for param in SENSITIVE_HEADERS if param in cleansed_headers)) else: cleansed_headers = '' if 'HTTP_X_FORWARDED_FOR' in request.META: ip = request.META['HTTP_X_FORWARDED_FOR'].split(",")[0] else: ip = request.META['REMOTE_ADDR'] logger.info( u"[ACCESS] %(h)s %(l)s user=%(u)s - %(t)s \"%(r)s\" status=%(s)s " u"%(b)s - \"%(f)s\" - \"%(a)s\" - data=%(i)s - headers=%(j)s -" u"content=%(o)s", { 'h': ip, 'l': '-', 'u': credentials, 't': datetime.datetime.now(), 'r': '%s %s' % (request.method, request.get_full_path()), 's': response.status_code, 'b': request.META.get('CONTENT_LENGTH', ''), 'f': request.META.get('HTTP_REFERER', ''), 'a': request.META.get('HTTP_USER_AGENT', '').decode( 'utf-8', 'replace'), 'i': cleansed, 'o': content, 'j': cleansed_headers }) return response
class ResourceTestCase(TestCase): """ A useful base class for the start of testing Tastypie APIs. """ def setUp(self): super(ResourceTestCase, self).setUp() self.serializer = Serializer() self.api_client = TestApiClient() def get_credentials(self): """ A convenience method for the user as a way to shorten up the often repetitious calls to create the same authentication. Raises ``NotImplementedError`` by default. Usage:: class MyResourceTestCase(ResourceTestCase): def get_credentials(self): return self.create_basic('daniel', 'pass') # Then the usual tests... """ raise NotImplementedError( "You must return the class for your Resource to test.") def create_basic(self, username, password): """ Creates & returns the HTTP ``Authorization`` header for use with BASIC Auth. """ import base64 return 'Basic %s' % base64.b64encode(':'.join( [username, password]).encode('utf-8')).decode('utf-8') def create_apikey(self, username, api_key): """ Creates & returns the HTTP ``Authorization`` header for use with ``ApiKeyAuthentication``. """ return 'ApiKey %s:%s' % (username, api_key) def create_digest(self, username, api_key, method, uri): """ Creates & returns the HTTP ``Authorization`` header for use with Digest Auth. """ from tastypie.authentication import hmac, sha1, uuid, python_digest new_uuid = uuid.uuid4() opaque = hmac.new(str(new_uuid).encode('utf-8'), digestmod=sha1).hexdigest().decode('utf-8') return python_digest.build_authorization_request( username, method.upper(), uri, 1, # nonce_count digest_challenge=python_digest.build_digest_challenge( time.time(), getattr(settings, 'SECRET_KEY', ''), 'django-tastypie', opaque, False), password=api_key) def create_oauth(self, user): """ Creates & returns the HTTP ``Authorization`` header for use with Oauth. """ from oauth_provider.models import Consumer, Token, Resource # Necessary setup for ``oauth_provider``. resource, _ = Resource.objects.get_or_create( url='test', defaults={'name': 'Test Resource'}) consumer, _ = Consumer.objects.get_or_create(key='123', defaults={ 'name': 'Test', 'description': 'Testing...' }) token, _ = Token.objects.get_or_create(key='foo', token_type=Token.ACCESS, defaults={ 'consumer': consumer, 'resource': resource, 'secret': '', 'user': user, }) # Then generate the header. oauth_data = { 'oauth_consumer_key': '123', 'oauth_nonce': 'abc', 'oauth_signature': '&', 'oauth_signature_method': 'PLAINTEXT', 'oauth_timestamp': str(int(time.time())), 'oauth_token': 'foo', } return 'OAuth %s' % ','.join( [key + '=' + value for key, value in oauth_data.items()]) def assertHttpOK(self, resp): """ Ensures the response is returning a HTTP 200. """ return self.assertEqual(resp.status_code, 200) def assertHttpCreated(self, resp): """ Ensures the response is returning a HTTP 201. """ return self.assertEqual(resp.status_code, 201) def assertHttpAccepted(self, resp): """ Ensures the response is returning either a HTTP 202 or a HTTP 204. """ self.assertIn(resp.status_code, [202, 204]) self.assertNotIn('Content-Type', resp) def assertHttpMultipleChoices(self, resp): """ Ensures the response is returning a HTTP 300. """ return self.assertEqual(resp.status_code, 300) def assertHttpSeeOther(self, resp): """ Ensures the response is returning a HTTP 303. """ return self.assertEqual(resp.status_code, 303) def assertHttpNotModified(self, resp): """ Ensures the response is returning a HTTP 304. """ return self.assertEqual(resp.status_code, 304) def assertHttpBadRequest(self, resp): """ Ensures the response is returning a HTTP 400. """ return self.assertEqual(resp.status_code, 400) def assertHttpUnauthorized(self, resp): """ Ensures the response is returning a HTTP 401. """ return self.assertEqual(resp.status_code, 401) def assertHttpForbidden(self, resp): """ Ensures the response is returning a HTTP 403. """ return self.assertEqual(resp.status_code, 403) def assertHttpNotFound(self, resp): """ Ensures the response is returning a HTTP 404. """ return self.assertEqual(resp.status_code, 404) def assertHttpMethodNotAllowed(self, resp): """ Ensures the response is returning a HTTP 405. """ return self.assertEqual(resp.status_code, 405) def assertHttpConflict(self, resp): """ Ensures the response is returning a HTTP 409. """ return self.assertEqual(resp.status_code, 409) def assertHttpGone(self, resp): """ Ensures the response is returning a HTTP 410. """ return self.assertEqual(resp.status_code, 410) def assertHttpUnprocessableEntity(self, resp): """ Ensures the response is returning a HTTP 422. """ return self.assertEqual(resp.status_code, 422) def assertHttpTooManyRequests(self, resp): """ Ensures the response is returning a HTTP 429. """ return self.assertEqual(resp.status_code, 429) def assertHttpApplicationError(self, resp): """ Ensures the response is returning a HTTP 500. """ return self.assertEqual(resp.status_code, 500) def assertHttpNotImplemented(self, resp): """ Ensures the response is returning a HTTP 501. """ return self.assertEqual(resp.status_code, 501) def assertValidJSON(self, data): """ Given the provided ``data`` as a string, ensures that it is valid JSON & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_json(data) def assertValidXML(self, data): """ Given the provided ``data`` as a string, ensures that it is valid XML & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_xml(data) def assertValidYAML(self, data): """ Given the provided ``data`` as a string, ensures that it is valid YAML & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_yaml(data) def assertValidPlist(self, data): """ Given the provided ``data`` as a string, ensures that it is valid binary plist & can be loaded properly. """ # Just try the load. If it throws an exception, the test case will fail. self.serializer.from_plist(data) def assertValidJSONResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/json``) * The content is valid JSON """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/json')) self.assertValidJSON(force_text(resp.content)) def assertValidXMLResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/xml``) * The content is valid XML """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/xml')) self.assertValidXML(force_text(resp.content)) def assertValidYAMLResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``text/yaml``) * The content is valid YAML """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('text/yaml')) self.assertValidYAML(force_text(resp.content)) def assertValidPlistResponse(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, assert that you get back: * An HTTP 200 * The correct content-type (``application/x-plist``) * The content is valid binary plist data """ self.assertHttpOK(resp) self.assertTrue(resp['Content-Type'].startswith('application/x-plist')) self.assertValidPlist(force_text(resp.content)) def deserialize(self, resp): """ Given a ``HttpResponse`` coming back from using the ``client``, this method checks the ``Content-Type`` header & attempts to deserialize the data based on that. It returns a Python datastructure (typically a ``dict``) of the serialized data. """ return self.serializer.deserialize(resp.content, format=resp['Content-Type']) def serialize(self, data, format='application/json'): """ Given a Python datastructure (typically a ``dict``) & a desired content-type, this method will return a serialized string of that data. """ return self.serializer.serialize(data, format=format) def assertKeys(self, data, expected): """ This method ensures that the keys of the ``data`` match up to the keys of ``expected``. It covers the (extremely) common case where you want to make sure the keys of a response match up to what is expected. This is typically less fragile than testing the full structure, which can be prone to data changes. """ self.assertEqual(sorted(data.keys()), sorted(expected))
def is_authorized(self, request, object=None): from client.api import EnvironmentResource, AreaResource, AnnotationResource from coresql.models import Environment, Area from coresql.utils import str2bool if hasattr(request, 'user') and not request.user.is_anonymous(): env_obj = None area_obj = None if request.method.upper() == "GET": if 'environment' in request.GET: try: env_obj = Environment.objects.get(pk=request.GET['environment']) except: env_obj = None if 'area' in request.GET: try: area_obj = Area.objects.get(pk=request.GET['area']) except: area_obj = None ''' For GET requests we check if there is a virtual access flag set in the request. If the flag is not set, the default behavior is to assume physical check-in ''' if 'virtual' in request.GET: try: virtual = str2bool(request.GET['virtual']) if virtual and (area_obj or env_obj): ''' if the virtual flag is set to TRUE, then allow access, otherwise, check that the user is actually checked-in where he says he is ''' return True except ValueError: return False elif request.method.upper() == "POST": ''' for the rest of the methods check that the requesting user is actually checked in ''' serdes = Serializer() deserialized = None try: deserialized = serdes.deserialize(request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json')) except Exception: return False if deserialized is None: return False if 'environment' in deserialized: try: #env_pk = int(deserialized['env']) env_obj = EnvironmentResource().get_via_uri(deserialized['environment'], request=request) except: env_obj = None if 'area' in deserialized: try: #area_pk = int(deserialized['area']) area_obj = AreaResource().get_via_uri(deserialized['area'], request=request) except: area_obj = None elif request.method.upper() in ["DELETE", "PUT"]: ann_res_uri = request.path try: ann_obj = AnnotationResource().get_via_uri(ann_res_uri, request=request) env_obj = ann_obj.environment area_obj = ann_obj.area #print "[authorization] env_obj: ", env_obj #print "[authorization] area_obj: ", area_obj except Exception: #print "[authorization] exception in getting annotation resource for deletion: ", ex env_obj = None area_obj = None user_profile = request.user.get_profile() ## will be an instance of UserProfile => available context return is_checked_in(user_profile, env_obj, area_obj) return False