Python django.contrib.sessions.middleware.SessionMiddleware() Examples
The following are 30
code examples of django.contrib.sessions.middleware.SessionMiddleware().
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.sessions.middleware
, or try the search function
.
Example #1
Source File: tests.py From TWLight with MIT License | 6 votes |
def _get_request_with_session(self, data): """ Why the song-and-dance with middleware? Well. RequestFactory() lets us add a user to the request, e.g. in order to pass our ToURequired test, but doesn't let us access the session by default; Client() lets us see the session, but not add a user to the request. We need to pass our access test *and* see the session, so we need to: * use RequestFactory() to add a user to the request * invoke SessionMiddleware to bring the session into being * actually generate the response, so that form_valid is invoked, since that is where the session key is added If you were getting the sense that class-based views are sometimes hostile to unit testing, you were right. """ request = RequestFactory().post(self.url, data=data, follow=True) request.user = self.editor middleware = SessionMiddleware() middleware.process_request(request) request.session.save() _ = views.RequestApplicationView.as_view()(request) return request
Example #2
Source File: test_django_project_views.py From product-database with MIT License | 6 votes |
def test_login_ignore_next_login_link(self): url = reverse(self.URL_NAME) data = { "username": "api", "password": "api" } request = RequestFactory().post(url + "?next=/productdb/login", data=data) request.user = AnonymousUser() middleware = SessionMiddleware() middleware.process_request(request) request.session.save() response = views.login_user(request) assert response.status_code == 302 assert response.url == reverse("productdb:home"), "Should ignore the redirect to the login link"
Example #3
Source File: test_django_project_views.py From product-database with MIT License | 6 votes |
def test_login_default(self): url = reverse(self.URL_NAME) data = { "username": "api", "password": "api" } request = RequestFactory().post(url, data=data) request.user = AnonymousUser() middleware = SessionMiddleware() middleware.process_request(request) request.session.save() response = views.login_user(request) assert response.status_code == 302 assert response.url == reverse("productdb:home")
Example #4
Source File: test_django_project_views.py From product-database with MIT License | 6 votes |
def test_login_with_next_link(self): url = reverse(self.URL_NAME) data = { "username": "api", "password": "api" } request = RequestFactory().post(url + "?next=/xyz", data=data) request.user = AnonymousUser() middleware = SessionMiddleware() middleware.process_request(request) request.session.save() response = views.login_user(request) assert response.status_code == 302 assert response.url == "/xyz"
Example #5
Source File: test_django_project_views.py From product-database with MIT License | 6 votes |
def test_login_failed(self): url = reverse(self.URL_NAME) data = { "username": "api", "password": "invalid password" } request = RequestFactory().post(url, data=data) request.user = AnonymousUser() middleware = SessionMiddleware() middleware.process_request(request) request.session.save() response = views.login_user(request) assert response.status_code == 200 assert "Login failed, invalid credentials" in response.content.decode()
Example #6
Source File: test_models.py From django-request-token with MIT License | 6 votes |
def test_authenticate(self): factory = RequestFactory() middleware = SessionMiddleware() anon = AnonymousUser() request = factory.get("/foo") middleware.process_request(request) request.user = anon user1 = get_user_model().objects.create_user(username="Finbar") token = RequestToken.objects.create_token( user=user1, scope="foo", max_uses=10, login_mode=RequestToken.LOGIN_MODE_REQUEST, ) token.authenticate(request) self.assertEqual(request.user, user1) request.user = get_user_model().objects.create_user(username="Hyde") self.assertRaises(InvalidAudienceError, token.authenticate, request)
Example #7
Source File: tests.py From django-warrant with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_add_user_tokens_signal(self): User = get_user_model() user = User.objects.create(username=settings.COGNITO_TEST_USERNAME) user.access_token = 'access_token_value' user.id_token = 'id_token_value' user.refresh_token = 'refresh_token_value' user.backend = 'warrant.django.backend.CognitoBackend' user.api_key = 'abcdefg' user.api_key_id = 'ab-1234' request = RequestFactory().get('/login') middleware = SessionMiddleware() middleware.process_request(request) request.session.save() signals.user_logged_in.send(sender=user.__class__, request=request, user=user) self.assertEqual(request.session['ACCESS_TOKEN'], 'access_token_value') self.assertEqual(request.session['ID_TOKEN'], 'id_token_value') self.assertEqual(request.session['REFRESH_TOKEN'], 'refresh_token_value') self.assertEqual(request.session['API_KEY'], 'abcdefg') self.assertEqual(request.session['API_KEY_ID'], 'ab-1234')
Example #8
Source File: test_views.py From django-cas-ng with MIT License | 6 votes |
def test_logout_completely(django_user_model, settings): """ Test the case where the user logs out. """ settings.CAS_LOGOUT_COMPLETELY = True factory = RequestFactory() request = factory.get('/logout/') # Create a session object from the middleware process_request_for_middleware(request, SessionMiddleware) user = django_user_model.objects.create_user('test@example.com', '') assert user is not None request.user = user response = LogoutView().get(request) assert response.status_code == 302 assert request.user.is_anonymous is True
Example #9
Source File: test_views.py From django-cas-ng with MIT License | 6 votes |
def test_logout_not_completely(django_user_model, settings): """ Test the case where the user logs out, without the logout_completely flag. """ settings.CAS_LOGOUT_COMPLETELY = False factory = RequestFactory() request = factory.get('/logout/') # Create a session object from the middleware process_request_for_middleware(request, SessionMiddleware) user = django_user_model.objects.create_user('test@example.com', '') assert user is not None request.user = user response = LogoutView().get(request) assert response.status_code == 302 assert request.user.is_anonymous is True
Example #10
Source File: test_views.py From django-cas-ng with MIT License | 6 votes |
def test_login_no_ticket_stores_explicit_next(settings): """ When there is an explicit next pointer, it gets stored in the cookie """ settings.CAS_STORE_NEXT = True factory = RequestFactory() request = factory.get('/login/', {'next': '/admin/'}) # Create a session object from the middleware process_request_for_middleware(request, SessionMiddleware) # Create a user object from middleware process_request_for_middleware(request, AuthenticationMiddleware) response = LoginView().get(request) assert response.status_code == 302 assert 'CASNEXT' in request.session assert request.session['CASNEXT'] == '/admin/'
Example #11
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #12
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #13
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
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 #14
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_flush_empty_without_session_cookie_doesnt_set_cookie(self): request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # 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) # A cookie should not be set. self.assertEqual(response.cookies, {}) # The session is accessed so "Vary: Cookie" should be set. self.assertEqual(response['Vary'], 'Cookie')
Example #15
Source File: test_speedrun.py From donation-tracker with Apache License 2.0 | 6 votes |
def setUp(self): self.factory = RequestFactory() self.sessions = SessionMiddleware() self.messages = MessageMiddleware() self.event1 = models.Event.objects.create( datetime=today_noon, targetamount=5, timezone=pytz.timezone(getattr(settings, 'TIME_ZONE', 'America/Denver')), ) self.run1 = models.SpeedRun.objects.create( name='Test Run 1', run_time='0:45:00', setup_time='0:05:00', order=1 ) self.run2 = models.SpeedRun.objects.create( name='Test Run 2', run_time='0:15:00', setup_time='0:05:00', order=2 ) if not User.objects.filter(username='admin').exists(): User.objects.create_superuser('admin', 'nobody@example.com', 'password')
Example #16
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #17
Source File: test.py From Inboxen with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, user=None, session_id=None, has_otp=False, has_sudo=False): super(MockRequest, self).__init__() self.method = "GET" if user is None: self.user = AnonymousUser() else: self.user = user session = SessionMiddleware() self.session = session.SessionStore(session_id) self._messages = SessionStorage(self) self.META = {"REMOTE_ADDR": "127.0.0.1"} # sudo ElevateMiddleware(lambda x: x)(self) if has_sudo: grant_sudo(self) # otp if has_otp: grant_otp(self, self.user) OTPMiddleware(lambda x: x)(self) # TODO: submit to django-elevate?
Example #18
Source File: test_tags.py From astrobin with GNU Affero General Public License v3.0 | 5 votes |
def test_astrobin_image_tag_uses_hashed_url(self): request = RequestFactory().get("/") middleware = SessionMiddleware() middleware.process_request(request) request.session.save() context = { "request": request } image = Image.objects.create( user=User.objects.create( username="test", email="test@test.com", password="test", ), image_file=SimpleUploadedFile( name='test.jpg', content=open("astrobin/fixtures/test.jpg", 'rb').read(), content_type='image/jpeg') ) image.save() result = astrobin_image(context, image, "regular") self.assertEquals("/%s/" % image.hash, result["url"])
Example #19
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_samesite_session_cookie(self): request = RequestFactory().get('/') response = HttpResponse() middleware = SessionMiddleware() middleware.process_request(request) request.session['hello'] = 'world' response = middleware.process_response(request, response) self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict')
Example #20
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_session_save_on_500(self): request = RequestFactory().get('/') response = HttpResponse('Horrible error') response.status_code = 500 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) # The value wasn't saved above. self.assertNotIn('hello', request.session.load())
Example #21
Source File: test_views.py From hypha with BSD 3-Clause "New" or "Revised" License | 5 votes |
def dummy_request(self, path): request = RequestFactory().get(path) middleware = SessionMiddleware() middleware.process_request(request) request.session.save() request.user = StaffFactory() request._messages = FallbackStorage(request) return request
Example #22
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
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 #23
Source File: test_models.py From django-request-token with MIT License | 5 votes |
def test__auth_is_authenticated(self): factory = RequestFactory() middleware = SessionMiddleware() request = factory.get("/foo") middleware.process_request(request) user1 = get_user_model().objects.create_user(username="Jekyll") request.user = user1 # try default token token = RequestToken.objects.create_token( scope="foo", max_uses=10, login_mode=RequestToken.LOGIN_MODE_NONE ) request = token._auth_is_authenticated(request) self.assertEqual(request.user, user1) # try request token token = RequestToken.objects.create_token( user=user1, scope="foo", max_uses=10, login_mode=RequestToken.LOGIN_MODE_REQUEST, ) request = token._auth_is_authenticated(request) token.login_mode = RequestToken.LOGIN_MODE_SESSION request = token._auth_is_authenticated(request) self.assertEqual(request.user, user1) token.user = get_user_model().objects.create_user(username="Hyde") self.assertRaises(InvalidAudienceError, token._auth_is_authenticated, request) # anonymous user fails request.user = AnonymousUser() self.assertRaises(InvalidAudienceError, token._auth_is_authenticated, request)
Example #24
Source File: test_models.py From django-request-token with MIT License | 5 votes |
def test__auth_is_anonymous(self): factory = RequestFactory() middleware = SessionMiddleware() anon = AnonymousUser() request = factory.get("/foo") middleware.process_request(request) request.user = anon # try default token token = RequestToken.objects.create_token( scope="foo", max_uses=10, login_mode=RequestToken.LOGIN_MODE_NONE ) request = token._auth_is_anonymous(request) self.assertEqual(request.user, anon) # try request token user1 = get_user_model().objects.create_user(username="Finbar") token = RequestToken.objects.create_token( user=user1, scope="foo", max_uses=10, login_mode=RequestToken.LOGIN_MODE_REQUEST, ) token._auth_is_anonymous(request) self.assertEqual(request.user, user1) self.assertFalse(hasattr(token.user, "backend")) # try a session token logout(request) request.user = anon token.login_mode = RequestToken.LOGIN_MODE_SESSION request = token._auth_is_anonymous(request) self.assertEqual(request.user, user1) self.assertEqual( token.user.backend, "django.contrib.auth.backends.ModelBackend" ) # authenticated user fails request.user = user1 self.assertRaises(InvalidAudienceError, token._auth_is_anonymous, request)
Example #25
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_empty_session_saved(self): """ If a session is emptied of data but still has a key, it should still be updated. """ request = RequestFactory().get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Set a session key and some data. middleware.process_request(request) request.session['foo'] = 'bar' # Handle the response through the middleware. response = middleware.process_response(request, response) self.assertEqual(tuple(request.session.items()), (('foo', 'bar'),)) # A cookie should be set, along with Vary: Cookie. self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie') # Empty the session data. del request.session['foo'] # Handle the response through the middleware. response = HttpResponse('Session test') response = middleware.process_response(request, response) self.assertEqual(dict(request.session.values()), {}) session = Session.objects.get(session_key=request.session.session_key) self.assertEqual(session.get_decoded(), {}) # While the session is empty, it hasn't been flushed so a cookie should # still be set, along with Vary: Cookie. self.assertGreater(len(request.session.session_key), 8) self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie') # Don't need DB flushing for these tests, so can use unittest.TestCase as base class
Example #26
Source File: test_forms.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def test_customer(self): factory = RequestFactory() request = factory.get('/checkin/') request.user = AnonymousUser request = add_middleware_to_request(request, SessionMiddleware) #form = CustomerForm(request)
Example #27
Source File: test_views.py From django-cas-ng with MIT License | 5 votes |
def test_login_authenticate_do_not_create_user(monkeypatch, django_user_model, settings): """ Test the case where the login view authenticates a user, but does not create a user based on the CAS_CREATE_USER setting. """ # No need to test the message framework settings.CAS_CREATE_USER = False # No need to test the message framework settings.CAS_LOGIN_MSG = None # Make sure we use our backend settings.AUTHENTICATION_BACKENDS = ['django_cas_ng.backends.CASBackend'] # Json serializer was havinga hard time settings.SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' def mock_verify(ticket, service): return 'test@example.com', {'ticket': ticket, 'service': service}, None monkeypatch.setattr('cas.CASClientV2.verify_ticket', mock_verify) factory = RequestFactory() request = factory.get('/login/', {'ticket': 'fake-ticket', 'service': 'fake-service'}) # Create a session object from the middleware process_request_for_middleware(request, SessionMiddleware) # Create a user object from middleware process_request_for_middleware(request, AuthenticationMiddleware) with pytest.raises(PermissionDenied): LoginView().get(request) assert django_user_model.objects.filter(username='test@example.com').exists() is False
Example #28
Source File: api_views.py From django-rest-registration with MIT License | 5 votes |
def add_session_to_request(self, request): middleware = SessionMiddleware() middleware.process_request(request) request.session.save()
Example #29
Source File: base.py From django-rest-registration with MIT License | 5 votes |
def add_session_to_request(self, request): middleware = SessionMiddleware() middleware.process_request(request) request.session.save()
Example #30
Source File: auth_tests.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def save_session(request): middleware = SessionMiddleware() middleware.process_request(request) request.session.save()