aeusman aeusman - 10 months ago 35
Python Question

Checking if a user has been assigned a token in Django Restframework

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?


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.