App Engine Python SDK version 1.9.12
[gae.git] / python / lib / django-0.96 / django / contrib / auth / __init__.py
blobdd3b8152e6be1967ef642e448db28c770c21a540
1 from django.core.exceptions import ImproperlyConfigured
3 SESSION_KEY = '_auth_user_id'
4 BACKEND_SESSION_KEY = '_auth_user_backend'
5 LOGIN_URL = '/accounts/login/'
6 REDIRECT_FIELD_NAME = 'next'
8 def load_backend(path):
9 i = path.rfind('.')
10 module, attr = path[:i], path[i+1:]
11 try:
12 mod = __import__(module, {}, {}, [attr])
13 except ImportError, e:
14 raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e)
15 try:
16 cls = getattr(mod, attr)
17 except AttributeError:
18 raise ImproperlyConfigured, 'Module "%s" does not define a "%s" authentication backend' % (module, attr)
19 return cls()
21 def get_backends():
22 from django.conf import settings
23 backends = []
24 for backend_path in settings.AUTHENTICATION_BACKENDS:
25 backends.append(load_backend(backend_path))
26 return backends
28 def authenticate(**credentials):
29 """
30 If the given credentials are valid, return a User object.
31 """
32 for backend in get_backends():
33 try:
34 user = backend.authenticate(**credentials)
35 except TypeError:
36 # This backend doesn't accept these credentials as arguments. Try the next one.
37 continue
38 if user is None:
39 continue
40 # Annotate the user object with the path of the backend.
41 user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
42 return user
44 def login(request, user):
45 """
46 Persist a user id and a backend in the request. This way a user doesn't
47 have to reauthenticate on every request.
48 """
49 if user is None:
50 user = request.user
51 # TODO: It would be nice to support different login methods, like signed cookies.
52 request.session[SESSION_KEY] = user.id
53 request.session[BACKEND_SESSION_KEY] = user.backend
55 def logout(request):
56 """
57 Remove the authenticated user's ID from the request.
58 """
59 try:
60 del request.session[SESSION_KEY]
61 except KeyError:
62 pass
63 try:
64 del request.session[BACKEND_SESSION_KEY]
65 except KeyError:
66 pass
68 def get_user(request):
69 from django.contrib.auth.models import AnonymousUser
70 try:
71 user_id = request.session[SESSION_KEY]
72 backend_path = request.session[BACKEND_SESSION_KEY]
73 backend = load_backend(backend_path)
74 user = backend.get_user(user_id) or AnonymousUser()
75 except KeyError:
76 user = AnonymousUser()
77 return user