/django/contrib/auth/__init__.py

https://github.com/eric-brechemier/django · Python · 100 lines · 73 code · 7 blank · 20 comment · 15 complexity · f1d8c19c1b9d40d42869582537025a3e MD5 · raw file

  1. import datetime
  2. from warnings import warn
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.utils.importlib import import_module
  5. SESSION_KEY = '_auth_user_id'
  6. BACKEND_SESSION_KEY = '_auth_user_backend'
  7. 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(module)
  13. except ImportError, e:
  14. raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e))
  15. except ValueError, e:
  16. raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
  17. try:
  18. cls = getattr(mod, attr)
  19. except AttributeError:
  20. raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
  21. if not hasattr(cls, "supports_object_permissions"):
  22. warn("Authentication backends without a `supports_object_permissions` attribute are deprecated. Please define it in %s." % cls,
  23. PendingDeprecationWarning)
  24. cls.supports_object_permissions = False
  25. if not hasattr(cls, 'supports_anonymous_user'):
  26. warn("Authentication backends without a `supports_anonymous_user` attribute are deprecated. Please define it in %s." % cls,
  27. PendingDeprecationWarning)
  28. cls.supports_anonymous_user = False
  29. return cls()
  30. def get_backends():
  31. from django.conf import settings
  32. backends = []
  33. for backend_path in settings.AUTHENTICATION_BACKENDS:
  34. backends.append(load_backend(backend_path))
  35. return backends
  36. def authenticate(**credentials):
  37. """
  38. If the given credentials are valid, return a User object.
  39. """
  40. for backend in get_backends():
  41. try:
  42. user = backend.authenticate(**credentials)
  43. except TypeError:
  44. # This backend doesn't accept these credentials as arguments. Try the next one.
  45. continue
  46. if user is None:
  47. continue
  48. # Annotate the user object with the path of the backend.
  49. user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
  50. return user
  51. def login(request, user):
  52. """
  53. Persist a user id and a backend in the request. This way a user doesn't
  54. have to reauthenticate on every request.
  55. """
  56. if user is None:
  57. user = request.user
  58. # TODO: It would be nice to support different login methods, like signed cookies.
  59. user.last_login = datetime.datetime.now()
  60. user.save()
  61. if SESSION_KEY in request.session:
  62. if request.session[SESSION_KEY] != user.id:
  63. # To avoid reusing another user's session, create a new, empty
  64. # session if the existing session corresponds to a different
  65. # authenticated user.
  66. request.session.flush()
  67. else:
  68. request.session.cycle_key()
  69. request.session[SESSION_KEY] = user.id
  70. request.session[BACKEND_SESSION_KEY] = user.backend
  71. if hasattr(request, 'user'):
  72. request.user = user
  73. def logout(request):
  74. """
  75. Removes the authenticated user's ID from the request and flushes their
  76. session data.
  77. """
  78. request.session.flush()
  79. if hasattr(request, 'user'):
  80. from django.contrib.auth.models import AnonymousUser
  81. request.user = AnonymousUser()
  82. def get_user(request):
  83. from django.contrib.auth.models import AnonymousUser
  84. try:
  85. user_id = request.session[SESSION_KEY]
  86. backend_path = request.session[BACKEND_SESSION_KEY]
  87. backend = load_backend(backend_path)
  88. user = backend.get_user(user_id) or AnonymousUser()
  89. except KeyError:
  90. user = AnonymousUser()
  91. return user