Python django.contrib.auth.BACKEND_SESSION_KEY Examples

The following are 20 code examples of django.contrib.auth.BACKEND_SESSION_KEY(). 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: 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 #2
Source File: middleware.py    From mozilla-django-oidc with Mozilla Public License 2.0 6 votes vote down vote up
def is_refreshable_url(self, request):
        """Takes a request and returns whether it triggers a refresh examination

        :arg HttpRequest request:

        :returns: boolean

        """
        # Do not attempt to refresh the session if the OIDC backend is not used
        backend_session = request.session.get(BACKEND_SESSION_KEY)
        is_oidc_enabled = True
        if backend_session:
            auth_backend = import_string(backend_session)
            is_oidc_enabled = issubclass(auth_backend, OIDCAuthenticationBackend)

        return (
            request.method == 'GET' and
            request.user.is_authenticated and
            is_oidc_enabled and
            request.path not in self.exempt_urls
        ) 
Example #3
Source File: functionaltest.py    From dirigible-spreadsheet with 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 #4
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 #5
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 #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-otp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def form_valid(self, form):
        # OTPTokenForm does not call authenticate(), so we may need to populate
        # user.backend ourselves to keep login() happy.
        user = form.get_user()
        if not hasattr(user, 'backend'):
            user.backend = self.request.session[BACKEND_SESSION_KEY]

        return super().form_valid(form)


# Backwards compatibility. 
Example #8
Source File: utils.py    From django-functest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shortcut_logout(self):
        self.set_session_data({AUTH_BACKEND_SESSION_KEY: ''}) 
Example #9
Source File: utils.py    From django-functest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shortcut_login(self, **credentials):
        user = authenticate(**credentials)
        if not user:
            raise ValueError("User {0} was not authenticated".format(user))

        session_auth_hash = ''
        if hasattr(user, 'get_session_auth_hash'):
            session_auth_hash = user.get_session_auth_hash()

        # Mimicking django.contrib.auth functionality
        self.set_session_data({AUTH_ID_SESSION_KEY: user.pk,
                               AUTH_HASH_SESSION_KEY: session_auth_hash,
                               AUTH_BACKEND_SESSION_KEY: user.backend}) 
Example #10
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 #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: models.py    From esproxy with MIT License 5 votes vote down vote up
def _is_cas_backend(session):
    """ Checks if the auth backend is CASBackend """
    backend = session.get(BACKEND_SESSION_KEY)
    from django_cas.backends import CASBackend
    return backend == '{0.__module__}.{0.__name__}'.format(CASBackend) 
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: 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 #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: 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 #19
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 #20
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)