PageRenderTime 56ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/packages/django/contrib/auth/__init__.py

https://gitlab.com/gregtyka/Scryve-Webapp
Python | 103 lines | 77 code | 6 blank | 20 comment | 17 complexity | bae7cbaddd0f6f037068a8e73a9327c8 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. try:
  22. getattr(cls, 'supports_object_permissions')
  23. except AttributeError:
  24. warn("Authentication backends without a `supports_object_permissions` attribute are deprecated. Please define it in %s." % cls,
  25. PendingDeprecationWarning)
  26. cls.supports_object_permissions = False
  27. try:
  28. getattr(cls, 'supports_anonymous_user')
  29. except AttributeError:
  30. warn("Authentication backends without a `supports_anonymous_user` attribute are deprecated. Please define it in %s." % cls,
  31. PendingDeprecationWarning)
  32. cls.supports_anonymous_user = False
  33. return cls()
  34. def get_backends():
  35. from django.conf import settings
  36. backends = []
  37. for backend_path in settings.AUTHENTICATION_BACKENDS:
  38. backends.append(load_backend(backend_path))
  39. return backends
  40. def authenticate(**credentials):
  41. """
  42. If the given credentials are valid, return a User object.
  43. """
  44. for backend in get_backends():
  45. try:
  46. user = backend.authenticate(**credentials)
  47. except TypeError:
  48. # This backend doesn't accept these credentials as arguments. Try the next one.
  49. continue
  50. if user is None:
  51. continue
  52. # Annotate the user object with the path of the backend.
  53. user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
  54. return user
  55. def login(request, user):
  56. """
  57. Persist a user id and a backend in the request. This way a user doesn't
  58. have to reauthenticate on every request.
  59. """
  60. if user is None:
  61. user = request.user
  62. # TODO: It would be nice to support different login methods, like signed cookies.
  63. user.last_login = datetime.datetime.now()
  64. user.save()
  65. if SESSION_KEY in request.session:
  66. if request.session[SESSION_KEY] != user.id:
  67. # To avoid reusing another user's session, create a new, empty
  68. # session if the existing session corresponds to a different
  69. # authenticated user.
  70. request.session.flush()
  71. else:
  72. request.session.cycle_key()
  73. request.session[SESSION_KEY] = user.id
  74. request.session[BACKEND_SESSION_KEY] = user.backend
  75. if hasattr(request, 'user'):
  76. request.user = user
  77. def logout(request):
  78. """
  79. Removes the authenticated user's ID from the request and flushes their
  80. session data.
  81. """
  82. request.session.flush()
  83. if hasattr(request, 'user'):
  84. from django.contrib.auth.models import AnonymousUser
  85. request.user = AnonymousUser()
  86. def get_user(request):
  87. from django.contrib.auth.models import AnonymousUser
  88. try:
  89. user_id = request.session[SESSION_KEY]
  90. backend_path = request.session[BACKEND_SESSION_KEY]
  91. backend = load_backend(backend_path)
  92. user = backend.get_user(user_id) or AnonymousUser()
  93. except KeyError:
  94. user = AnonymousUser()
  95. return user