Python django.conf.settings.SESSION_COOKIE_NAME Examples

The following are 30 code examples for showing how to use django.conf.settings.SESSION_COOKIE_NAME(). 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: django-qsessions   Author: QueraTeam   File: test_middleware.py    License: 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 2
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 3
Project: django-polaris   Author: stellar   File: middleware.py    License: 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
Project: dirigible-spreadsheet   Author: pythonanywhere   File: functionaltest.py    License: 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
Project: drf-to-s3   Author: metabolize   File: util.py    License: 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 6
Project: wagtail   Author: wagtail   File: account.py    License: 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 7
Project: credentials   Author: edx   File: mixins.py    License: 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 8
Project: django-functest   Author: django-functest   File: funcselenium.py    License: 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
Project: djongo   Author: nesdis   File: tests.py    License: 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 10
Project: djongo   Author: nesdis   File: tests.py    License: 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
Project: djongo   Author: nesdis   File: tests.py    License: 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
Project: coursys   Author: sfu-fas   File: testing.py    License: GNU General Public License v3.0 5 votes vote down vote up
def login_user(self, userid):
        """
        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()
        """
        if not 'django.contrib.sessions' in settings.INSTALLED_APPS:
            raise AssertionError("Unable to login without django.contrib.sessions in INSTALLED_APPS")
        try:
            user = User.objects.get(username=userid)
        except User.DoesNotExist:
            user = User(username=userid, password='')
            user.save()
        user.backend = "%s.%s" % ("django.contrib.auth.backends",
                                  "ModelBackend")
        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)

        # 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
Project: django-angularjs-blog   Author: bluedazzle   File: test_view_blog.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        classify = Classification.objects.create(c_name='test')
        self.art = Article.objects.create(caption='article',
                                          sub_caption='sub_article',
                                          classification=classify,
                                          content='article test',
                                          publish=True)
        settings.SESSION_ENGINE = 'django.contrib.sessions.backends.file'
        engine = import_module(settings.SESSION_ENGINE)
        store = engine.SessionStore()
        store.save()
        self.session = store
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key 
Example 14
Project: GTDWeb   Author: lanbing510   File: client.py    License: GNU General Public License v2.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, None)
            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 15
Project: GTDWeb   Author: lanbing510   File: client.py    License: GNU General Public License v2.0 5 votes vote down vote up
def login(self, **credentials):
        """
        Sets the Factory to appear as if it has successfully logged into a site.

        Returns True if login is possible; False if the provided credentials
        are incorrect, or the user is inactive, or if the sessions framework is
        not available.
        """
        from django.contrib.auth import authenticate, login
        user = authenticate(**credentials)
        if (user and user.is_active and
                apps.is_installed('django.contrib.sessions')):
            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)

            return True
        else:
            return False 
Example 16
Project: GTDWeb   Author: lanbing510   File: middleware.py    License: GNU General Public License v2.0 5 votes vote down vote up
def process_request(self, request):
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = self.SessionStore(session_key) 
Example 17
Project: GTDWeb   Author: lanbing510   File: middleware.py    License: GNU General Public License v2.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 18
Project: GTDWeb   Author: lanbing510   File: file.py    License: GNU General Public License v2.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 19
Project: django-qsessions   Author: QueraTeam   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_unmodified_session(client):
    client.get("/", HTTP_USER_AGENT="TestUA/1.1")
    assert settings.SESSION_COOKIE_NAME not in client.cookies 
Example 20
Project: django-qsessions   Author: QueraTeam   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_login(client):
    admin_login_url = reverse("admin:login")
    user = User.objects.create_superuser("user", "", "secret")
    response = client.post(
        admin_login_url,
        data={"username": "user", "password": "secret", "this_is_the_login_form": "1", "next": "/admin/"},
        HTTP_USER_AGENT="TestUA/1.1",
    )
    assert response.url == "/admin/"
    session = Session.objects.get(pk=client.cookies[settings.SESSION_COOKIE_NAME].value)
    assert user == session.user 
Example 21
Project: django-qsessions   Author: QueraTeam   File: test_admin.py    License: MIT License 5 votes vote down vote up
def test_smoke_admin(admin_client):
    admin_client.get("/modify_session/", HTTP_USER_AGENT="Chrome/70.0.3538.102", REMOTE_ADDR="89.160.20.112")
    resp = admin_client.get("/admin/qsessions/session/?active=1&owner=my")
    assert resp.status_code == 200
    content = resp.content.decode("UTF-8")
    assert "Linköping, Sweden" in content  # From REMOTE_ADDR
    assert "Chrome 70.0.3538" in content  # From HTTP_USER_AGENT
    resp = admin_client.get(
        "/admin/qsessions/session/%s/change/" % admin_client.cookies[settings.SESSION_COOKIE_NAME].value
    )
    assert "FOO" in resp.content.decode("UTF-8")  # Set by modify_session 
Example 22
Project: django-qsessions   Author: QueraTeam   File: middleware.py    License: 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(
            ip=get_client_ip(request)[0], user_agent=request.META.get("HTTP_USER_AGENT", ""), session_key=session_key,
        ) 
Example 23
Project: django-test-addons   Author: hspandher   File: utils.py    License: MIT License 5 votes vote down vote up
def create_session(self):
        session_engine = import_module(settings.SESSION_ENGINE)
        store = session_engine.SessionStore()
        store.save()
        self.client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key 
Example 24
Project: casepro   Author: rapidpro   File: perftest.py    License: BSD 3-Clause "New" or "Revised" License 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 25
Project: bioforum   Author: reBiocoder   File: client.py    License: MIT License 5 votes vote down vote up
def session(self):
        """Return 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 26
Project: bioforum   Author: reBiocoder   File: client.py    License: 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 27
Project: bioforum   Author: reBiocoder   File: middleware.py    License: 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 28
Project: bioforum   Author: reBiocoder   File: file.py    License: 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().__init__(session_key) 
Example 29
Project: aiohttp-json-rpc   Author: pengutronix   File: django.py    License: Apache License 2.0 5 votes vote down vote up
def login(self, request):
        try:
            username = str(request.params['username'])
            password = str(request.params['password'])

        except(KeyError, TypeError, ValueError):
            raise RpcInvalidParamsError

        user = authenticate(username=username, password=password)

        if not user:
            return False

        # to use the standard django login mechanism, which is build on the
        # request-, response-system, we have to fake a django http request
        fake_request = HttpRequest()
        fake_request.session = self.session_engine.SessionStore()
        django_login(fake_request, user)
        fake_request.session.save()

        # set session cookie
        request.http_request.ws.set_cookie(
            name=settings.SESSION_COOKIE_NAME,
            value=fake_request.session.session_key,
            path='/',
            max_age=None,
            domain=settings.SESSION_COOKIE_DOMAIN,
            secure=settings.SESSION_COOKIE_SECURE or None,
            expires=None,
        )

        # rediscover methods and topics
        self.prepare_request(request.http_request, user=user)

        return True

    # request processing 
Example 30
Project: zulip   Author: zulip   File: test_tornado.py    License: Apache License 2.0 5 votes vote down vote up
def login_user(self, *args: Any, **kwargs: Any) -> None:
        super().login_user(*args, **kwargs)
        session_cookie = settings.SESSION_COOKIE_NAME
        session_key = self.client.session.session_key
        self.session_cookie = {
            "Cookie": f"{session_cookie}={session_key}",
        }