PageRenderTime 26ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/auth/__init__.py

https://github.com/rohanza/django
Python | 113 lines | 87 code | 8 blank | 18 comment | 17 complexity | 9b302ca0bbe2586fde7c1daf30b603c9 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. from django.contrib.auth.signals import user_logged_in, user_logged_out
  6. SESSION_KEY = '_auth_user_id'
  7. BACKEND_SESSION_KEY = '_auth_user_backend'
  8. REDIRECT_FIELD_NAME = 'next'
  9. def load_backend(path):
  10. i = path.rfind('.')
  11. module, attr = path[:i], path[i+1:]
  12. try:
  13. mod = import_module(module)
  14. except ImportError, e:
  15. raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e))
  16. except ValueError, e:
  17. raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
  18. try:
  19. cls = getattr(mod, attr)
  20. except AttributeError:
  21. raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
  22. if not hasattr(cls, "supports_object_permissions"):
  23. warn("Authentication backends without a `supports_object_permissions` attribute are deprecated. Please define it in %s." % cls,
  24. DeprecationWarning)
  25. cls.supports_object_permissions = False
  26. if not hasattr(cls, 'supports_anonymous_user'):
  27. warn("Authentication backends without a `supports_anonymous_user` attribute are deprecated. Please define it in %s." % cls,
  28. DeprecationWarning)
  29. cls.supports_anonymous_user = False
  30. if not hasattr(cls, 'supports_inactive_user'):
  31. warn("Authentication backends without a `supports_inactive_user` attribute are deprecated. Please define it in %s." % cls,
  32. PendingDeprecationWarning)
  33. cls.supports_inactive_user = False
  34. return cls()
  35. def get_backends():
  36. from django.conf import settings
  37. backends = []
  38. for backend_path in settings.AUTHENTICATION_BACKENDS:
  39. backends.append(load_backend(backend_path))
  40. if not backends:
  41. raise ImproperlyConfigured('No authentication backends have been defined. Does AUTHENTICATION_BACKENDS contain anything?')
  42. return backends
  43. def authenticate(**credentials):
  44. """
  45. If the given credentials are valid, return a User object.
  46. """
  47. for backend in get_backends():
  48. try:
  49. user = backend.authenticate(**credentials)
  50. except TypeError:
  51. # This backend doesn't accept these credentials as arguments. Try the next one.
  52. continue
  53. if user is None:
  54. continue
  55. # Annotate the user object with the path of the backend.
  56. user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
  57. return user
  58. def login(request, user):
  59. """
  60. Persist a user id and a backend in the request. This way a user doesn't
  61. have to reauthenticate on every request.
  62. """
  63. if user is None:
  64. user = request.user
  65. # TODO: It would be nice to support different login methods, like signed cookies.
  66. if SESSION_KEY in request.session:
  67. if request.session[SESSION_KEY] != user.id:
  68. # To avoid reusing another user's session, create a new, empty
  69. # session if the existing session corresponds to a different
  70. # authenticated user.
  71. request.session.flush()
  72. else:
  73. request.session.cycle_key()
  74. request.session[SESSION_KEY] = user.id
  75. request.session[BACKEND_SESSION_KEY] = user.backend
  76. if hasattr(request, 'user'):
  77. request.user = user
  78. user_logged_in.send(sender=user.__class__, request=request, user=user)
  79. def logout(request):
  80. """
  81. Removes the authenticated user's ID from the request and flushes their
  82. session data.
  83. """
  84. # Dispatch the signal before the user is logged out so the receivers have a
  85. # chance to find out *who* logged out.
  86. user = getattr(request, 'user', None)
  87. if hasattr(user, 'is_authenticated') and not user.is_authenticated():
  88. user = None
  89. user_logged_out.send(sender=user.__class__, request=request, user=user)
  90. request.session.flush()
  91. if hasattr(request, 'user'):
  92. from django.contrib.auth.models import AnonymousUser
  93. request.user = AnonymousUser()
  94. def get_user(request):
  95. from django.contrib.auth.models import AnonymousUser
  96. try:
  97. user_id = request.session[SESSION_KEY]
  98. backend_path = request.session[BACKEND_SESSION_KEY]
  99. backend = load_backend(backend_path)
  100. user = backend.get_user(user_id) or AnonymousUser()
  101. except KeyError:
  102. user = AnonymousUser()
  103. return user