0

I am setting up token authentication for a site using Django Restframework and need to be able to have a user download their token, however the catch is that they much only be able to download their token once (similar to the Amazon AWS model).

In other words; is there a native way to check if a user has been assigned a token in restframework?

aeusman
  • 11
  • 1
  • 6
  • 2
    what did you try so far? – Justin M. Ucar Jul 25 '16 at 20:15
  • I've tried poking through the documentation to see if there are any other Token.object functions other than create and get_or_create, but wasn't able to find anything. Source diving didn't give me anything either. My goal is to avoid a try catch block for a failed token authorization in favor of a native solution (too many possible problems with the try-catch block approach). – aeusman Jul 25 '16 at 20:23

2 Answers2

2

you can do this:

from rest_framework.authtoken.models import Token
from django.conf import settings
token = Token.objects.create(user=settings.AUTH_USER_MODEL)

now you can just check if your given user has a token:

user_with_token = Token.objects.get(user=user)

if you just wanna see if the user has a token:

is_tokened = Token.objects.filter(user=user).exist()  # Returns a boolean

if the entry exists it means the user has a token assigned to it. Reference: HERE

Follow the documentation there to make sure your database is migrated.

Justin M. Ucar
  • 853
  • 9
  • 17
  • So to check this I run in a shell; from rest_framework.authtoken.models import Token; from django.conf import settings; #I've created a user test which has no token in django web admin; u = User.objects.get(username='test'); user_token = Token.objects.get(user=u); < This returns a DoesNotExist Error, which I'm trying to essentially catch natively – aeusman Jul 25 '16 at 20:37
0

try use a django signal to create user token automatically, something like this on your models file.

@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
    Token.objects.create(user=instance)