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")
예제 #2
0
    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')
예제 #3
0
    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))
예제 #4
0
파일: api.py 프로젝트: jasonrig/mytardis
    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
예제 #5
0
    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')
예제 #6
0
파일: api.py 프로젝트: TheGoodRob/mytardis
    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)
예제 #8
0
    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"
예제 #9
0
 class Meta(common.ProjectResource.Meta):
     authentication = SessionAuthentication()
예제 #10
0
 class Meta:
     queryset = Season.objects.all()
     authentication = SessionAuthentication()
     authorization = Authorization()
예제 #11
0
 class Meta:
     queryset = Document.objects.all()
     authentication = SessionAuthentication()
     authorization = Authorization()
예제 #12
0
 class Meta:
     queryset = UserProfile.objects.all().prefetch_related()
     resource_name = 'user_prof'
     excludes = ['activation_key']
     authentication = SessionAuthentication()
예제 #13
0
파일: api.py 프로젝트: mohdbakhrayba/prs
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)
예제 #14
0
파일: api.py 프로젝트: chenghz4/driverdata
 class Meta:
     queryset = Query.objects.all()
     authentication = SessionAuthentication()
     authorization = OwnedOnlyAuthorization()
예제 #15
0
 class Meta:
     queryset = Location.objects.all().select_related()
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
예제 #16
0
파일: api.py 프로젝트: chenghz4/driverdata
 class Meta:
     authentication = SessionAuthentication()
     authorization = Authorization()
예제 #17
0
파일: api.py 프로젝트: chenghz4/driverdata
 class Meta:
     exclude = ['indexed']
     queryset = CensusField.objects.all()
     allowed_methods = ['get']
     authentication = SessionAuthentication()
예제 #18
0
파일: api.py 프로젝트: chenghz4/driverdata
 class Meta:
     queryset = Account.objects.all()
     authentication = SessionAuthentication()
     authorization = SelfOnlyAuthorization()
예제 #19
0
파일: api.py 프로젝트: chenghz4/driverdata
 class Meta:
     queryset = QueryFilter.objects.all()
     authentication = SessionAuthentication()
     authorization = OwnedOnlyAuthorization()
     validation = QueryFilterValidation()
예제 #20
0
 class Meta(CommonMetaApi):
     queryset = Map.objects.distinct().order_by('-date')
     resource_name = 'maps'
     authentication = MultiAuthentication(SessionAuthentication(),
                                          GeonodeApiKeyAuthentication())
예제 #21
0
 class Meta(CommonMetaApi):
     queryset = ResourceBase.objects.filter(featured=True).order_by('-date')
     resource_name = 'featured'
     authentication = MultiAuthentication(SessionAuthentication(),
                                          GeonodeApiKeyAuthentication())
예제 #22
0
 class Meta:
     queryset = AppList.objects.all()
     allowed_methods = ['get',]
     authentication = SessionAuthentication()
     authorization = DjangoAuthorization()
예제 #23
0
 class Meta:
     queryset = Season.objects.all().prefetch_related()
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     always_return_data = True
예제 #24
0
 class Meta:
     queryset = RaceClass.objects.all().select_related()
     resource_name = 'raceclass'
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     always_return_data = True
예제 #25
0
 class Meta:
     queryset = Coupon.objects.all().select_related()
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     always_return_data = True
예제 #26
0
 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']
예제 #27
0
파일: api.py 프로젝트: ojengwa/apipanda
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)
예제 #28
0
 class Meta:
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     queryset = Run.objects.all()
예제 #29
0
 class Meta(common.GraphResource.Meta):
     authentication = SessionAuthentication()
     serializer = GraphSerializer()
     nodes = fields.ToManyField(NodeResource, 'nodes')
     edges = fields.ToManyField(EdgeResource, 'edges')
예제 #30
0
 class Meta:
     queryset = Result.objects.all()
     authorization = GraphOwnerAuthorization()
     authentication = SessionAuthentication()
     list_allowed_methods = ['get']
예제 #31
0
 class Meta:
     queryset = Festival.objects.all()
     authentication = SessionAuthentication()
     authorization = Authorization()
예제 #32
0
 class Meta:
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     queryset = Registration.objects.all().select_related()
     excludes = ['_anon_l_name', '_anon_f_name', '_anon_car']
예제 #33
0
 class Meta:
     queryset = Minutes.objects.all()
     authentication = SessionAuthentication()
     authorization = Authorization()
예제 #34
0
 class Meta:
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     queryset = Event.objects.all().select_related()
     resource_name = "event"
예제 #35
0
 class Meta:
     queryset = Notification.objects.all()
     detail_allowed_methods = ['delete']
     authentication = SessionAuthentication()
     authorization = Authorization()
예제 #36
0
 class Meta:
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     queryset = Session.objects.all()
     resource_name = "sessions"
예제 #37
0
 class Meta:
     authentication = SessionAuthentication()
     authorization = ClubAdminAuthorization()
     queryset = Result.objects.all().prefetch_related()
     include_resource_uri = False
예제 #38
0
 class Meta:
     queryset = Job.objects.all()
     authorization = GraphOwnerAuthorization()
     authentication = SessionAuthentication()
     list_allowed_methods = ['post']
     detail_allowed_methods = ['get']