Python django.contrib.auth.load_backend() Examples

The following are 24 code examples of django.contrib.auth.load_backend(). 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 also want to check out all available functions/classes of the module django.contrib.auth , or try the search function .
Example #1
Source File: viste.py    From jorvik with GNU General Public License v3.0 6 votes vote down vote up
def verifica_token(request, me, token):
    verifica = Token.verifica(token, redirect=True)
    if not verifica:
        return errore_generico(request, me, titolo="Token scaduto",
                               messaggio="Potresti aver seguito un link che รจ scaduto.")

    persona, url = verifica

    user = Utenza.objects.get(persona=persona)
    if not hasattr(user, 'backend'):
        for backend in settings.AUTHENTICATION_BACKENDS:
            if user == load_backend(backend).get_user(user.pk):
                user.backend = backend
                break
    if hasattr(user, 'backend'):
        login(request, user)
    return redirect(url) 
Example #2
Source File: protocol.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def getUserFromSessionId(self, session_id):
        """Return the user from `session_id`."""
        session_engine = self.factory.getSessionEngine()
        session_wrapper = session_engine.SessionStore(session_id)
        user_id = session_wrapper.get(SESSION_KEY)
        backend = session_wrapper.get(BACKEND_SESSION_KEY)
        if backend is None:
            return None
        auth_backend = load_backend(backend)
        if user_id is not None and auth_backend is not None:
            user = auth_backend.get_user(user_id)
            # Get the user again prefetching the SSHKey for the user. This is
            # done so a query is not made for each action that is possible on
            # a node in the node listing.
            return (
                User.objects.filter(id=user.id)
                .prefetch_related("sshkey_set")
                .first()
            )
        else:
            return None 
Example #3
Source File: middleware.py    From ontask_b with MIT License 6 votes vote down vote up
def clean_username(self, username, request):
        """
        Allows the backend to clean the username, if the backend defines a
        clean_username method.
        """
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            LOGGER.debug(
                _('calling the backend {0} clean_username with {1}'),
                backend,
                username)
            username = backend.clean_username(username)
            LOGGER.debug(_('cleaned username is {0}'), username)
        except AttributeError:  # Backend has no clean_username method.
            pass
        return username 
Example #4
Source File: middleware_patched.py    From ontask_b with MIT License 6 votes vote down vote up
def clean_username(self, username, request):
        """
        Allows the backend to clean the username, if the backend defines a
        clean_username method.
        """
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            LOGGER.debug('calling the backend %s clean_username with %s',
                         backend,
                         username)
            username = backend.clean_username(username)
            LOGGER.debug('cleaned username is %s', username)
        except AttributeError:  # Backend has no clean_username method.
            pass
        return username 
Example #5
Source File: models.py    From django-username-email with MIT License 6 votes vote down vote up
def with_perm(self, perm, is_active=True, include_superusers=True, backend=None, obj=None):
            if backend is None:
                backends = auth._get_backends(return_tuples=True)
                if len(backends) == 1:
                    backend, _ = backends[0]
                else:
                    raise ValueError(
                        'You have multiple authentication backends configured and '
                        'therefore must provide the `backend` argument.'
                    )
            elif not isinstance(backend, str):
                raise TypeError(
                    'backend must be a dotted import path string (got %r).'
                    % backend
                )
            else:
                backend = auth.load_backend(backend)
            if hasattr(backend, 'with_perm'):
                return backend.with_perm(
                    perm,
                    is_active=is_active,
                    include_superusers=include_superusers,
                    obj=obj,
                )
            return self.none() 
Example #6
Source File: middleware.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def clean_username(self, username, request):
        """
        Allows the backend to clean the username, if the backend defines a
        clean_username method.
        """
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            username = backend.clean_username(username)
        except AttributeError:  # Backend has no clean_username method.
            pass
        return username 
Example #7
Source File: views.py    From django-mfa with MIT License 5 votes vote down vote up
def get_user(self):
        try:
            user_id = self.request.session['u2f_pre_verify_user_pk']
            backend_path = self.request.session['u2f_pre_verify_user_backend']
            self.request.session['verfied_u2f'] = False
            assert backend_path in settings.AUTHENTICATION_BACKENDS
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            if user is not None:
                user.backend = backend_path
            return user
        except (KeyError, AssertionError):
            return None 
Example #8
Source File: auth.py    From django-pgschemas with MIT License 5 votes vote down vote up
def get_user(scope):
    """
    Return the user model instance associated with the given scope.
    If no user is retrieved, return an instance of `AnonymousUser`.
    """
    if "session" not in scope:
        raise ValueError("Cannot find session in scope. You should wrap your consumer in SessionMiddleware.")
    user = None
    session = scope["session"]
    with scope["tenant"]:
        try:
            user_id = _get_user_session_key(session)
            backend_path = 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 = 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:
                        session.flush()
                        user = None
    return user or AnonymousUser() 
Example #9
Source File: views.py    From django-u2f with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_user(self):
        try:
            user_id = self.request.session['u2f_pre_verify_user_pk']
            backend_path = self.request.session['u2f_pre_verify_user_backend']
            assert backend_path in settings.AUTHENTICATION_BACKENDS
            backend = load_backend(backend_path)
            user = backend.get_user(user_id)
            if user is not None:
                user.backend = backend_path
            return user
        except (KeyError, AssertionError):
            return None 
Example #10
Source File: models.py    From cykel with MIT License 5 votes vote down vote up
def with_perm(
        self, perm, is_active=True, include_superusers=True, backend=None, obj=None
    ):
        if backend is None:
            backends = auth._get_backends(return_tuples=True)
            if len(backends) == 1:
                backend, _ = backends[0]
            else:
                raise ValueError(
                    "You have multiple authentication backends configured and "
                    "therefore must provide the `backend` argument."
                )
        elif not isinstance(backend, str):
            raise TypeError(
                "backend must be a dotted import path string (got %r)." % backend
            )
        else:
            backend = auth.load_backend(backend)
        if hasattr(backend, "with_perm"):
            return backend.with_perm(
                perm,
                is_active=is_active,
                include_superusers=include_superusers,
                obj=obj,
            )
        return self.none() 
Example #11
Source File: middleware.py    From python2017 with MIT License 5 votes vote down vote up
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request) 
Example #12
Source File: middleware.py    From python2017 with MIT License 5 votes vote down vote up
def clean_username(self, username, request):
        """
        Allows the backend to clean the username, if the backend defines a
        clean_username method.
        """
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            username = backend.clean_username(username)
        except AttributeError:  # Backend has no clean_username method.
            pass
        return username 
Example #13
Source File: client.py    From python2017 with 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 #14
Source File: middleware.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request) 
Example #15
Source File: client.py    From python with 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 #16
Source File: middleware.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def _remove_invalid_user(self, request):
        """
        Remove the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request) 
Example #17
Source File: middleware.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def clean_username(self, username, request):
        """
        Allow the backend to clean the username, if the backend defines a
        clean_username method.
        """
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            username = backend.clean_username(username)
        except AttributeError:  # Backend has no clean_username method.
            pass
        return username 
Example #18
Source File: client.py    From Hands-On-Application-Development-with-PyCharm with 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
Source File: middleware.py    From bioforum with MIT License 5 votes vote down vote up
def _remove_invalid_user(self, request):
        """
        Remove the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request) 
Example #20
Source File: middleware.py    From bioforum with MIT License 5 votes vote down vote up
def clean_username(self, username, request):
        """
        Allow the backend to clean the username, if the backend defines a
        clean_username method.
        """
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            username = backend.clean_username(username)
        except AttributeError:  # Backend has no clean_username method.
            pass
        return username 
Example #21
Source File: client.py    From bioforum with 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 #22
Source File: middleware.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _remove_invalid_user(self, request):
        """
        Removes the current authenticated user in the request which is invalid
        but only if the user is authenticated via the RemoteUserBackend.
        """
        try:
            stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
        except ImportError:
            # backend failed to load
            auth.logout(request)
        else:
            if isinstance(stored_backend, RemoteUserBackend):
                auth.logout(request) 
Example #23
Source File: middleware.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def clean_username(self, username, request):
        """
        Allows the backend to clean the username, if the backend defines a
        clean_username method.
        """
        backend_str = request.session[auth.BACKEND_SESSION_KEY]
        backend = auth.load_backend(backend_str)
        try:
            username = backend.clean_username(username)
        except AttributeError:  # Backend has no clean_username method.
            pass
        return username 
Example #24
Source File: middleware.py    From product-definition-center with MIT License 4 votes vote down vote up
def process_request(self, request):
        # Overwrite process_request from auth.middleware because it force
        # user logout when REMOTE_USER header is not present which can
        # cause problem while deploying with Kerberos authentication when
        # we need to enable both anonymous access and kerberos login.

        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Django remote user auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the RemoteUserMiddleware class.")

        if settings.DEBUG and getattr(settings, "DEBUG_USER", None):
            request.META[self.header] = settings.DEBUG_USER

        try:
            username = request.META[self.header]
        except KeyError:
            # When the page which requires kerberos login was redirected from
            # kerberos login entrance, 'REMOTE_USER' header is lost in request
            # meta, thus the RemoteUserMiddleware will make it falling into
            # redirect loop.
            return

        # If the user is already authenticated and that user is the user we are
        # getting passed in the headers, then the correct user is already
        # persisted in the session and we don't need to continue.
        if request.user.is_authenticated:
            if request.user.get_username() == self.clean_username(username, request):
                return
        # We are seeing this user for the first time in this session, attempt
        # to authenticate the user.
        user = auth.authenticate(remote_user=username, request=request)
        if user:
            # User is valid.  Set request.user and persist user in the session
            # by logging the user in.
            request.user = user
            request.session['auth_backend'] = user.backend
            backend = load_backend(user.backend)
            if getattr(backend, 'save_login', True):
                auth.login(request, user)