def test_apikey_and_authentication_enforce_user(self): session_auth = SessionAuthentication() api_key_auth = ApiKeyAuthentication() auth = MultiAuthentication(api_key_auth, session_auth) john_doe = User.objects.get(username="******") request1 = HttpRequest() request2 = HttpRequest() request3 = HttpRequest() request1.method = "POST" request1.META = {"HTTP_X_CSRFTOKEN": "abcdef1234567890abcdef1234567890"} request1.COOKIES = {settings.CSRF_COOKIE_NAME: "abcdef1234567890abcdef1234567890"} request1.user = john_doe request2.POST["username"] = "******" request2.POST["api_key"] = "invalid key" request3.method = "POST" request3.META = {"HTTP_X_CSRFTOKEN": "abcdef1234567890abcdef1234567890"} request3.COOKIES = {settings.CSRF_COOKIE_NAME: "abcdef1234567890abcdef1234567890"} request3.user = john_doe request3.POST["username"] = "******" request3.POST["api_key"] = "invalid key" # session auth should pass if since john_doe is logged in self.assertEqual(session_auth.is_authenticated(request1), True) # api key auth should fail because of invalid api key self.assertEqual(isinstance(api_key_auth.is_authenticated(request2), HttpUnauthorized), True) # multi auth shouldn't change users if api key auth fails # multi auth passes since session auth is valid self.assertEqual(request3.user.username, "johndoe") self.assertEqual(auth.is_authenticated(request3), True) self.assertEqual(request3.user.username, "johndoe")
def test_get_identifier(self): auth = SessionAuthentication() request = HttpRequest() # Not logged in. request.user = AnonymousUser() self.assertEqual(auth.get_identifier(request), '') # Logged in. request.user = User.objects.get(username='******') self.assertEqual(auth.get_identifier(request), 'johndoe')
def test_is_authenticated(self): auth = SessionAuthentication() request = HttpRequest() request.method = 'POST' request.COOKIES = { settings.CSRF_COOKIE_NAME: 'abcdef1234567890abcdef1234567890' } # No CSRF token. request.META = {} self.assertFalse(auth.is_authenticated(request)) # Invalid CSRF token. request.META = { 'HTTP_X_CSRFTOKEN': 'abc123' } self.assertFalse(auth.is_authenticated(request)) # Not logged in. request.META = { 'HTTP_X_CSRFTOKEN': 'abcdef1234567890abcdef1234567890' } request.user = AnonymousUser() self.assertFalse(auth.is_authenticated(request)) # Logged in. request.user = User.objects.get(username='******') self.assertTrue(auth.is_authenticated(request)) # Logged in (with GET & no token). request.method = 'GET' request.META = {} request.user = User.objects.get(username='******') self.assertTrue(auth.is_authenticated(request)) # Secure & wrong referrer. class SecureRequest(HttpRequest): def _get_scheme(self): return 'https' request = SecureRequest() request.method = 'POST' request.COOKIES = { settings.CSRF_COOKIE_NAME: 'abcdef1234567890abcdef1234567890' } request.META = { 'HTTP_X_CSRFTOKEN': 'abcdef1234567890abcdef1234567890' } request.META['HTTP_HOST'] = 'example.com' request.META['HTTP_REFERER'] = '' request.user = User.objects.get(username='******') self.assertFalse(auth.is_authenticated(request)) # Secure & correct referrer. request.META['HTTP_REFERER'] = 'https://example.com/' self.assertTrue(auth.is_authenticated(request))
def is_authenticated(self, request, **kwargs): # noqa # too complex ''' handles backends explicitly so that it can return False when credentials are given but wrong and return Anonymous User when credentials are not given or the session has expired (web use). ''' auth_info = request.META.get('HTTP_AUTHORIZATION') if 'HTTP_AUTHORIZATION' not in request.META: if hasattr(request.user, 'allowed_tokens'): tokens = request.user.allowed_tokens session_auth = SessionAuthentication() check = session_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): session_auth_result = False else: request._authentication_backend = session_auth session_auth_result = check else: request.user = AnonymousUser() session_auth_result = True request.user.allowed_tokens = tokens return session_auth_result else: if auth_info.startswith('Basic'): basic_auth = BasicAuthentication() check = basic_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): return False else: request._authentication_backend = basic_auth return check if auth_info.startswith('ApiKey'): apikey_auth = ApiKeyAuthentication() check = apikey_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): return False else: request._authentication_backend = apikey_auth return check
def test_apikey_and_authentication_enforce_user(self): session_auth = SessionAuthentication() api_key_auth = ApiKeyAuthentication() auth = MultiAuthentication(api_key_auth, session_auth) john_doe = User.objects.get(username='******') request1 = HttpRequest() request2 = HttpRequest() request3 = HttpRequest() request1.method = 'POST' request1.META = { 'HTTP_X_CSRFTOKEN': 'abcdef1234567890abcdef1234567890' } request1.COOKIES = { settings.CSRF_COOKIE_NAME: 'abcdef1234567890abcdef1234567890' } request1.user = john_doe request2.POST['username'] = '******' request2.POST['api_key'] = 'invalid key' request3.method = 'POST' request3.META = { 'HTTP_X_CSRFTOKEN': 'abcdef1234567890abcdef1234567890' } request3.COOKIES = { settings.CSRF_COOKIE_NAME: 'abcdef1234567890abcdef1234567890' } request3.user = john_doe request3.POST['username'] = '******' request3.POST['api_key'] = 'invalid key' #session auth should pass if since john_doe is logged in self.assertTrue(session_auth.is_authenticated(request1)) #api key auth should fail because of invalid api key self.assertEqual(isinstance(api_key_auth.is_authenticated(request2), HttpUnauthorized), True) #multi auth shouldn't change users if api key auth fails #multi auth passes since session auth is valid self.assertEqual(request3.user.username, 'johndoe') self.assertTrue(auth.is_authenticated(request3)) self.assertEqual(request3.user.username, 'johndoe')
def is_authenticated(self, request, **kwargs): ''' handles backends explicitly so that it can return False when credentials are given but wrong and return Anonymous User when credentials are not given or the session has expired (web use). ''' auth_info = request.META.get('HTTP_AUTHORIZATION') if 'HTTP_AUTHORIZATION' not in request.META: session_auth = SessionAuthentication() check = session_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): return(False) else: request._authentication_backend = session_auth return(check) else: request.user = AnonymousUser() return(True) else: if auth_info.startswith('Basic'): basic_auth = BasicAuthentication() check = basic_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): return(False) else: request._authentication_backend = basic_auth return(check) if auth_info.startswith('ApiKey'): apikey_auth = ApiKeyAuthentication() check = apikey_auth.is_authenticated(request, **kwargs) if check: if isinstance(check, HttpUnauthorized): return(False) else: request._authentication_backend = apikey_auth return(check)
def test_is_authenticated(self): auth = SessionAuthentication() request = HttpRequest() request.method = "POST" request.COOKIES = {settings.CSRF_COOKIE_NAME: "abcdef1234567890abcdef1234567890"} # No CSRF token. request.META = {} self.assertFalse(auth.is_authenticated(request)) # Invalid CSRF token. request.META = {"HTTP_X_CSRFTOKEN": "abc123"} self.assertFalse(auth.is_authenticated(request)) # Not logged in. request.META = {"HTTP_X_CSRFTOKEN": "abcdef1234567890abcdef1234567890"} request.user = AnonymousUser() self.assertFalse(auth.is_authenticated(request)) # Logged in. request.user = User.objects.get(username="******") self.assertEqual(auth.is_authenticated(request), True) # Logged in (with GET & no token). request.method = "GET" request.META = {} request.user = User.objects.get(username="******") self.assertEqual(auth.is_authenticated(request), True) # Secure & wrong referrer. class SecureRequest(HttpRequest): def _get_scheme(self): return "https" request = SecureRequest() request.method = "POST" request.COOKIES = {settings.CSRF_COOKIE_NAME: "abcdef1234567890abcdef1234567890"} request.META = {"HTTP_X_CSRFTOKEN": "abcdef1234567890abcdef1234567890"} request.META["HTTP_HOST"] = "example.com" request.META["HTTP_REFERER"] = "" request.user = User.objects.get(username="******") self.assertFalse(auth.is_authenticated(request)) # Secure & correct referrer. request.META["HTTP_REFERER"] = "https://example.com/" self.assertEqual(auth.is_authenticated(request), True)
def test_is_authenticated(self): auth = SessionAuthentication() request = HttpRequest() request.COOKIES = { settings.CSRF_COOKIE_NAME: 'abcdef1234567890abcdef1234567890' } # No CSRF token. request.META = {} self.assertFalse(auth.is_authenticated(request)) # Invalid CSRF token. request.META = { 'HTTP_X_CSRFTOKEN': 'abc123' } self.assertFalse(auth.is_authenticated(request)) # Not logged in. request.META = { 'HTTP_X_CSRFTOKEN': 'abcdef1234567890abcdef1234567890' } request.user = AnonymousUser() self.assertFalse(auth.is_authenticated(request)) # Logged in. request.user = User.objects.get(username='******') self.assertTrue(auth.is_authenticated(request)) # Secure & wrong referrer. os.environ["HTTPS"] = "on" request.META['HTTP_HOST'] = 'example.com' request.META['HTTP_REFERER'] = '' self.assertFalse(auth.is_authenticated(request)) # Secure & correct referrer. request.META['HTTP_REFERER'] = 'https://example.com/' self.assertTrue(auth.is_authenticated(request)) os.environ["HTTPS"] = "off"
class Meta(common.ProjectResource.Meta): authentication = SessionAuthentication()
class Meta: queryset = Season.objects.all() authentication = SessionAuthentication() authorization = Authorization()
class Meta: queryset = Document.objects.all() authentication = SessionAuthentication() authorization = Authorization()
class Meta: queryset = UserProfile.objects.all().prefetch_related() resource_name = 'user_prof' excludes = ['activation_key'] authentication = SessionAuthentication()
def generate_meta(klass, overrides={}): """Utility function to generate a standard ModelResource Meta class. """ metaitems = { 'authentication': MultiAuthentication(ApiKeyAuthentication(), BasicAuthentication(), SessionAuthentication()), 'queryset': klass.objects.all(), 'resource_name': klass._meta.model_name, 'filtering': generate_filtering(klass), 'cache': SimpleCache(), 'allowed_methods': ['get'], } metaitems.update(overrides) return type('Meta', (object,), metaitems)
class Meta: queryset = Query.objects.all() authentication = SessionAuthentication() authorization = OwnedOnlyAuthorization()
class Meta: queryset = Location.objects.all().select_related() authentication = SessionAuthentication() authorization = ClubAdminAuthorization()
class Meta: authentication = SessionAuthentication() authorization = Authorization()
class Meta: exclude = ['indexed'] queryset = CensusField.objects.all() allowed_methods = ['get'] authentication = SessionAuthentication()
class Meta: queryset = Account.objects.all() authentication = SessionAuthentication() authorization = SelfOnlyAuthorization()
class Meta: queryset = QueryFilter.objects.all() authentication = SessionAuthentication() authorization = OwnedOnlyAuthorization() validation = QueryFilterValidation()
class Meta(CommonMetaApi): queryset = Map.objects.distinct().order_by('-date') resource_name = 'maps' authentication = MultiAuthentication(SessionAuthentication(), GeonodeApiKeyAuthentication())
class Meta(CommonMetaApi): queryset = ResourceBase.objects.filter(featured=True).order_by('-date') resource_name = 'featured' authentication = MultiAuthentication(SessionAuthentication(), GeonodeApiKeyAuthentication())
class Meta: queryset = AppList.objects.all() allowed_methods = ['get',] authentication = SessionAuthentication() authorization = DjangoAuthorization()
class Meta: queryset = Season.objects.all().prefetch_related() authentication = SessionAuthentication() authorization = ClubAdminAuthorization() always_return_data = True
class Meta: queryset = RaceClass.objects.all().select_related() resource_name = 'raceclass' authentication = SessionAuthentication() authorization = ClubAdminAuthorization() always_return_data = True
class Meta: queryset = Coupon.objects.all().select_related() authentication = SessionAuthentication() authorization = ClubAdminAuthorization() always_return_data = True
class Meta: queryset = Membership.objects.all().select_related() authentication = SessionAuthentication() #authorization = IsOwnerAuthorization() #TODO: Need to add permissions authorization = ClubAdminAuthorization() excludes = ['_anon_f_name', '_anon_l_name']
from tastypie.authorization import DjangoAuthorization from tastypie.authentication import (SessionAuthentication, MultiAuthentication, ApiKeyAuthentication) from app.models import Billing from app.exceptions import CustomBadRequest from workspace.models import (Organisation, Workspace, Invitation) try: import json except Exception: import simplejson as json Authentication = MultiAuthentication( ApiKeyAuthentication(), SessionAuthentication(), ) class Resource(ModelResource): """docstring for Resource""" class Meta: always_return_data = True allowed_methods = ['get', 'post', 'put', 'patch', 'options', 'head'] authentication = Authentication authorization = DjangoAuthorization() validation = Validation() collection_name = 'data' cache = SimpleCache(timeout=10)
class Meta: authentication = SessionAuthentication() authorization = ClubAdminAuthorization() queryset = Run.objects.all()
class Meta(common.GraphResource.Meta): authentication = SessionAuthentication() serializer = GraphSerializer() nodes = fields.ToManyField(NodeResource, 'nodes') edges = fields.ToManyField(EdgeResource, 'edges')
class Meta: queryset = Result.objects.all() authorization = GraphOwnerAuthorization() authentication = SessionAuthentication() list_allowed_methods = ['get']
class Meta: queryset = Festival.objects.all() authentication = SessionAuthentication() authorization = Authorization()
class Meta: authentication = SessionAuthentication() authorization = ClubAdminAuthorization() queryset = Registration.objects.all().select_related() excludes = ['_anon_l_name', '_anon_f_name', '_anon_car']
class Meta: queryset = Minutes.objects.all() authentication = SessionAuthentication() authorization = Authorization()
class Meta: authentication = SessionAuthentication() authorization = ClubAdminAuthorization() queryset = Event.objects.all().select_related() resource_name = "event"
class Meta: queryset = Notification.objects.all() detail_allowed_methods = ['delete'] authentication = SessionAuthentication() authorization = Authorization()
class Meta: authentication = SessionAuthentication() authorization = ClubAdminAuthorization() queryset = Session.objects.all() resource_name = "sessions"
class Meta: authentication = SessionAuthentication() authorization = ClubAdminAuthorization() queryset = Result.objects.all().prefetch_related() include_resource_uri = False
class Meta: queryset = Job.objects.all() authorization = GraphOwnerAuthorization() authentication = SessionAuthentication() list_allowed_methods = ['post'] detail_allowed_methods = ['get']