def test_check_active_false(self):
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        create_api_key(User, instance=bob_doe, created=True)
        request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_key.key
        self.assertTrue(auth.is_authenticated(request))
    def test_check_active_false(self):
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        create_api_key(User, instance=bob_doe, created=True)
        request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_key.key
        self.assertTrue(auth.is_authenticated(request))
    def test_check_active_false(self):
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        bob_doe.set_password('pass')
        bob_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('bobdoe:pass'.encode('utf-8')).decode('utf-8')
        self.assertTrue(auth.is_authenticated(request))
Example #4
0
    def test_check_active_false(self):
        user_class = get_user_model()
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = user_class.objects.get(**{user_class.USERNAME_FIELD: 'bobdoe'})
        create_api_key(User, instance=bob_doe, created=True)
        request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_key.key
        self.assertTrue(auth.is_authenticated(request))
    def test_check_active_false(self):
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        bob_doe.set_password('pass')
        bob_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('bobdoe:pass'.encode('utf-8')).decode('utf-8')
        self.assertTrue(auth.is_authenticated(request))
Example #6
0
    def test_check_active_true(self):
        auth = BasicAuthentication()
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        bob_doe.set_password('pass')
        bob_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('bobdoe:pass'.encode('utf-8')).decode('utf-8')
        auth_res = auth.is_authenticated(request)
        # is_authenticated() returns HttpUnauthorized for inactive users in Django >= 1.10, False for < 1.10
        self.assertTrue(auth_res is False or isinstance(auth_res, HttpUnauthorized))
Example #7
0
    def test_check_active_false(self):
        if django.VERSION >= (1, 10):
            # Authenticating inactive users via ModelUserBackend not supported for Django >= 1.10"
            return
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        create_api_key(User, instance=bob_doe, created=True)
        request.META['HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_key.key
        self.assertTrue(auth.is_authenticated(request))
Example #8
0
    def test_check_active_true(self):
        auth = BasicAuthentication()
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        bob_doe.set_password('pass')
        bob_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('bobdoe:pass')
        auth_res = auth.is_authenticated(request)
        # is_authenticated() returns HttpUnauthorized for inactive users in Django >= 1.10, False for < 1.10
        self.assertTrue(auth_res is False or isinstance(auth_res, HttpUnauthorized))
Example #9
0
    def test_check_active_false(self):
        user_class = get_user_model()
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = user_class.objects.get(
            **{user_class.USERNAME_FIELD: 'bobdoe'})
        create_api_key(User, instance=bob_doe, created=True)
        request.META[
            'HTTP_AUTHORIZATION'] = 'ApiKey bobdoe:%s' % bob_doe.api_key.key
        self.assertTrue(auth.is_authenticated(request))
Example #10
0
    def test_check_active_false(self):
        if django.VERSION >= (1, 10):
            # Authenticating inactive users via ModelUserBackend not supported for Django >= 1.10"
            return
        auth = BasicAuthentication(require_active=False)
        request = HttpRequest()

        bob_doe = User.objects.get(username='******')
        bob_doe.set_password('pass')
        bob_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('bobdoe:pass')
        self.assertTrue(auth.is_authenticated(request))
Example #11
0
    def test_is_authenticated(self):
        auth = BasicAuthentication()
        request = HttpRequest()

        # No HTTP Basic auth details should fail.
        self.assertEqual(
            isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # HttpUnauthorized with auth type and realm
        self.assertEqual(
            auth.is_authenticated(request)['WWW-Authenticate'],
            'Basic Realm="django-tastypie"')

        # Wrong basic auth details.
        request.META['HTTP_AUTHORIZATION'] = 'abcdefg'
        self.assertEqual(
            isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # No password.
        request.META['HTTP_AUTHORIZATION'] = base64.b64encode(
            'daniel'.encode('utf-8')).decode('utf-8')
        self.assertEqual(
            isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong user/password.
        request.META['HTTP_AUTHORIZATION'] = base64.b64encode(
            'daniel:pass'.encode('utf-8')).decode('utf-8')
        self.assertEqual(
            isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Correct user/password.
        john_doe = User.objects.get(username='******')
        john_doe.set_password('pass')
        john_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode(
            'johndoe:pass'.encode('utf-8')).decode('utf-8')
        self.assertEqual(auth.is_authenticated(request), True)

        # Regression: Password with colon.
        john_doe = User.objects.get(username='******')
        john_doe.set_password('pass:word')
        john_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode(
            'johndoe:pass:word'.encode('utf-8')).decode('utf-8')
        self.assertEqual(auth.is_authenticated(request), True)

        # Capitalization shouldn't matter.
        john_doe = User.objects.get(username='******')
        john_doe.set_password('pass:word')
        john_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'bAsIc %s' % base64.b64encode(
            'johndoe:pass:word'.encode('utf-8')).decode('utf-8')
        self.assertEqual(auth.is_authenticated(request), True)
    def test_is_authenticated(self):
        auth = BasicAuthentication()
        request = HttpRequest()

        # No HTTP Basic auth details should fail.
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # HttpUnauthorized with auth type and realm
        self.assertEqual(auth.is_authenticated(request)['WWW-Authenticate'], 'Basic Realm="django-tastypie"')

        # Wrong basic auth details.
        request.META['HTTP_AUTHORIZATION'] = 'abcdefg'
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # No password.
        request.META['HTTP_AUTHORIZATION'] = base64.b64encode('daniel')
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong user/password.
        request.META['HTTP_AUTHORIZATION'] = base64.b64encode('daniel:pass')
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Correct user/password.
        john_doe = User.objects.get(username='******')
        john_doe.set_password('pass')
        john_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('johndoe:pass')
        self.assertEqual(auth.is_authenticated(request), True)

        # Regression: Password with colon.
        john_doe = User.objects.get(username='******')
        john_doe.set_password('pass:word')
        john_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('johndoe:pass:word')
        self.assertEqual(auth.is_authenticated(request), True)
Example #13
0
def api_user_follow(request):
    if request.method == 'POST':
        basic_auth = BasicAuthentication()
        if basic_auth.is_authenticated(request):
            to_user_id = int(request.POST.get("to_user", 0))
            try:
                to_user = User.objects.get(id=to_user_id)
            except User.DoesNotExist:
                raise Http404
            from_user = request.user
            from_user.relationships.add(to_user)

            response_data={'status':'success'}
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
    raise Http404
Example #14
0
 class Meta:
     queryset = Device.objects.all().distinct().order_by('-created_date')
     resource_name = 'devices'
     authentication = BasicAuthentication()
     authorization = DjangoAuthorization()
     include_resource_uri = False
     allowed_methods = ['get', 'post', 'put']
Example #15
0
 class Meta:
     authorization = Authorization()
     authentication = MultiAuthentication(BasicAuthentication(),
                                          SessionAuthentication())
     allowed_methods = ['get']
     resource_name = 'cypher'
     object_class = object
Example #16
0
 class Meta:
     resource_name = 'project'
     default_format = 'application/json'
     queryset = Project.objects.all()
     authentication = BasicAuthentication()
     authorization = GuardianAuthorization()
     abstract = True
Example #17
0
    class Meta:
        queryset = Medico.objects.all()
        resource_name = 'medico'

        autentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        fields = ['cedula', 'nombre']
Example #18
0
 class Meta:
     queryset = Profile.objects.all()
     resource_name = 'user'
     excludes = ['email', 'password', 'is_superuser']
     # Add it here.
     authentication = BasicAuthentication()
     authorization = DjangoAuthorization()
Example #19
0
    def test_multiauth_apikey_and_basic_auth__no_details_fails(self):
        auth = MultiAuthentication(BasicAuthentication(),
                                   ApiKeyAuthentication())
        request = HttpRequest()

        self.assertEqual(
            isinstance(auth.is_authenticated(request), HttpUnauthorized), True)
Example #20
0
 class Meta:
     object_class = Member
     queryset = Member.objects.all()
     resource_name = 'members'
     allowed_methods = ['get', 'post', 'put', 'delete']
     excludes = ['member_photo']
     authentication = BasicAuthentication()
Example #21
0
 class Meta:
     queryset = VersionedApp.objects.all()
     resource_name = 'versioned_app'
     filtering = {'name': ALL}
     authentication = MultiAuthentication(BasicAuthentication(),
                                          ApiKeyAuthentication())
     authorization = DjangoAuthorization()
Example #22
0
 class Meta:
     queryset = Luggage.objects.all()
     allowed_methods = ['get', 'post']
     authentication = MultiAuthentication(BasicAuthentication(),
                                          ApiKeyAuthentication())
     authorization = Authorization()
     filtering = {'passenger': ALL}
Example #23
0
 class Meta:
     include_resource_uri = False
     authentication = MultiAuthentication(SessionAuthentication(),
                                          BasicAuthentication())
     list_allowed_methods = ['get']
     detail_allowed_methods = []
     resource_name = 'data/balance'
Example #24
0
 class Meta:
     resource_name = 'cdr'
     authorization = Authorization()
     authentication = BasicAuthentication()
     allowed_methods = ['post']
     throttle = BaseThrottle(throttle_at=1000,
                             timeframe=3600)  # default 1000 calls / hour
Example #25
0
 class Meta:
     queryset = User.objects.all()
     resource_name = 'user'
     excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
     allowed_methods = ['get', ]
     authentication = BasicAuthentication()
     authorization = DjangoAuthorization()
Example #26
0
 class Meta:
     queryset = EmailSubscriber.objects.all()
     filtering = {
         'email': ALL,
         'event': ALL_WITH_RELATIONS,
     }
     authentication = BasicAuthentication()
Example #27
0
 class Meta:
     queryset = Project.objects.all()
     resource_name = 'projects'
     list_allowed_methods = ['get', 'post']
     detail_allowed_methods = ['get', 'put', 'delete', 'patch']
     authorization = DjangoAuthorization()
     authentication = BasicAuthentication()
 class Meta:
     queryset = Node.objects.all()
     resource_name = 'node'
     allowed_methods = ['get']
     authentication = BasicAuthentication()
     authorization = DjangoAuthorization()
     always_return_data = True
    def test_apikey_and_basic_auth(self):
        auth = MultiAuthentication(BasicAuthentication(),
                                   ApiKeyAuthentication())
        request = HttpRequest()
        john_doe = User.objects.get(username='******')

        # No API Key or HTTP Basic auth details should fail.
        self.assertEqual(
            isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Basic Auth still returns appropriately.
        self.assertEqual(
            auth.is_authenticated(request)['WWW-Authenticate'],
            'Basic Realm="django-tastypie"')

        # API Key Auth works.
        request = HttpRequest()
        request.GET['username'] = '******'
        request.GET['api_key'] = john_doe.api_key.key
        self.assertEqual(auth.is_authenticated(request), True)
        self.assertEqual(auth.get_identifier(request), 'johndoe')

        # Basic Auth works.
        request = HttpRequest()
        john_doe = User.objects.get(username='******')
        john_doe.set_password('pass')
        john_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode(
            'johndoe:pass'.encode('utf-8')).decode('utf-8')
        self.assertEqual(auth.is_authenticated(request), True)
Example #30
0
 class Meta:
     queryset = Category.objects.all()
     authorization = DjangoAuthorization()
     authentication = BasicAuthentication()
     allowed_methods = ['get', 'post', 'put', 'delete']
     detail_allowed_methods = ['get', 'post', 'put', 'delete']
     filtering = {'id': ALL, 'username': ALL_WITH_RELATIONS}
Example #31
0
 class Meta:
     queryset = Book.objects.all()
     resource_name = 'book'
     filtering = {'title': ALL}
     authentication = BasicAuthentication()
     authorization = DjangoAuthorization()
     always_return_data = True
Example #32
0
 class Meta:
     queryset = User.objects.all()
     fields = ["first_name", "last_name", "username",]
     allowed_method = ['get']
     resource_name = 'login'
     authorization = DjangoAuthorization()
     authentication = BasicAuthentication()
Example #33
0
 class Meta:
     queryset = User.objects.all()
     resource_name = 'users'
     allowed_methods = ['get', 'post', 'delete', 'put', 'options']
     authorization = Authorization()
     authentication = MultiAuthentication(
         ApiKeyAuthentication(),
         BasicAuthentication(),
     )
     collection_name = 'users'
     detail_uri_name = 'username'
     fields = (
         'username',
         'id',
         'full_name',
         'first_name',
         'last_name',
         'third_name',
         'position',
         'avatar',
         'is_staff',
         'email',
     )
     filtering = {
         'id': (
             'exact',
             'ne',
         ),
     }
Example #34
0
 class Meta:
     queryset = User.objects.all()
     resource_name = "user"
     excludes = ["email", "password", "is_active", "is_staff", "is_superuser"]
     allowed_methods = ["get"]
     authorization = DjangoAuthorization()
     authentication = BasicAuthentication()
Example #35
0
 class Meta:
     queryset = Storage.objects.all()
     resource_name = 'storage'
     allowed_methods = ['get']
     authentication = BasicAuthentication()
     detail_uri_name = 'name'
     collection_name = 'results'
 class Meta:
     queryset = Transaction.objects.all()
     resource_name = 'transaction'
     allowed_methods = ['get', 'post']
     authentication = BasicAuthentication()
     authorization = DjangoAuthorization()
     always_return_data = True
Example #37
0
    def test_whitelisting(self):
        auth = BasicAuthentication(whitelisted_methods=['a_method'])
        request = HttpRequest()

        # Calling with a whitelisted method_name without credentials should work
        self.assertEqual(auth.is_authenticated(request, method_name='a_method'), True)
        
        # Calling any other method should require auth
        self.assertEqual(isinstance(auth.is_authenticated(request, method_name='another_method'), HttpUnauthorized), True)

        # Correct user/password.
        john_doe = User.objects.get(username='******')
        john_doe.set_password('pass')
        john_doe.save()
        request.META['HTTP_AUTHORIZATION'] = 'Basic %s' % base64.b64encode('johndoe:pass')
        self.assertEqual(auth.is_authenticated(request, method_name="another_method"), True)
        self.assertEqual(auth.is_authenticated(request, method_name="a_method"), True)
    def test_is_authenticated(self):
        auth = BasicAuthentication()
        request = HttpRequest()

        # No HTTP Basic auth details should fail.
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # HttpUnauthorized with auth type and realm
        self.assertEqual(auth.is_authenticated(request)["WWW-Authenticate"], 'Basic Realm="django-tastypie"')

        # Wrong basic auth details.
        request.META["HTTP_AUTHORIZATION"] = "abcdefg"
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # No password.
        request.META["HTTP_AUTHORIZATION"] = base64.b64encode("daniel")
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Wrong user/password.
        request.META["HTTP_AUTHORIZATION"] = base64.b64encode("daniel:pass")
        self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True)

        # Correct user/password.
        john_doe = User.objects.get(username="******")
        john_doe.set_password("pass")
        john_doe.save()
        request.META["HTTP_AUTHORIZATION"] = "Basic %s" % base64.b64encode("johndoe:pass")
        self.assertEqual(auth.is_authenticated(request), True)
Example #39
0
def api_upload_photo(request):
    if request.method == 'POST':
        basic_auth = BasicAuthentication()
        if basic_auth.is_authenticated(request):
            photo = Photo(user=request.user, title=request.POST.get('title', None), file=request.FILES['file'])
            photo.save()

            at_users = request.POST.get('atusers', '').split(',')
            for user_id in at_users:
                try:
                    to_user = User.objects.get(id=int(user_id))
                    message = Message(from_user=request.user, to_user=to_user, description=get_photo_info(photo)).save()
                except Exception:
                    pass

            # TODO the api resource_uri need to dynamic
            response_data={"resource_uri": "/api/v1/photo/%d/" % (photo.id) , "file_url": photo.file.url}
            return HttpResponse(simplejson.dumps(response_data), mimetype='application/json')
    raise Http404
Example #40
0
    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
Example #41
0
    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)
Example #42
0
class Authentication(ApiKeyAuthentication):
    def __init__(self):
        self.api_key_auth = ApiKeyAuthentication()
        self.basic_auth = BasicAuthentication(backend=ApiKeyBackend())

    def is_authenticated(self, request, **kwargs):
        if request.user.is_authenticated():
            return True
        ret = self.basic_auth.is_authenticated(request, **kwargs)
        if isinstance(ret, HttpUnauthorized):
            ret2 = self.api_key_auth.is_authenticated(request, **kwargs)
            if not isinstance(ret2, HttpUnauthorized):
                return ret2
        return ret

    def get_identifier(self, request):
        if request.user.is_authenticated():
            return request.user.username
        ret = self.basic_auth.get_identifier(request)
        if isinstance(ret, HttpUnauthorized):
            ret2 = self.api_key_auth.get_identifier(request)
            if not isinstance(ret2, HttpUnauthorized):
                return ret2
        return ret
Example #43
0
 def __init__(self):
     self.api_key_auth = ApiKeyAuthentication()
     self.basic_auth = BasicAuthentication(backend=ApiKeyBackend())