I'm working with django rest framework
to build my api
, and in the front end I'm using Angular framework
.
I developed a custom middleware
that intercepts every request. I want to logout the user when the condition is not satisfied.
class MyCustomMiddleware(MiddlewareMixin):
def process_request(self, request):
if not request.user.is_authenticated():
#user is not allowed to do this request
#logout the user
I know that from the backend
I can't redirect the user to the login page, it's a front end
staff, but I want to send a notification or something to the front end to tell it that it should redirect the user to the login page.
I have tried to raise PermissionError
and HTTP_403_FORBIDDEN
but none of them worked.
I thought about adding some thing (attribute/parameter) in the header of the request so that in front end interceptor I test if that attribute/parameter exists, but I couldn't find a way for that.
I also tried to set the user of the request to None : request.user=None
but it also failed.
Could somebody tell me if this is possible or not at first?
If so how can I achieve this?
Thanks a lot.
I found it :D
from django.http.response import HttpResponseForbidden
class MyCustomMiddleware(MiddlewareMixin):
def process_request(self, request):
if not request.user.is_authenticated():
#user is not allowed to do this request
return HttpResponseForbidden()
it was just to raise a 403 error
and from front end side I read the status code of the error, if its 403
then redirect the user to the login page.
I Hope it helps somebody in the future.