Reputation: 12383
I am working on a solution that is taking a JWT token, finding the associated user, and setting the user in the request to the found user with the token. My middleware looks like this:
class UserTokenMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
header_token = request.META.get('HTTP_AUTHORIZATION', None)
if header_token is not None:
try:
token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
data = {'token': token}
valid_data = VerifyJSONWebTokenSerializer().validate(data)
user = valid_data['user']
request.user = user
except Token.DoesNotExist:
pass
print(request.user.auth_token);
return self.get_response(request)
And it works! The auth_token is present! And its added at the bottom of my middleware like so:
MIDDLEWARE = [
#Added Last
"app.middleware.UserTokenMiddleware"
]
Now here where doesn't work. I am trying to log out by deleted token, and I need the key. So I have this:
@action( url_path="logout", detail=False, methods=["get"], renderer_classes=[JSONRenderer])
def endsession(self, request):
result = logout(request)
#request.user.auth_token.delete()
print("Auth Token")
print(request.user.auth_token);
print(result)
return Response({"logout": "successful"})
Except I always get the following error:
Exception Type: AttributeError at /v1/users/logout
Exception Value: 'AnonymousUser' object has no attribute 'auth_token'
Any clue to why the auth_token is suddenly disappearing and reverting to AnonymousUser?
Upvotes: 1
Views: 104
Reputation: 599590
Because you call logout
at the start of the view; that specifically sets the user to anonymous.
Upvotes: 1