2

From the tastypie tutorial:

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)

The tutorial says:

"Tastypie includes a signal function you can use to auto-create ApiKey objects."

I don't know where to put this code, help please.

okm
  • 23,575
  • 5
  • 83
  • 90
Kendo Jaa
  • 95
  • 2
  • 9
  • I put this code in my api.py. and It worked!! It automatically generate api_key,when I create new user. I knew this because I did by admin page. But I don't know how send the apikey back to user. The second question is " is it correct the apikey in the client side should be deleted when user log out from this application. and will get the same apikey again when he logs in – Kendo Jaa Feb 03 '13 at 10:15
  • It depends on your usage -- but I can't think of many use cases you would need to regenerate the API key every time the user logs out. You *might* be thinking of [session keys](http://en.wikipedia.org/wiki/Session_key). – K Z Feb 03 '13 at 10:19
  • when user logs in ,the process that will happen is check the compatibility between the user and password by compare with attribute in User model. and then send him back the apikey. Is this statement true? – Kendo Jaa Feb 03 '13 at 10:20
  • I strongly suspect you are thinking of [session key](http://en.wikipedia.org/wiki/Session_key) instead of [API key](http://en.wikipedia.org/wiki/Application_programming_interface_key). – K Z Feb 03 '13 at 10:21
  • OH, I misunderstood the concept of api key . thx for your advise. Actually, Api Key is for identify the user by that key > – Kendo Jaa Feb 03 '13 at 10:55
  • @KayZhu I am in the process of development of mobile application. and the user of this application have to authenticate with username and password to use this app. What authentication method in tastypie is the most suitable for this application. Or do you have any recommendation. sorry I'm quite noob – Kendo Jaa Feb 03 '13 at 11:09
  • It really depends on your usage and needs.. do you provide your users with API keys so that they can use your API endpoints directly? If so, I would use `ApiKeyAuthentication`. If your users use your API *indirectly* after they log in with their password, then why not just use Django's `auth` or tastypie's `BasicAuthentication`? You may also want to checkout `OAuth`.. – K Z Feb 03 '13 at 12:16
  • You may also be interested in this discussion: https://github.com/toastdriven/django-tastypie/issues/197 – K Z Feb 03 '13 at 12:31
  • I am developing mobile application with tastypie django – Kendo Jaa Feb 03 '13 at 14:04
  • If your users needs to log in to your mobile app with their password, then I think `BasicAuthentication` is a good choice here. If you give your users API keys, go with `ApiKeyAuthentication`. – K Z Feb 04 '13 at 23:14

1 Answers1

0

You can put this code in models.py file of the relevant app. Alternatively, you can also place it in signals.py under your app directory -- remember to also import signals in your app's __init__.py file.

What this code does here is that by using signals, every time a User is created, an HMAC API key will be automatically created for this user [source]:

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'))
K Z
  • 29,661
  • 8
  • 73
  • 78