Python django.conf.settings.SESSION_COOKIE_NAME Examples

The following are 30 code examples of django.conf.settings.SESSION_COOKIE_NAME(). 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.conf.settings , or try the search function .
Example #1
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_httponly_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], True)
        self.assertIn(
            cookies.Morsel._reserved['httponly'],
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        ) 
Example #2
Source File: util.py    From drf-to-s3 with MIT License 6 votes vote down vote up
def establish_session(original_function):
    '''
    Simulate establishing a session.

    Adapted from https://code.djangoproject.com/ticket/10899 and
    http://blog.joshcrompton.com/2012/09/how-to-use-sessions-in-django-unit-tests.html

    FIXME this needs its own tests

    '''
    def new_function(self, *args, **kwargs):
        from importlib import import_module
        from django.conf import settings

        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()  # we need to make load() work, or the cookie is worthless

        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
        self.session_key = store.session_key

        original_function(self, *args, **kwargs)
    return new_function 
Example #3
Source File: middleware.py    From django-polaris with Apache License 2.0 6 votes vote down vote up
def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.
        from django.conf import settings
        from polaris import settings as polaris_settings

        if (
            settings.SESSION_COOKIE_NAME in response.cookies
            and not polaris_settings.LOCAL_MODE
        ):
            response.cookies[settings.SESSION_COOKIE_NAME]["samesite"] = "None"
            response.cookies[settings.SESSION_COOKIE_NAME]["secure"] = True

        return response 
Example #4
Source File: functionaltest.py    From dirigible-spreadsheet with MIT License 6 votes vote down vote up
def login(
        self, username=None, password=USER_PASSWORD, manually=False
    ):
        if username is None:
            username = self.get_my_username()

        if manually:
            self.get_element('id=id_username').clear()
            self.get_element('id=id_password').clear()
            self.get_element('id=id_username').send_keys(username)
            self.get_element('id=id_password').send_keys(password)
            self.click_link('id_login')
            return

        session_key = self.session_keys[username]
        ## to set a cookie we need to first visit the domain.
        ## 404 pages load the quickest!
        self.browser.get(urljoin(Url.ROOT, "/404_no_such_url/"))
        self.browser.add_cookie(dict(
            name=settings.SESSION_COOKIE_NAME,
            value=session_key,
            path='/',
        ))
        self.go_to_url(Url.ROOT) 
Example #5
Source File: mixins.py    From credentials with GNU Affero General Public License v3.0 6 votes vote down vote up
def login(self, superuser=False):
        """ Craft cookie to fake a login. """
        assert auth, "auth.py could not be imported from acceptance_tests"

        # First visit a guaranteed 404, just to get selenium in the right domain (it doesn't like us setting cookies
        # for places we aren't in, even if we specify a domain).
        self.driver.get('http://localhost:19150/not-a-place')

        self.driver.add_cookie({
            'name': settings.SESSION_COOKIE_NAME,
            'value': auth.SESSION_SUPER_KEY if superuser else auth.SESSION_KEY,
            'secure': False,
            'path': '/',
        })

        self.driver.refresh() 
Example #6
Source File: middleware.py    From django-cookies-samesite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.protected_cookies = get_config_setting(
            "SESSION_COOKIE_SAMESITE_KEYS", set()
        )

        if not isinstance(self.protected_cookies, (list, set, tuple)):
            raise ValueError(
                "SESSION_COOKIE_SAMESITE_KEYS should be a list, set or tuple."
            )

        self.protected_cookies = set(self.protected_cookies)
        self.protected_cookies |= {
            settings.SESSION_COOKIE_NAME,
            settings.CSRF_COOKIE_NAME,
        }

        samesite_flag = get_config_setting("SESSION_COOKIE_SAMESITE", "")
        self.samesite_flag = (
            str(samesite_flag).capitalize() if samesite_flag is not None else ""
        )
        self.samesite_force_all = get_config_setting(
            "SESSION_COOKIE_SAMESITE_FORCE_ALL"
        )

        return super(CookiesSameSite, self).__init__(*args, **kwargs) 
Example #7
Source File: account.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)

        messages.success(self.request, _('You have been successfully logged out.'))
        # By default, logging out will generate a fresh sessionid cookie. We want to use the
        # absence of sessionid as an indication that front-end pages are being viewed by a
        # non-logged-in user and are therefore cacheable, so we forcibly delete the cookie here.
        response.delete_cookie(
            settings.SESSION_COOKIE_NAME,
            domain=settings.SESSION_COOKIE_DOMAIN,
            path=settings.SESSION_COOKIE_PATH
        )

        # HACK: pretend that the session hasn't been modified, so that SessionMiddleware
        # won't override the above and write a new cookie.
        self.request.session.modified = False

        return response 
Example #8
Source File: funcselenium.py    From django-functest with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_session(self):
        session_cookie = self._driver.get_cookie(settings.SESSION_COOKIE_NAME)
        if session_cookie is None:
            # Create new
            session = get_session_store()
            cookie_data = {'name': settings.SESSION_COOKIE_NAME,
                           'value': session.session_key,
                           'path': '/',
                           'secure': False,
                           }
            if self._driver.name == 'phantomjs':
                # Not sure why this is needed, but it seems to do the trick
                cookie_data['domain'] = '.localhost'

            self._add_cookie(cookie_data)
        else:
            session = get_session_store(session_key=session_cookie['value'])
        return session 
Example #9
Source File: test_middleware.py    From django-qsessions with MIT License 6 votes vote down vote up
def test_modify_session(client, logged_in):
    if logged_in:
        user = User.objects.create_superuser("user", "", "secret")
        client.force_login(user)
    else:
        user = None

    client.get("/read_session/", HTTP_USER_AGENT="TestUA/1.1")
    client.get("/modify_session/", HTTP_USER_AGENT="TestUA/1.1")
    data = json.loads(client.get("/read_session/", HTTP_USER_AGENT="TestUA/1.1").content.decode("UTF-8"))
    assert data["FOO"] == "BAR"
    assert data[USER_AGENT_SESSION_KEY] == "TestUA/1.1"
    if user:
        assert str(data[SESSION_KEY]) == str(user.id)

    assert settings.SESSION_COOKIE_NAME in client.cookies
    session = Session.objects.get(pk=client.cookies[settings.SESSION_COOKIE_NAME].value)
    assert session.user_agent == "TestUA/1.1"
    assert session.ip == "127.0.0.1"
    assert session.user == user 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_no_httponly_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], '')
        self.assertNotIn(
            cookies.Morsel._reserved['httponly'],
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        ) 
Example #11
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_session_delete_on_end(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header looks like:
        #  Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
        self.assertEqual(
            'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
            'Max-Age=0; Path=/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        ) 
Example #12
Source File: utils.py    From edx-proctoring with GNU Affero General Public License v3.0 5 votes vote down vote up
def login_user(self, user):
        """
        Login as specified user, does not depend on auth backend (hopefully)

        This is based on Client.login() with a small hack that does not
        require the call to authenticate()
        """
        user.backend = "django.contrib.auth.backends.ModelBackend"
        engine = import_module(settings.SESSION_ENGINE)

        # Create a fake request to store login details.
        request = HttpRequest()

        request.session = engine.SessionStore()
        login(request, user)

        # Set the cookie to represent the session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data)

        # Save the session values.
        request.session.save() 
Example #13
Source File: test_views.py    From devops with MIT License 5 votes vote down vote up
def setup_session(client):
    assert apps.is_installed("django.contrib.sessions"), "sessions not installed"
    engine = import_module(settings.SESSION_ENGINE)
    cookie = client.cookies.get(settings.SESSION_COOKIE_NAME, None)
    if cookie:
        return engine.SessionStore(cookie.value)
    s = engine.SessionStore()
    s.save()
    client.cookies[settings.SESSION_COOKIE_NAME] = s.session_key
    return s 
Example #14
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_clearsessions_command(self):
        """
        Test clearsessions command for clearing expired sessions.
        """
        storage_path = self.backend._get_storage_path()
        file_prefix = settings.SESSION_COOKIE_NAME

        def count_sessions():
            return len([
                session_file for session_file in os.listdir(storage_path)
                if session_file.startswith(file_prefix)
            ])

        self.assertEqual(0, count_sessions())

        # One object in the future
        self.session['foo'] = 'bar'
        self.session.set_expiry(3600)
        self.session.save()

        # One object in the past
        other_session = self.backend()
        other_session['foo'] = 'bar'
        other_session.set_expiry(-3600)
        other_session.save()

        # One object in the present without an expiry (should be deleted since
        # its modification time + SESSION_COOKIE_AGE will be in the past when
        # clearsessions runs).
        other_session2 = self.backend()
        other_session2['foo'] = 'bar'
        other_session2.save()

        # Three sessions are in the filesystem before clearsessions...
        self.assertEqual(3, count_sessions())
        management.call_command('clearsessions')
        # ... and two are deleted.
        self.assertEqual(1, count_sessions()) 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_session_delete_on_end_with_custom_domain_and_path(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header with a custom domain and path looks like:
        #  Set-Cookie: sessionid=; Domain=.example.local;
        #              expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0;
        #              Path=/example/
        self.assertEqual(
            'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, '
            '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        ) 
Example #16
Source File: file.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, session_key=None):
        self.storage_path = type(self)._get_storage_path()
        self.file_prefix = settings.SESSION_COOKIE_NAME
        super(SessionStore, self).__init__(session_key) 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_secure_session_cookie(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Simulate a request the modifies the session
        middleware.process_request(request)
        request.session['hello'] = 'world'

        # Handle the response through the middleware
        response = middleware.process_response(request, response)
        self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['secure'], True) 
Example #18
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_login_session_without_hash_session_key(self):
        """
        Session without django.contrib.auth.HASH_SESSION_KEY should login
        without an exception.
        """
        user = User.objects.get(username='testclient')
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()
        session[SESSION_KEY] = user.id
        session.save()
        original_session_key = session.session_key
        self.client.cookies[settings.SESSION_COOKIE_NAME] = original_session_key

        self.login()
        self.assertNotEqual(original_session_key, self.client.session.session_key) 
Example #19
Source File: test_views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_logout_preserve_language(self):
        """Language stored in session is preserved after logout"""
        # Create a new session with language
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()
        session[LANGUAGE_SESSION_KEY] = 'pl'
        session.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = session.session_key

        self.client.get('/logout/')
        self.assertEqual(self.client.session[LANGUAGE_SESSION_KEY], 'pl') 
Example #20
Source File: middleware.py    From python2017 with MIT License 5 votes vote down vote up
def process_request(self, request):
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
        request.session = self.SessionStore(session_key) 
Example #21
Source File: client.py    From python2017 with MIT License 5 votes vote down vote up
def _login(self, user, backend=None):
        from django.contrib.auth import login
        engine = import_module(settings.SESSION_ENGINE)

        # Create a fake request to store login details.
        request = HttpRequest()

        if self.session:
            request.session = self.session
        else:
            request.session = engine.SessionStore()
        login(request, user, backend)

        # Save the session values.
        request.session.save()

        # Set the cookie to represent the session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data) 
Example #22
Source File: client.py    From python2017 with MIT License 5 votes vote down vote up
def session(self):
        """
        Obtains the current session variables.
        """
        engine = import_module(settings.SESSION_ENGINE)
        cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
        if cookie:
            return engine.SessionStore(cookie.value)

        session = engine.SessionStore()
        session.save()
        self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key
        return session 
Example #23
Source File: test_view.py    From edx-enterprise with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_post_not_logged_in(self):
        assert settings.SESSION_COOKIE_NAME not in self.client.cookies  # precondition check - no session cookie

        response = self.client.post(self.view_url, data={})

        assert response.status_code == 302 
Example #24
Source File: requestnegotiation.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def anonymize_response(self, request, response):
        """ anonymizes a response by deleting cookies for users
            that are not logged in
        """
        if not request.user.is_authenticated:
            if settings.SESSION_COOKIE_NAME in request.COOKIES:
                response.delete_cookie(
                    settings.SESSION_COOKIE_NAME,
                    path=settings.SESSION_COOKIE_PATH,
                    domain=settings.SESSION_COOKIE_DOMAIN,
                )
        return response 
Example #25
Source File: file.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, session_key=None):
        self.storage_path = type(self)._get_storage_path()
        self.file_prefix = settings.SESSION_COOKIE_NAME
        super(SessionStore, self).__init__(session_key) 
Example #26
Source File: middleware.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def process_response(self, request, response):
        """
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie or delete
        the session cookie if the session has been emptied.
        """
        try:
            accessed = request.session.accessed
            modified = request.session.modified
            empty = request.session.is_empty()
        except AttributeError:
            pass
        else:
            # First check if we need to delete this cookie.
            # The session should be deleted only if the session is entirely empty
            if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
                response.delete_cookie(settings.SESSION_COOKIE_NAME,
                    domain=settings.SESSION_COOKIE_DOMAIN)
            else:
                if accessed:
                    patch_vary_headers(response, ('Cookie',))
                if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
                    if request.session.get_expire_at_browser_close():
                        max_age = None
                        expires = None
                    else:
                        max_age = request.session.get_expiry_age()
                        expires_time = time.time() + max_age
                        expires = cookie_date(expires_time)
                    # Save the session data and refresh the client cookie.
                    # Skip session save for 500 responses, refs #3881.
                    if response.status_code != 500:
                        request.session.save()
                        response.set_cookie(settings.SESSION_COOKIE_NAME,
                                request.session.session_key, max_age=max_age,
                                expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
                                path=settings.SESSION_COOKIE_PATH,
                                secure=settings.SESSION_COOKIE_SECURE or None,
                                httponly=settings.SESSION_COOKIE_HTTPONLY or None)
        return response 
Example #27
Source File: middleware.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def process_request(self, request):
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
        request.session = self.SessionStore(session_key) 
Example #28
Source File: client.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _login(self, user):
        from django.contrib.auth import login
        engine = import_module(settings.SESSION_ENGINE)

        # Create a fake request to store login details.
        request = HttpRequest()

        if self.session:
            request.session = self.session
        else:
            request.session = engine.SessionStore()
        login(request, user)

        # Save the session values.
        request.session.save()

        # Set the cookie to represent the session.
        session_cookie = settings.SESSION_COOKIE_NAME
        self.cookies[session_cookie] = request.session.session_key
        cookie_data = {
            'max-age': None,
            'path': '/',
            'domain': settings.SESSION_COOKIE_DOMAIN,
            'secure': settings.SESSION_COOKIE_SECURE or None,
            'expires': None,
        }
        self.cookies[session_cookie].update(cookie_data) 
Example #29
Source File: client.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def _session(self):
        """
        Obtains the current session variables.
        """
        if apps.is_installed('django.contrib.sessions'):
            engine = import_module(settings.SESSION_ENGINE)
            cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
            if cookie:
                return engine.SessionStore(cookie.value)
            else:
                s = engine.SessionStore()
                s.save()
                self.cookies[settings.SESSION_COOKIE_NAME] = s.session_key
                return s
        return {} 
Example #30
Source File: client.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        session = import_module(settings.SESSION_ENGINE).SessionStore()
        session_cookie = self.cookies.get(settings.SESSION_COOKIE_NAME)
        if session_cookie:
            session.delete(session_key=session_cookie.value)
        self.cookies = SimpleCookie()