DEV Community

Bum-Ho12
Bum-Ho12

Posted on

Python: creating tokens without the Django auth models

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:

BaseUserManager model code implementation
Basically, you can create tokens for your normal model, but it requires a bit of work. I mean if your model is this way:

simple account model
all you have to do is:

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.

token Model code

Create another file handling the fetching of tokens, I have named mine token_getter.py

code that gets tokens from the AuthToken model

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

code that describe token validation
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.

Top comments (1)

Collapse
 
dumebii profile image
Dumebi Okolo

Thanks for sharing!