I have question related with Django . I am using Knox Token Authentication to generate tokens for every user when he log in on the page.
Now I want to use that token for every request that will send so I can get the corresponding user for the token. Also I am using custom function example def dashboard(request) in Django for every URL route.
I have see on youtube that there are option to get user from token but is not with functions
class UserAPI(generics.RetrieveAPIView):
permission_classes = [
permissions.IsAuthenticated,
]
serializer_class = UserSerializer
def get_object(self):
return self.request.user
So is there a whey to get the corresponding user from a token within a custom function
Great, I figured out in hours that knox doesn't come with full token_key stored in database.
Real token we can get is something like:
a512529e7ffceaa8406ceb616d088b3422ad15811a5eb470e8f4c4896c9aa649In database token_key is stored by default
a512529e. 8 digits.Filter objects using this:
knox_object = AuthToken.objects.filter(token_key__startswith=token[:8]).first()Then get user objectknox_object.user.usernameOr you can use this, faster
From the knox source codes
You can see
TOKEN_KEY_LENGTHis of 8 digits.I wrote a simple function to do that
Life be easier now. :)
Yes, I improved it and published it.
You may try my fork. If you just simply want to add
@smart_token_userbefore any GET/POST/PUT/... methods.https://github.com/xros/django-rest-knox
Just git clone, and
pip install ./I wrote a decorator.
With this, in our app views.py we can easily get user object by doing so,
@smart_token_userwill modify the request handler. We can have arequest.userattr only once the token is valid. And all invalid attempts will be thrown out with HTTP 401 Unauthorized response. Life can be easier with this decorator.Or use this like original if you want:
authentication_classes = (TokenAuthentication,)