Python: creating tokens without the Django auth models
Bum-Ho12
Posted on October 18, 2023
Hi, as a beginner in django_restframework, it is difficult to work with tokens without first creating a BaseUserManager account model and abstract it to be able to access the AuthToken functionality of restframework. I mean this way:
Basically, you can create tokens for your normal model, but it requires a bit of work. I mean if your model is this way:
Create a new python file in your app and give it a name. The file is for handling tokens, mine i have called it tokenizer.py.
Create another file handling the fetching of tokens, I have named mine token_getter.py
Now, create a third file that handles the token validation, name it whatever you think is best for your taste. I just happened to call mine auth_validity.py
In your views.py,
import
from .auth_validity import is_authenticated
from .token_getter import get_token
and
from .tokenizer import AuthToken
now you can use it like this while you create a user and assign token
AuthToken.objects.create(user=account)
obj = Account.objects.get(email_address = account.email_address)
obj.token = AuthToken.objects.get(user=obj).key
obj.save()
or do this for validation
if is_authenticated(request):
# content
or do this to login
account = Account.objects.get(token = get_token(request))
Well, i don't know how secure this implementation is, but it is easier if you want to avoid using AbstractBaseUser and BaseUserManager so as to access token authentication in django restframework.
Hope this is helpful to someone out there looking for an easier way out without adding extra packages or having to use BaseUserManager.
Posted on October 18, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.