def test_is_authenticated_header(self): user_class = get_user_model() auth = ApiKeyAuthentication() request = HttpRequest() # Simulate sending the signal. john_doe = user_class.objects.get(**{user_class.USERNAME_FIELD: 'johndoe'}) create_api_key(User, instance=john_doe, created=True) # No username/api_key details should fail. self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong username details. request.META['HTTP_AUTHORIZATION'] = 'foo' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # No api_key. request.META['HTTP_AUTHORIZATION'] = 'ApiKey daniel' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong user/api_key. request.META['HTTP_AUTHORIZATION'] = 'ApiKey daniel:pass' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Correct user/api_key. john_doe = user_class.objects.get(**{user_class.USERNAME_FIELD: 'johndoe'}) request.META['HTTP_AUTHORIZATION'] = 'ApiKey johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True) # Capitalization shouldn't matter. john_doe = user_class.objects.get(**{user_class.USERNAME_FIELD: 'johndoe'}) request.META['HTTP_AUTHORIZATION'] = 'aPiKeY johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True)
def is_authenticated(self, request, **kwargs): """ Finds the user and checks their API key. Should return either ``True`` if allowed, ``False`` if not or an ``HttpResponse`` if you need something custom. """ from myproject.utils import get_user_from_user_or_detail user_class = get_user_model() try: unique_field, api_key = self.extract_credentials(request) except ValueError: return self._unauthorized() if not unique_field or not api_key: return self._unauthorized() user = get_user_from_user_or_detail(unique_field) if not user: return self._unauthorized() key_auth_check = self.get_key(user, api_key) if key_auth_check and not isinstance(key_auth_check, HttpUnauthorized): request.user = user return key_auth_check
def is_authenticated(self, request, **kwargs): """ Finds the user and checks their API key. Should return either ``True`` if allowed, ``False`` if not or an ``HttpResponse`` if you need something custom. """ from tastypie.utils import get_user_model auth_user_model = get_user_model() try: username, api_key = self.extract_credentials(request) except ValueError: return self._unauthorized() if not username or not api_key: return self._unauthorized() try: username_field = {getattr(auth_user_model, 'USERNAME_FIELD', 'username'): username} user = auth_user_model.objects.get(**username_field) except (auth_user_model.DoesNotExist, auth_user_model.MultipleObjectsReturned): return self._unauthorized() if not self.check_active(user): return False key_auth_check = self.get_key(user, api_key) if key_auth_check and not isinstance(key_auth_check, HttpUnauthorized): request.user = user return key_auth_check
def test_is_authenticated_get_params(self): user_class = get_user_model() auth = ApiKeyAuthentication() request = HttpRequest() # Simulate sending the signal. john_doe = user_class.objects.get(**{user_class.USERNAME_FIELD: 'johndoe'}) create_api_key(User, instance=john_doe, created=True) # No username/api_key details should fail. self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong username details. request.GET[user_class.USERNAME_FIELD] = 'foo' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # No api_key. request.GET[user_class.USERNAME_FIELD] = 'daniel' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong user/api_key. request.GET[user_class.USERNAME_FIELD] = 'daniel' request.GET['api_key'] = 'foo' self.assertEqual(isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Correct user/api_key. john_doe = user_class.objects.get(**{user_class.USERNAME_FIELD: 'johndoe'}) request.GET[user_class.USERNAME_FIELD] = 'johndoe' request.GET['api_key'] = john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True) self.assertEqual(auth.get_identifier(request), 'johndoe')
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): 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 get_user(self, username): from tastypie.utils import get_user_model auth_user_model = get_user_model() try: username_field = {getattr(auth_user_model, 'USERNAME_FIELD', 'username'): username} user = auth_user_model.objects.get(**username_field) except (auth_user_model.DoesNotExist, auth_user_model.MultipleObjectsReturned): return False return user
def extract_credentials(self, request): user_class = get_user_model() if request.META.get('HTTP_AUTHORIZATION') and request.META['HTTP_AUTHORIZATION'].lower().startswith('apikey '): (auth_type, data) = request.META['HTTP_AUTHORIZATION'].split( None, 1 ) if auth_type.lower() != 'apikey': raise ValueError("Incorrect authorization header.") unique_field, api_key = data.split(':', 1) else: unique_field = request.GET.get(user_class.USERNAME_FIELD) or request.POST.get(user_class.USERNAME_FIELD) api_key = request.GET.get('api_key') or request.POST.get('api_key') return unique_field, api_key
def extract_credentials(self, request): user_class = get_user_model() if request.META.get('HTTP_AUTHORIZATION') and request.META[ 'HTTP_AUTHORIZATION'].lower().startswith('apikey '): (auth_type, data) = request.META['HTTP_AUTHORIZATION'].split(None, 1) if auth_type.lower() != 'apikey': raise ValueError("Incorrect authorization header.") unique_field, api_key = data.split(':', 1) else: unique_field = request.GET.get( user_class.USERNAME_FIELD) or request.POST.get( user_class.USERNAME_FIELD) api_key = request.GET.get('api_key') or request.POST.get('api_key') return unique_field, api_key
def test_is_authenticated_header(self): user_class = get_user_model() auth = ApiKeyAuthentication() request = HttpRequest() # Simulate sending the signal. john_doe = user_class.objects.get( **{user_class.USERNAME_FIELD: 'johndoe'}) create_api_key(User, instance=john_doe, created=True) # No username/api_key details should fail. self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong username details. request.META['HTTP_AUTHORIZATION'] = 'foo' self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # No api_key. request.META['HTTP_AUTHORIZATION'] = 'ApiKey daniel' self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong user/api_key. request.META['HTTP_AUTHORIZATION'] = 'ApiKey daniel:pass' self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Correct user/api_key. john_doe = user_class.objects.get( **{user_class.USERNAME_FIELD: 'johndoe'}) request.META[ 'HTTP_AUTHORIZATION'] = 'ApiKey johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True) # Capitalization shouldn't matter. john_doe = user_class.objects.get( **{user_class.USERNAME_FIELD: 'johndoe'}) request.META[ 'HTTP_AUTHORIZATION'] = 'aPiKeY johndoe:%s' % john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True)
def handle_noargs(self, **options): """Goes through all users and adds API keys for any that don't have one.""" self.verbosity = int(options.get('verbosity', 1)) auth_user_model = get_user_model() for user in auth_user_model.objects.all().iterator(): try: api_key = ApiKey.objects.get(user=user) if not api_key.key: # Autogenerate the key. api_key.save() if self.verbosity >= 1: print u"Generated a new key for '%s'" % user.username except ApiKey.DoesNotExist: api_key = ApiKey.objects.create(user=user) if self.verbosity >= 1: print u"Created a new key for '%s'" % user.username
def test_is_authenticated_get_params(self): user_class = get_user_model() auth = ApiKeyAuthentication() request = HttpRequest() # Simulate sending the signal. john_doe = user_class.objects.get( **{user_class.USERNAME_FIELD: 'johndoe'}) create_api_key(User, instance=john_doe, created=True) # No username/api_key details should fail. self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong username details. request.GET[user_class.USERNAME_FIELD] = 'foo' self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # No api_key. request.GET[user_class.USERNAME_FIELD] = 'daniel' self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Wrong user/api_key. request.GET[user_class.USERNAME_FIELD] = 'daniel' request.GET['api_key'] = 'foo' self.assertEqual( isinstance(auth.is_authenticated(request), HttpUnauthorized), True) # Correct user/api_key. john_doe = user_class.objects.get( **{user_class.USERNAME_FIELD: 'johndoe'}) request.GET[user_class.USERNAME_FIELD] = 'johndoe' request.GET['api_key'] = john_doe.api_key.key self.assertEqual(auth.is_authenticated(request), True) self.assertEqual(auth.get_identifier(request), 'johndoe')
request_method = models.CharField(max_length=10, blank=True, default='') accessed = models.PositiveIntegerField() def __unicode__(self): return u"%s @ %s" % (self.identifier, self.accessed) def save(self, *args, **kwargs): self.accessed = int(time.time()) return super(ApiAccess, self).save(*args, **kwargs) if 'django.contrib.auth' in settings.INSTALLED_APPS: import uuid from django.conf import settings auth_user_model = get_user_model() class ApiKey(models.Model): user = models.OneToOneField(auth_user_model, related_name='api_key') key = models.CharField(max_length=256, blank=True, default='') created = models.DateTimeField(default=now) def __unicode__(self): return u"%s for %s" % (self.key, self.user) def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(ApiKey, self).save(*args, **kwargs)