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
):
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 cls
= getattr(mod
, attr
)
17 except AttributeError:
18 raise ImproperlyConfigured
, 'Module "%s" does not define a "%s" authentication backend' % (module
, attr
)
22 from django
.conf
import settings
24 for backend_path
in settings
.AUTHENTICATION_BACKENDS
:
25 backends
.append(load_backend(backend_path
))
28 def authenticate(**credentials
):
30 If the given credentials are valid, return a User object.
32 for backend
in get_backends():
34 user
= backend
.authenticate(**credentials
)
36 # This backend doesn't accept these credentials as arguments. Try the next one.
40 # Annotate the user object with the path of the backend.
41 user
.backend
= "%s.%s" % (backend
.__module
__, backend
.__class
__.__name
__)
44 def login(request
, user
):
46 Persist a user id and a backend in the request. This way a user doesn't
47 have to reauthenticate on every request.
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
57 Remove the authenticated user's ID from the request.
60 del request
.session
[SESSION_KEY
]
64 del request
.session
[BACKEND_SESSION_KEY
]
68 def get_user(request
):
69 from django
.contrib
.auth
.models
import AnonymousUser
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()
76 user
= AnonymousUser()