John Mee
John Mee

Reputation: 52313

Can you explain how "django.contrib.auth" works to me please?

I'm working on an authentication module drawing inspiration from and replacing "django.contrib.auth".

What are they doing with all this and why?

def get_user(request):
  from django.contrib.auth.models import AnonymousUser
  try:
    user_id = request.session[SESSION_KEY]
    backend_path = request.session[BACKEND_SESSION_KEY]
    backend = load_backend(backend_path)
    user = backend.get_user(user_id) or AnonymousUser()
  except KeyError:
    user = AnonymousUser()
  return user

class LazyUser(object):
  def __get__(self, request, obj_type=None):
    if not hasattr(request, '_cached_user'):
        from django.contrib.auth import get_user
        request._cached_user = get_user(request)
    return request._cached_user

class AuthenticationMiddleware(object):
  def process_request(self, request):
    assert hasattr(request, 'session'), "The Django authentication ..."
    request.__class__.user = LazyUser()
    return None

I'd add the authenticate, login, and logout routines but don't want to bore you with too many code dumps. I think I get it now, (that last question might be the key) but only by having forced myself to lay out the question (somewhat) sensibly :-)

Upvotes: 0

Views: 846

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799062

  1. No. It pulls the user at most once per request, but does not span requests.
  2. Yes.
  3. They do. The store the PK.
  4. So that it becomes a class attribute of request (as opposed to an instance attribute), which allows it to work correctly as a descriptor.

Upvotes: 4

Related Questions