Python django.conf.settings.AUTHENTICATION_BACKENDS Examples

The following are 30 code examples for showing how to use django.conf.settings.AUTHENTICATION_BACKENDS(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: panel.py    License: GNU General Public License v3.0 6 votes vote down vote up
def settings_info():
    info = []
    info.append(('Deploy mode', settings.DEPLOY_MODE))
    info.append(('Database engine', settings.DATABASES['default']['ENGINE']))
    info.append(('Authentication Backends', settings.AUTHENTICATION_BACKENDS))
    info.append(('Cache backend', settings.CACHES['default']['BACKEND']))
    info.append(('Haystack engine', settings.HAYSTACK_CONNECTIONS['default']['ENGINE']))
    info.append(('Email backend', settings.EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_EMAIL') and settings.CELERY_EMAIL:
        info.append(('Celery email backend', settings.CELERY_EMAIL_BACKEND))
    if hasattr(settings, 'CELERY_BROKER_URL'):
        info.append(('Celery broker', settings.CELERY_BROKER_URL.split(':')[0]))

    DATABASES = copy.deepcopy(settings.DATABASES)
    for d in DATABASES:
        if 'PASSWORD' in DATABASES[d]:
            DATABASES[d]['PASSWORD'] = '*****'
    info.append(('DATABASES',  mark_safe('<pre>'+escape(pprint.pformat(DATABASES))+'</pre>')))

    return info 
Example 2
Project: starthinker   Author: google   File: tests.py    License: Apache License 2.0 6 votes vote down vote up
def test_ui_project(self):

    # not logged in ( blank )
    resp = self.client.get('/project/')
    self.assertEqual(resp.status_code, 200)

    self.client.force_login(self.account, backend=settings.AUTHENTICATION_BACKENDS[0])

    # logged in
    resp = self.client.get('/project/')
    self.assertEqual(resp.status_code, 200)

    self.assertContains(resp, self.project_user.identifier)
    self.assertContains(resp, self.project_domain.identifier)
    self.assertContains(resp, self.project_global.identifier)
    self.assertContains(resp, self.project_domain.share.upper())
    self.assertContains(resp, self.project_global.share.upper()) 
Example 3
Project: starthinker   Author: google   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def oauth_callback(request):

  # get the credentials from the Google redirect
  flow = CredentialsFlowWrapper(settings.UI_CLIENT, redirect_uri=settings.CONST_URL + '/oauth_callback/')
  flow.code_verifier = request.session.get('code_verifier')
  flow.fetch_token(code=request.GET['code'])

  # get or create the account
  account = Account.objects.get_or_create_user(flow.credentials)

  # log the account in ( set cookie )
  django_login(request, account, backend=settings.AUTHENTICATION_BACKENDS[0])

  messages.success(request, 'Welcome To StarThinker')

  return HttpResponseRedirect('/') 
Example 4
Project: zulip   Author: zulip   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
def dev_direct_login(
    request: HttpRequest,
    next: str = REQ(default="/"),
) -> HttpResponse:
    # This function allows logging in without a password and should only be called
    # in development environments.  It may be called if the DevAuthBackend is included
    # in settings.AUTHENTICATION_BACKENDS
    if (not dev_auth_enabled()) or settings.PRODUCTION:
        # This check is probably not required, since authenticate would fail without
        # an enabled DevAuthBackend.
        return redirect_to_config_error('dev')
    email = request.POST['direct_email']
    subdomain = get_subdomain(request)
    realm = get_realm(subdomain)
    user_profile = authenticate(dev_auth_username=email, realm=realm)
    if user_profile is None:
        return redirect_to_config_error('dev')
    do_login(request, user_profile)

    redirect_to = get_safe_redirect_to(next, user_profile.realm.uri)
    return HttpResponseRedirect(redirect_to) 
Example 5
Project: dirigible-spreadsheet   Author: pythonanywhere   File: functionaltest.py    License: MIT License 6 votes vote down vote up
def create_users(self):
        for username in self.get_my_usernames():
            user = User.objects.create(username=username)
            user.set_password('p4ssw0rd')
            user.save()
            profile = user.get_profile()
            profile.has_seen_sheet_page = True
            profile.save()

            # create sessions we can use for login too
            session = SessionStore()
            session[SESSION_KEY] = user.pk
            session[BACKEND_SESSION_KEY] = settings.AUTHENTICATION_BACKENDS[0]
            session[HASH_SESSION_KEY] = user.get_session_auth_hash()
            session.save()
            self.session_keys[username] = session.session_key 
Example 6
Project: govready-q   Author: GovReady   File: middleware.py    License: GNU General Public License v3.0 6 votes vote down vote up
def QTemplateContextProcessor(request):
    return {
        "APP_VERSION_STRING": settings.APP_VERSION_STRING,
        "APP_VERSION_COMMIT": settings.APP_VERSION_COMMIT,
        "MOUSE_CURSOR_FOLLOWER": getattr(settings, 'MOUSE_CURSOR_FOLLOWER', False),
        "LOGIN_ENABLED": ('django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS),
    }

# The authentication backend below is used when Q is behind an enterprise proxy server
# handling authentication. The proxy server passes the username and email address of
# the authenticated user in the environment (via HTTP headers or other variables). When
# specifying HTTP headers, be sure to prepend "HTTP_" (e.g., HTTP_IAM-Username). Do not
# prepend anything if it's in the environment (e.g., ICAM_DISPLAYNAME).

# Email address handling: We update the user's email address with the one passed
# in the header whenever we come here. But this only occurs when the user is logging in.
# It seems like if the user has an active Django session and the username in the header
# matches the user in the session then the session is kept and ProxyHeaderUserAuthenticationBackend
# is not called. 
Example 7
Project: diting   Author: getway   File: models.py    License: GNU General Public License v2.0 6 votes vote down vote up
def refresh_setting(self):
        try:
            value = json.loads(self.value)
        except json.JSONDecodeError:
            return
        setattr(settings, self.name, value)

        if self.name == "AUTH_LDAP":
            if self.cleaned_value and settings.AUTH_LDAP_BACKEND not in settings.AUTHENTICATION_BACKENDS:
                settings.AUTHENTICATION_BACKENDS.insert(0, settings.AUTH_LDAP_BACKEND)
            elif not self.cleaned_value and settings.AUTH_LDAP_BACKEND in settings.AUTHENTICATION_BACKENDS:
                settings.AUTHENTICATION_BACKENDS.remove(settings.AUTH_LDAP_BACKEND)

        if self.name == "AUTH_LDAP_SEARCH_FILTER":
            settings.AUTH_LDAP_USER_SEARCH = LDAPSearch(
                settings.AUTH_LDAP_SEARCH_OU, ldap.SCOPE_SUBTREE,
                settings.AUTH_LDAP_SEARCH_FILTER,
            ) 
Example 8
Project: canvas   Author: canvasnetworks   File: api.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def login_with_facebook(request, facebook_access_token):
    try:
        fb_user = FacebookUser.get_from_access_token(facebook_access_token)
    except FacebookUser.DoesNotExist:
        raise PermissionDenied("No DrawQuest user exists for this Facebook account.")

    user = fb_user.user

    if not user.is_active:
        return inactive_user_http_response()

    # this is a total hack because we don't care to write a backend for the above authenticate method
    user.backend = settings.AUTHENTICATION_BACKENDS[0]

    auth.login(request, user)

    return {
        'user': PrivateUserDetails.from_id(user.id).to_client(),
        'user_bio': user.userinfo.bio_text,
        'user_subscribed_to_starred': is_subscribed(user, 'starred'),
        'sessionid': request.session.session_key,
    } 
Example 9
Project: steemprojects.com   Author: wise-team   File: decorators.py    License: MIT License 6 votes vote down vote up
def render_to(template):
    """Simple render_to decorator"""
    def decorator(func):
        """Decorator"""
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            """Rendering method"""
            out = func(request, *args, **kwargs) or {}
            if isinstance(out, dict):
                out = render(request, template, common_context(
                    settings.AUTHENTICATION_BACKENDS,
                    request.user,
                    plus_id=getattr(settings, 'SOCIAL_AUTH_GOOGLE_PLUS_KEY', None),
                    **out
                ))
            return out
        return wrapper
    return decorator 
Example 10
Project: django-rest-registration   Author: apragacz   File: checks.py    License: MIT License 5 votes vote down vote up
def drf_compatible_django_auth_backend_check() -> bool:
    return all(
        incompat_cls_name not in settings.AUTHENTICATION_BACKENDS
        for incompat_cls_name in __DRF_INCOMPATIBLE_DJANGO_AUTH_BACKENDS__
    ) 
Example 11
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_backends(return_tuples=False):
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        backend = load_backend(backend_path)
        backends.append((backend, backend_path) if return_tuples else backend)
    if not backends:
        raise ImproperlyConfigured(
            'No authentication backends have been defined. Does '
            'AUTHENTICATION_BACKENDS contain anything?'
        )
    return backends 
Example 12
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_user(request):
    """
    Returns the user model instance associated with the given request session.
    If no user is retrieved an instance of `AnonymousUser` is returned.
    """
    from .models import AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(request)
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            # Verify the session
            if ('django.contrib.auth.middleware.SessionAuthenticationMiddleware'
                    in settings.MIDDLEWARE_CLASSES and hasattr(user, 'get_session_auth_hash')):
                session_hash = request.session.get(HASH_SESSION_KEY)
                session_hash_verified = session_hash and constant_time_compare(
                    session_hash,
                    user.get_session_auth_hash()
                )
                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser() 
Example 13
Project: django-cas-ng   Author: django-cas-ng   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_login_authenticate_and_create_user(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view authenticates a new user.
    """
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    response = LoginView().get(request)
    assert response.status_code == 302
    assert response['Location'] == '/'
    assert django_user_model.objects.get(username='test@example.com').is_authenticated is True 
Example 14
Project: django-cas-ng   Author: django-cas-ng   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_login_authenticate_do_not_create_user(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view authenticates a user, but does not
    create a user based on the CAS_CREATE_USER setting.
    """
    # No need to test the message framework
    settings.CAS_CREATE_USER = False
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)

    with pytest.raises(PermissionDenied):
        LoginView().get(request)
    assert django_user_model.objects.filter(username='test@example.com').exists() is False 
Example 15
Project: django-cas-ng   Author: django-cas-ng   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_login_proxy_callback(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view has a pgtiou.
    """
    # No need to test the message framework
    settings.CAS_PROXY_CALLBACK = True
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)
    request.session['pgtiou'] = 'fake-pgtiou'
    request.session.save()

    user = django_user_model.objects.create_user('test@example.com', '')
    assert user is not None
    pgt = ProxyGrantingTicket.objects.create(session_key=request.session.session_key,
                                             user=user, pgtiou='fake-pgtiou',
                                             pgt='fake-pgt')
    assert pgt is not None

    response = LoginView().get(request)
    assert response.status_code == 302
    assert django_user_model.objects.get(username='test@example.com').is_authenticated is True
    assert ProxyGrantingTicket.objects.filter(pgtiou='fake-pgtiou').exists() is True
    assert ProxyGrantingTicket.objects.filter(pgtiou='fake-pgtiou').count() == 1 
Example 16
Project: django-cas-ng   Author: django-cas-ng   File: test_views.py    License: MIT License 5 votes vote down vote up
def test_login_redirect_based_on_cookie(monkeypatch, django_user_model, settings):
    """
    Test the case where the login view authenticates a new user and redirects them based on cookie.
    """
    # No need to test the message framework
    settings.CAS_LOGIN_MSG = None
    # Make sure we use our backend
    settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend']
    # Json serializer was havinga  hard time
    settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'
    # Store next as cookie
    settings.CAS_STORE_NEXT = True

    def mock_verify(ticket, service):
        return 'test@example.com', {'ticket': ticket, 'service': service}, None
    monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify)

    factory = RequestFactory()
    request = factory.get('/login/', {'ticket': 'fake-ticket',
                                      'service': 'fake-service'})

    # Create a session object from the middleware
    process_request_for_middleware(request, SessionMiddleware)
    # Create a user object from middleware
    process_request_for_middleware(request, AuthenticationMiddleware)
    # Add the next pointer
    request.session['CASNEXT'] = '/admin/'

    response = LoginView().get(request)
    assert response.status_code == 302
    assert response['Location'] == '/admin/'

    assert 'CASNEXT' not in request.session
    assert django_user_model.objects.get(username='test@example.com').is_authenticated is True 
Example 17
Project: casepro   Author: rapidpro   File: perftest.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def force_login(self, user, backend=None):
        if backend is None:
            backend = settings.AUTHENTICATION_BACKENDS[0]
        user.backend = backend
        self._login(user) 
Example 18
Project: bioforum   Author: reBiocoder   File: client.py    License: MIT License 5 votes vote down vote up
def force_login(self, user, backend=None):
        def get_backend():
            from django.contrib.auth import load_backend
            for backend_path in settings.AUTHENTICATION_BACKENDS:
                backend = load_backend(backend_path)
                if hasattr(backend, 'get_user'):
                    return backend_path
        if backend is None:
            backend = get_backend()
        user.backend = backend
        self._login(user, backend) 
Example 19
Project: bioforum   Author: reBiocoder   File: checks.py    License: MIT License 5 votes vote down vote up
def check_dependencies(**kwargs):
    """
    Check that the admin's dependencies are correctly installed.
    """
    errors = []
    # contrib.contenttypes must be installed.
    if not apps.is_installed('django.contrib.contenttypes'):
        missing_app = checks.Error(
            "'django.contrib.contenttypes' must be in INSTALLED_APPS in order "
            "to use the admin application.",
            id="admin.E401",
        )
        errors.append(missing_app)
    # The auth context processor must be installed if using the default
    # authentication backend.
    try:
        default_template_engine = Engine.get_default()
    except Exception:
        # Skip this non-critical check:
        # 1. if the user has a non-trivial TEMPLATES setting and Django
        #    can't find a default template engine
        # 2. if anything goes wrong while loading template engines, in
        #    order to avoid raising an exception from a confusing location
        # Catching ImproperlyConfigured suffices for 1. but 2. requires
        # catching all exceptions.
        pass
    else:
        if ('django.contrib.auth.context_processors.auth'
                not in default_template_engine.context_processors and
                'django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS):
            missing_template = checks.Error(
                "'django.contrib.auth.context_processors.auth' must be in "
                "TEMPLATES in order to use the admin application.",
                id="admin.E402"
            )
            errors.append(missing_template)
    return errors 
Example 20
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def _get_backends(return_tuples=False):
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        backend = load_backend(backend_path)
        backends.append((backend, backend_path) if return_tuples else backend)
    if not backends:
        raise ImproperlyConfigured(
            'No authentication backends have been defined. Does '
            'AUTHENTICATION_BACKENDS contain anything?'
        )
    return backends 
Example 21
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_user(request):
    """
    Return the user model instance associated with the given request session.
    If no user is retrieved, return an instance of `AnonymousUser`.
    """
    from .models import AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(request)
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            # Verify the session
            if hasattr(user, 'get_session_auth_hash'):
                session_hash = request.session.get(HASH_SESSION_KEY)
                session_hash_verified = session_hash and constant_time_compare(
                    session_hash,
                    user.get_session_auth_hash()
                )
                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser() 
Example 22
Project: starthinker   Author: google   File: tests.py    License: Apache License 2.0 5 votes vote down vote up
def test_ui_recipe_edit(self):

    # not logged in ( redirect )
    resp = self.client.get('/recipe/edit/')
    self.assertEqual(resp.status_code, 302)

    self.client.force_login(self.account, backend=settings.AUTHENTICATION_BACKENDS[0])

    # logged in ( projects in form )
    resp = self.client.get('/recipe/edit/')
    self.assertEqual(resp.status_code, 200)
    self.assertContains(resp, self.project_user)
    self.assertContains(resp, self.project_domain)
    self.assertContains(resp, self.project_global) 
Example 23
Project: pasportaservo   Author: tejoesperanto   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def redirect_update(self, request, payload):
        place = get_object_or_404(Place, pk=payload['place'])
        place.owner.user.backend = settings.AUTHENTICATION_BACKENDS[0]
        login(request, place.owner.user)
        messages.info(request, _("You've been automatically logged in. Happy editing!"))
        return HttpResponseRedirect(place.owner.get_absolute_url()) 
Example 24
Project: zulip   Author: zulip   File: auth.py    License: Apache License 2.0 5 votes vote down vote up
def api_dev_fetch_api_key(request: HttpRequest, username: str=REQ()) -> HttpResponse:
    """This function allows logging in without a password on the Zulip
    mobile apps when connecting to a Zulip development environment.  It
    requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
    """
    if not dev_auth_enabled() or settings.PRODUCTION:
        return json_error(_("Dev environment not enabled."))

    # Django invokes authenticate methods by matching arguments, and this
    # authentication flow will not invoke LDAP authentication because of
    # this condition of Django so no need to check if LDAP backend is
    # enabled.
    validate_login_email(username)

    subdomain = get_subdomain(request)
    realm = get_realm(subdomain)

    return_data: Dict[str, bool] = {}
    user_profile = authenticate(dev_auth_username=username,
                                realm=realm,
                                return_data=return_data)
    if return_data.get("inactive_realm"):
        return json_error(_("This organization has been deactivated."),
                          data={"reason": "realm deactivated"}, status=403)
    if return_data.get("inactive_user"):
        return json_error(_("Your account has been disabled."),
                          data={"reason": "user disable"}, status=403)
    if user_profile is None:
        return json_error(_("This user is not registered."),
                          data={"reason": "unregistered"}, status=403)
    do_login(request, user_profile)
    api_key = get_api_key(user_profile)
    return json_success({"api_key": api_key, "email": user_profile.delivery_email}) 
Example 25
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: client.py    License: MIT License 5 votes vote down vote up
def force_login(self, user, backend=None):
        def get_backend():
            from django.contrib.auth import load_backend
            for backend_path in settings.AUTHENTICATION_BACKENDS:
                backend = load_backend(backend_path)
                if hasattr(backend, 'get_user'):
                    return backend_path
        if backend is None:
            backend = get_backend()
        user.backend = backend
        self._login(user, backend) 
Example 26
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: checks.py    License: MIT License 5 votes vote down vote up
def check_dependencies(**kwargs):
    """
    Check that the admin's dependencies are correctly installed.
    """
    errors = []
    # contrib.contenttypes must be installed.
    if not apps.is_installed('django.contrib.contenttypes'):
        missing_app = checks.Error(
            "'django.contrib.contenttypes' must be in INSTALLED_APPS in order "
            "to use the admin application.",
            id="admin.E401",
        )
        errors.append(missing_app)
    # The auth context processor must be installed if using the default
    # authentication backend.
    try:
        default_template_engine = Engine.get_default()
    except Exception:
        # Skip this non-critical check:
        # 1. if the user has a non-trivial TEMPLATES setting and Django
        #    can't find a default template engine
        # 2. if anything goes wrong while loading template engines, in
        #    order to avoid raising an exception from a confusing location
        # Catching ImproperlyConfigured suffices for 1. but 2. requires
        # catching all exceptions.
        pass
    else:
        if ('django.contrib.auth.context_processors.auth'
                not in default_template_engine.context_processors and
                'django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS):
            missing_template = checks.Error(
                "'django.contrib.auth.context_processors.auth' must be in "
                "TEMPLATES in order to use the admin application.",
                id="admin.E402"
            )
            errors.append(missing_template)
    return errors 
Example 27
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: __init__.py    License: MIT License 5 votes vote down vote up
def _get_backends(return_tuples=False):
    backends = []
    for backend_path in settings.AUTHENTICATION_BACKENDS:
        backend = load_backend(backend_path)
        backends.append((backend, backend_path) if return_tuples else backend)
    if not backends:
        raise ImproperlyConfigured(
            'No authentication backends have been defined. Does '
            'AUTHENTICATION_BACKENDS contain anything?'
        )
    return backends 
Example 28
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_user(request):
    """
    Return the user model instance associated with the given request session.
    If no user is retrieved, return an instance of `AnonymousUser`.
    """
    from .models import AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(request)
        backend_path = request.session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in settings.AUTHENTICATION_BACKENDS:
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            # Verify the session
            if hasattr(user, 'get_session_auth_hash'):
                session_hash = request.session.get(HASH_SESSION_KEY)
                session_hash_verified = session_hash and constant_time_compare(
                    session_hash,
                    user.get_session_auth_hash()
                )
                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser() 
Example 29
Project: python   Author: Yeah-Kun   File: client.py    License: Apache License 2.0 5 votes vote down vote up
def force_login(self, user, backend=None):
        def get_backend():
            from django.contrib.auth import load_backend
            for backend_path in settings.AUTHENTICATION_BACKENDS:
                backend = load_backend(backend_path)
                if hasattr(backend, 'get_user'):
                    return backend_path
        if backend is None:
            backend = get_backend()
        user.backend = backend
        self._login(user, backend) 
Example 30
Project: python   Author: Yeah-Kun   File: checks.py    License: Apache License 2.0 5 votes vote down vote up
def check_dependencies(**kwargs):
    """
    Check that the admin's dependencies are correctly installed.
    """
    errors = []
    # contrib.contenttypes must be installed.
    if not apps.is_installed('django.contrib.contenttypes'):
        missing_app = checks.Error(
            "'django.contrib.contenttypes' must be in INSTALLED_APPS in order "
            "to use the admin application.",
            id="admin.E401",
        )
        errors.append(missing_app)
    # The auth context processor must be installed if using the default
    # authentication backend.
    try:
        default_template_engine = Engine.get_default()
    except Exception:
        # Skip this non-critical check:
        # 1. if the user has a non-trivial TEMPLATES setting and Django
        #    can't find a default template engine
        # 2. if anything goes wrong while loading template engines, in
        #    order to avoid raising an exception from a confusing location
        # Catching ImproperlyConfigured suffices for 1. but 2. requires
        # catching all exceptions.
        pass
    else:
        if ('django.contrib.auth.context_processors.auth'
                not in default_template_engine.context_processors and
                'django.contrib.auth.backends.ModelBackend' in settings.AUTHENTICATION_BACKENDS):
            missing_template = checks.Error(
                "'django.contrib.auth.context_processors.auth' must be in "
                "TEMPLATES in order to use the admin application.",
                id="admin.E402"
            )
            errors.append(missing_template)
    return errors