2
from django.core.exceptions import ImproperlyConfigured
4
SESSION_KEY = '_auth_user_id'
5
BACKEND_SESSION_KEY = '_auth_user_backend'
6
REDIRECT_FIELD_NAME = 'next'
8
def load_backend(path):
10
module, attr = path[:i], path[i+1:]
12
mod = __import__(module, {}, {}, [attr])
13
except ImportError, e:
14
raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e)
16
raise ImproperlyConfigured, 'Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?'
18
cls = getattr(mod, attr)
19
except AttributeError:
20
raise ImproperlyConfigured, 'Module "%s" does not define a "%s" authentication backend' % (module, attr)
24
from django.conf import settings
26
for backend_path in settings.AUTHENTICATION_BACKENDS:
27
backends.append(load_backend(backend_path))
30
def authenticate(**credentials):
32
If the given credentials are valid, return a User object.
34
for backend in get_backends():
36
user = backend.authenticate(**credentials)
38
# This backend doesn't accept these credentials as arguments. Try the next one.
42
# Annotate the user object with the path of the backend.
43
user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
46
def login(request, user):
48
Persist a user id and a backend in the request. This way a user doesn't
49
have to reauthenticate on every request.
53
# TODO: It would be nice to support different login methods, like signed cookies.
54
user.last_login = datetime.datetime.now()
57
if SESSION_KEY in request.session:
58
if request.session[SESSION_KEY] != user.id:
59
# To avoid reusing another user's session, create a new, empty
60
# session if the existing session corresponds to a different
62
request.session.flush()
64
request.session.cycle_key()
65
request.session[SESSION_KEY] = user.id
66
request.session[BACKEND_SESSION_KEY] = user.backend
67
if hasattr(request, 'user'):
72
Removes the authenticated user's ID from the request and flushes their
75
request.session.flush()
76
if hasattr(request, 'user'):
77
from django.contrib.auth.models import AnonymousUser
78
request.user = AnonymousUser()
80
def get_user(request):
81
from django.contrib.auth.models import AnonymousUser
83
user_id = request.session[SESSION_KEY]
84
backend_path = request.session[BACKEND_SESSION_KEY]
85
backend = load_backend(backend_path)
86
user = backend.get_user(user_id) or AnonymousUser()
88
user = AnonymousUser()