Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Auth backend with middleware

Tags:

django

I tried looking at this answer, as well as using django sessions here.

The login with my custom auth works fine, but I want to validate the token on every request with middleware, and I can't figure out how to store the token so that it may be accessed from both the middleware as well as views.

I tried storing a session variable from my auth backend, but I would always get a key error when trying to access it from my views.

Is there a good way to do this?

Thanks!

class MyAuthBackend(object):

    supports_inactive_user = False
    supports_object_permissions = False
    supports_anonymous_user = False

    def authenticate(self, username=None, password=None):
    # This makes a call to my API to varify login, then return token if valid. I need to make login_valid accessible to my middleware and views.
        login_valid = auth.login(username,password)
        if login_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                user = User(username=username, password='never_used')
                user.is_active = True
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None





class MyAuthMiddleware(object):
    def process_request(self, request):
        if not request.user.is_anonymous():
    # API call to my backend to check if token is still valid. If not, return to login page.
            token_variable = ???????????
            if isTokenStillValid(token_variable):
                return
            else:
            return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)
like image 793
Zee Avatar asked May 16 '26 04:05

Zee


1 Answers

Are you using the default django.contrib.auth login view for logging in? It seems to completely clear the session during the login process (which happens after your authentication backend is called, in contrib.auth.login function, described here).

I think you might either try to write your own login view, with an alternative login function that preserves the auth token, or store the token somewhere else (database table, cache system). The latter might make it difficult to allow multiple simultaneous logins for one user.

like image 175
che Avatar answered May 17 '26 17:05

che



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!