Created
September 7, 2012 14:53
-
-
Save mjtamlyn/3666841 to your computer and use it in GitHub Desktop.
Basic rest_framework app key & access token based auth (stripped down)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AccessTokenAuthentication(BaseAuthentication): | |
def authenticate(self, request): | |
auth_header = request.META.get('HTTP_AUTHORIZATION') | |
if not auth_header: | |
return None | |
token = re.match(r'token;([a-f0-9]{32})', auth_header, re.I) | |
if not token: | |
return None | |
token = token.groups()[0].lower() | |
try: | |
access = Access.objects.get(token=token) | |
except Access.DoesNotExist: | |
return None | |
return access | |
class APIKeyAuthentication(BaseAuthentication): | |
def authenticate(self, request): | |
auth_header = request.META.get('HTTP_AUTHORIZATION') | |
if not auth_header: | |
return None | |
key = re.match(r'key;([a-f0-9]{32})', auth_header, re.I) | |
if not key: | |
return None | |
key = key.groups()[0].lower() | |
try: | |
application = Application.objects.get(key=key) | |
except Application.DoesNotExist: | |
return None | |
return application |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Application(models.Model): | |
name = models.CharField(max_length=200) | |
key = models.CharField(max_length=32, blank=True) | |
def save(self, *args, **kwargs): | |
if not self.key: | |
self.key = uuid.uuid4().hex | |
return super(Application, self).save(*args, **kwargs) | |
def is_authenticated(self): | |
"""Application objects can mock as a user for djangorestframework.""" | |
return True | |
class Access(models.Model): | |
user = models.ForeignKey('auth.User') | |
application = models.ForeignKey(Application) | |
token = models.CharField(max_length=32, blank=True) | |
active = models.BooleanField(default=True) | |
created = models.DateTimeField(default=timezone.now, editable=False) | |
def save(self, *args, **kwargs): | |
new = not self.token # new ones (should) never specify a token | |
if new: | |
# create a random token | |
self.token = uuid.uuid4().hex | |
return super(Access, self).save(*args, **kwargs) | |
def is_authenticated(self): | |
"""Access objects can mock as a user for djangorestframework.""" | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment