Beispiel #1
0
        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`.
            """
            logger.debug("Start to retrieve the user data from usercache")
            now = timezone.now()
            user = None
            try:
                userid = auth._get_user_session_key(request)
                userkey = settings.GET_USER_KEY(userid)
                user = usercache.get(userkey)
                if not user:
                    user = User.objects.get(pk=userid)
                    usercache.set(userkey, user, settings.USER_CACHE_TIMEOUT)
                    diff = timezone.now() - now
                    logger.debug(
                        "Spend {} milliseconds to cache the user({}) data from database to usercache"
                        .format(
                            round((diff.seconds * 1000 + diff.microseconds) /
                                  1000), user.email))
                else:
                    diff = timezone.now() - now
                    logger.debug(
                        "Spend {} milliseconds to get the user({}) data from usercache"
                        .format(
                            round((diff.seconds * 1000 + diff.microseconds) /
                                  1000), user.email))
            except KeyError:
                pass
            except ObjectDoesNotExist as ex:
                pass

            return user or anonymoususer
Beispiel #2
0
        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`.
            """
            logger.debug("Start to retrieve the user data from database")
            now = timezone.now()
            user = None
            try:
                userid = auth._get_user_session_key(request)
                user = User.objects.get(pk=userid)
            except KeyError:
                pass
            except ObjectDoesNotExist as ex:
                pass
            finally:
                diff = timezone.now() - now
                logger.debug(
                    "Spend {} milliseconds to retrieve  the user({}) data from  database"
                    .format(
                        round(
                            (diff.seconds * 1000 + diff.microseconds) / 1000),
                        user.email if user else "AnonymousUser"))

            return user or anonymoususer
Beispiel #3
0
def monkey_patched_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 django.contrib.auth.models import AnonymousUser
    user = None
    try:
        user_id = auth._get_user_session_key(request)
        backend_path = request.session[auth.BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in AUTHENTICATION_BACKENDS:
            backend = auth.load_backend(backend_path)
            user = backend.get_user(user_id)
            session_hash = request.session.get(auth.HASH_SESSION_KEY)
            logging.debug(
                request, " ---> Ignoring session hash: %s vs %s" %
                (user.get_session_auth_hash() if user else "[no user]",
                 session_hash))
            # # 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()
Beispiel #4
0
def get_user_object(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()
Beispiel #5
0
 def process_request(self, request):
     assert hasattr(request, 'session'), (
         "The Django authentication middleware requires session middleware "
         "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
         "'django.contrib.sessions.middleware.SessionMiddleware' before "
         "'django.contrib.auth.middleware.AuthenticationMiddleware'."
     )
     request.user = SimpleLazyObject(lambda: get_user(_get_user_session_key(request)))
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 django.contrib.auth.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:
                    session_hash_verified = (
                        session_hash
                        and hasattr(user, '_legacy_get_session_auth_hash')
                        and constant_time_compare(
                            session_hash,
                            user._legacy_get_session_auth_hash(),
                        ))
                if not session_hash_verified and hasattr(
                        settings, 'OLD_SECRET_KEY'):  # noqa
                    key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"  # noqa
                    compare_kwargs = {}
                    if django.VERSION >= (3, 1):
                        compare_kwargs['algorithm'] = (
                            settings.DEFAULT_HASHING_ALGORITHM
                            if django.VERSION < (4, 0) else "sha256")
                    session_hash_verified = session_hash and constant_time_compare(  # noqa
                        session_hash,
                        salted_hmac(key_salt,
                                    user.password,
                                    secret=settings.OLD_SECRET_KEY,
                                    **compare_kwargs).hexdigest())

                    request.session.cycle_key()
                    request.session[
                        HASH_SESSION_KEY] = user.get_session_auth_hash(
                        )  # noqa

                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser()
Beispiel #7
0
 def get_user_id_from_session(request):
     """
     Return the user_id stored in the session of the request.
     """
     from django.contrib.auth import _get_user_session_key
     try:
         # Django call to get the user id which is serialized in the session.
         return _get_user_session_key(request)
     except KeyError:
         return None
Beispiel #8
0
def _get_user(request):
    """
    Return the user associated to the request session;
    Return anonymoususer if no user is associated
    """
    try:
        userid = auth._get_user_session_key(request)
    except:
        return anonymoususer

    return load_user(userid)
Beispiel #9
0
def get_profile_id(request):
    profile_id = None
    try:
        user_id = _get_user_session_key(request)
    except KeyError:
        pass
    else:
        from bookshelf import models

        profile_id = (
            models.Profile.objects.filter(user_id=user_id)
            .values_list("pk", flat=True)
            .first()
        )
    return profile_id
Beispiel #10
0
        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`.
            """
            user = None
            try:
                userid = auth._get_user_session_key(request)
                user = User.objects.get(pk=userid)
            except KeyError:
                pass
            except ObjectDoesNotExist as ex:
                pass

            return user or anonymoususer
Beispiel #11
0
 def get_user_id_from_session(request):
     """
     Return the user_id stored in the session of the request.
     """
     # Starting in django 1.8, the user_id is now serialized
     # as a string in the session.  Before, it was stored
     # directly as an integer. If back-porting to prior to
     # django 1.8, replace the implementation of this method
     # with:
     # return request.session[SESSION_KEY]
     from django.contrib.auth import _get_user_session_key
     try:
         return _get_user_session_key(request)
     except KeyError:
         return None
 def get_user_id_from_session(request):
     """
     Return the user_id stored in the session of the request.
     """
     # Starting in django 1.8, the user_id is now serialized
     # as a string in the session.  Before, it was stored
     # directly as an integer. If back-porting to prior to
     # django 1.8, replace the implementation of this method
     # with:
     # return request.session[SESSION_KEY]
     from django.contrib.auth import _get_user_session_key
     try:
         return _get_user_session_key(request)
     except KeyError:
         return None
Beispiel #13
0
def _get_user(request):
    if not hasattr(request, "_cached_user"):
        try:
            user_id = _get_user_session_key(request)
            USER_CACHE_KEY = "USER_BY_SESSION_CACHE_{}".format(user_id)
            user = cache.get(USER_CACHE_KEY)
            if not user:
                user = get_user(request)
                cache.set(USER_CACHE_KEY, user)
        except KeyError:
            user = get_user(request)
        if user.is_anonymous():
            AnonymousUser = get_anonymous_user_model()
            user = AnonymousUser()
        request._cached_user = user

    return request._cached_user
Beispiel #14
0
        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`.
            """
            user = None
            try:
                userid = auth._get_user_session_key(request)
                userkey = settings.GET_USER_KEY(userid)
                user = usercache.get(userkey)
                if not user:
                    user = User.objects.get(pk=userid)
                    usercache.set(userkey, user, settings.USER_CACHE_TIMEOUT)
            except KeyError:
                pass
            except ObjectDoesNotExist as ex:
                pass

            return user or anonymoususer
Beispiel #15
0
def monkey_patched_get_user(request):
    """
    Return the user model instance associated with the given request session.
    If no user is retrieved, return an instance of `AnonymousUser`.

    Monkey patched for the django 2.0 upgrade because session authentication,
    added in 1.7 and required in 1.10, invalidates all existing 1.5 session auth
    tokens. These tokens need to be refreshed as users login over the year, so
    until then, leave this moneky patch running until we're ready to invalidate
    any user who hasn't logged in during the window between the django 2.0 launch
    and when this monkey patch is removed.
    """
    from django.contrib.auth.models import AnonymousUser
    user = None
    try:
        user_id = auth._get_user_session_key(request)
        backend_path = request.session[auth.BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        if backend_path in AUTHENTICATION_BACKENDS:
            backend = auth.load_backend(backend_path)
            user = backend.get_user(user_id)
            session_hash = request.session.get(auth.HASH_SESSION_KEY)
            logging.debug(
                request, " ---> Ignoring session hash: %s vs %s" %
                (user.get_session_auth_hash() if user else "[no user]",
                 session_hash))
            # # 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()
Beispiel #16
0
def login(request, user):
    session_auth_hash = ''
    if user is None:
        user = request.user
    if hasattr(user, 'get_session_auth_hash'):
        session_auth_hash = user.get_session_auth_hash()

    if SESSION_KEY in request.session:
        if _get_user_session_key(request) != user.pk or (
                    session_auth_hash and
                        request.session.get(HASH_SESSION_KEY) != session_auth_hash):
            request.session.flush()
    else:
        request.session.cycle_key()

    request.session[SESSION_KEY] = user.pk
    request.session[BACKEND_SESSION_KEY] = user.backend
    request.session[HASH_SESSION_KEY] = session_auth_hash
    if hasattr(request, 'user'):
        request.user = user
    rotate_token(request)
    user_logged_in.send(sender=user.__class__, request=request, user=user)
Beispiel #17
0
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 django.contrib.auth.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 and hasattr(settings, 'OLD_SECRET_KEY'):
                    key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
                    session_hash_verified = session_hash and constant_time_compare(
                        session_hash,
                        salted_hmac(key_salt, user.password, secret=settings.OLD_SECRET_KEY).hexdigest()
                    )

                    request.session.cycle_key()
                    request.session[HASH_SESSION_KEY] = user.get_session_auth_hash()

                if not session_hash_verified:
                    request.session.flush()
                    user = None

    return user or AnonymousUser()
Beispiel #18
0
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.
    """
    user = None
    try:
        payload = jwt_decode_handler(request.token)
        user_id = payload.get('user_id', None)
    except (DecodeError, ExpiredSignatureError):
        return AnonymousUser()
    try:
        backend_path = request.session[BACKEND_SESSION_KEY]
        user_id_in_session = _get_user_session_key(request)
    except KeyError:
        user = User.objects.get(pk=user_id)
        login(request, user)
        backend_path = request.session[BACKEND_SESSION_KEY]
    else:
        if user_id_in_session != user_id:
            user = User.objects.get(pk=user_id)
            login(request, user)
            backend_path = request.session[BACKEND_SESSION_KEY]

    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()
Beispiel #19
0
def index(request):
    print(auth.get_user(request),auth._get_user_session_key(request))
    logging.info(request)
    return render(request, 'index.html')
Beispiel #20
0
    def process_request(self, request):
        assert hasattr(request, 'session'), (
            "The djangae.contrib.googleauth middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE%s setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'djangae.contrib.googleauth.middleware.AuthenticationMiddleware'."
        ) % ("_CLASSES" if settings.MIDDLEWARE is None else "")

        request.user = SimpleLazyObject(lambda: get_user(request))

        # See if the handling view is marked with the auth_middleware_exempt
        # decorator, and return if so.
        if request.resolver_match:
            func = request.resolver_match.func
            exempt = getattr(func, "_auth_middleware_exempt", False)
            if exempt:
                return None

        backend_str = request.session.get(BACKEND_SESSION_KEY)

        if request.user.is_authenticated:
            if backend_str and isinstance(load_backend(backend_str),
                                          OAuthBackend):

                # Should we link the Django session to the OAuth session? In most cases we shouldn't
                # as oauth would've been used for identification at login only.
                expire_session = getattr(settings, _OAUTH_LINK_EXPIRY_SETTING,
                                         False)

                if expire_session:
                    # The user is authenticated with Django, and they use the OAuth backend, so they
                    # should have a valid oauth session
                    oauth_session = OAuthUserSession.objects.filter(
                        pk=request.user.google_oauth_id).first()

                    # Their oauth session does not exist, so let's log them out
                    if not oauth_session:
                        logout(request)
                        return None

                    # Their oauth session expired but we still have an active user session
                    if not oauth_session.is_valid:
                        return redirect(
                            reverse("googleauth_oauth2login") + '?' +
                            urlencode(dict(next=request.path)))

            elif backend_str and isinstance(load_backend(backend_str),
                                            IAPBackend):
                if not IAPBackend.can_authenticate(request):
                    logout(request)
        else:
            backends = get_backends()
            try:
                iap_backend = next(
                    filter(lambda be: isinstance(be, IAPBackend), backends))
            except StopIteration:
                iap_backend = None

            # Try to authenticate with IAP if the headers
            # are available
            if iap_backend and IAPBackend.can_authenticate(request):
                # Calling login() cycles the csrf token which causes POST request
                # to break. We only call login if authenticating with IAP changed
                # the user ID in the session, or the user ID was not in the session
                # at all.
                user = iap_backend.authenticate(request)
                if user and user.is_authenticated:
                    should_login = (SESSION_KEY not in request.session or
                                    _get_user_session_key(request) != user.pk)

                    # We always set the backend to IAP so that it truely reflects what was the last
                    # backend to authenticate this user
                    user.backend = 'djangae.contrib.googleauth.backends.iap.%s' % IAPBackend.__name__

                    if should_login:
                        # Setting the backend is needed for the call to login
                        login(request, user)
                    else:
                        # If we don't call login, we need to set request.user ourselves
                        # and update the backend string in the session
                        request.user = user
                        request.session[BACKEND_SESSION_KEY] = user.backend
Beispiel #21
0
    def get_user_id(self):
        serialized = self.request.session.get('_auth_user_id')
        if serialized is None:
            return None

        return _get_user_session_key(self.request)