I am using a custom authentication backend for Django (which runs off couchdb). I have a custom user model.
As part of the login, I am doing a request.user = u
You say you've written a custom authentication backend, but in fact what you seem to have written is a complete custom authentication app, which doesn't interface with Django's contrib.auth
.
If you want to use a non-relational database for your authentication data, all you need to do is create a class that provides two methods: get_user(user_id)
and authenticate(**credentials)
. See the documentation. Once you have authenticated a user, you simply call Django's normal login methods. There should be no reason to manually set request.user
or put anything into the session.
Update after edit That has nothing to do with it. There's no requirement that the user class derives from auth.models.User
. You still just need to define a get_user
method that will return an instance of your user class.
Added these in my view
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
and started getting original user
In case you are using an API (Django-rest-framework) and accessing a view using a get, post, etc. methods.
You can get a user by sending the Bearer/JWT token corresponding to that user.
Wrong
# prints Anonymous User
def printUser(request):
print(request.user)
Correct
# using decorators
# prints username of the user
@api_view(['GET']) # or ['POST'] .... according to the requirement
def printUser()
print(request.user)