Tastypie APIKey authentication
Asked Answered
E

1

12

How does the Tastypie APIKey authentication work? I know there is a signal as mentioned in the documentation:

from django.contrib.auth.models import User    
from django.db import models  
from tastypie.models import create_api_key 

models.signals.post_save.connect(create_api_key, sender=User)

However, when is this called? If I want to give a user their APIkey I know I can find it in the APIKey db that this create_api_key function adds the key into, but where and when do I call this models.signals.post_save function?

Is this just another django model? I think it is?

Is this called everytime a user account is saved?

Edson answered 18/9, 2012 at 21:7 Comment(0)
U
18

You can put this in models.py file of the relevant app (such as main/). What post_save.connect(create_api_key, sender=User) does is that everytime an User instance is saved, create_api_key() will be called.

Now let's look into what create_api_key() does by diving a bit into the source of tastypie:

class ApiKey(models.Model):
    user = models.OneToOneField(User, related_name='api_key')
    key = models.CharField(max_length=256, blank=True, default='')
    created = models.DateTimeField(default=datetime.datetime.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)

    def generate_key(self):
        # Get a random UUID.
        new_uuid = uuid.uuid4()
        # Hmac that beast.
        return hmac.new(str(new_uuid), digestmod=sha1).hexdigest()


def create_api_key(sender, **kwargs):
    """
    A signal for hooking up automatic ``ApiKey`` creation.
    """
    if kwargs.get('created') is True:
        ApiKey.objects.create(user=kwargs.get('instance'))

As you can see, create_api_key() will create a new ApiKey record, which will be related to the calling User. This record will also have a HMAC key when it was saved to the ApiKey table. The key is generated by generate_key() function.

Unstained answered 18/9, 2012 at 22:32 Comment(4)
awesome perfect... thanks. So if I change a user's account information will api key change then as well (say the password is changed)?Edson
Nope, the API key will only be created when a new user record is created: docs.djangoproject.com/en/dev/ref/signals/#post-save . Basically, when new User record is created, a created=True parameter will be sent to create_api_key(), updating User will not set created=True thus not triggering the ApiKey creation.Unstained
Im not clear on this, so can you pass create_api_key for an existing user? If not how do you create one for an existing user?Pelag
@Pelag I am not sure what you mean by the first question, but create_api_key is a signal that is not called by updating existing user, if this answers your question.. Second one, the quick (and possibly dirty) way is write a simple script for all users who doesn't have a key, so that it generate_key for them and stores it to ApiKey table at their row.Unstained

© 2022 - 2024 — McMap. All rights reserved.