예제 #1
0
def should_completely_remove_data_from_session_when_deleted():
    # Do an initial request, to add some data to the storage
    middleware = SessionMiddleware()
    request, response = factory.get('/'), HttpResponse('')
    middleware.process_request(request)
    storage = SessionStorage('name', 'namespace')
    storage.process_request(request)
    step = storage['step1']
    step.data = {'blarg': 'bloog'}
    storage.process_response(response)
    middleware.process_response(request, response)

    # Create a fake request, to ensure that the data was saved properly, and
    # then delete the stored data.
    request = factory.get('/')
    request.COOKIES.update(((k, v.value)
                            for k, v in response.cookies.iteritems()))
    middleware.process_request(request)
    assert 'namespace|name' in request.session
    # do the delete
    storage = SessionStorage('name', 'namespace')
    storage.process_request(request)
    storage.delete()
    response = HttpResponse('')
    storage.process_response(response)
    middleware.process_response(request, response)

    # Create another fake request, to ensure that the data is gone!
    request = factory.get('/')
    request.COOKIES.update(((k, v.value)
                            for k, v in response.cookies.iteritems()))
    middleware.process_request(request)
    assert 'namespace|name' not in request.session
예제 #2
0
def should_completely_remove_data_from_database_when_deleted():
    middleware = SessionMiddleware()

    # Do an initial request, to add some data to the storage
    request, response = factory.get('/'), HttpResponse('')
    middleware.process_request(request)
    # The session key isn't actually determined until the session is used (it's
    # all lazy), so we'll set some test data initially that we can then use
    # later.
    request.session['some other data'] = 'testing'
    storage = DatabaseStorage('name', 'namespace')
    storage.process_request(request)
    step = storage['step1']
    step.data = {'blarg': 'bloog'}
    storage.process_response(response)
    middleware.process_response(request, response)
    session_key = request.session.session_key  # save for later request
    assert WizardState.objects.filter(name='name', namespace='namespace').count() == 1

    # check deletion
    request = factory.get('/')
    request.COOKIES[settings.SESSION_COOKIE_NAME] = session_key  # use session
    middleware.process_request(request)
    storage = DatabaseStorage('name', 'namespace')
    storage.process_request(request)
    storage.delete()
    #storage.process_response(HttpResponse(''))
    assert WizardState.objects.filter(name='name', namespace='namespace').count() == 0
    assert request.session['some other data'] == 'testing'
예제 #3
0
파일: tests.py 프로젝트: nim65s/django
    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")
예제 #4
0
class SignedCookiesTest(TestCase):
    def setUp(self):
        self.middleware = SignedCookiesMiddleware()
        self.auth_middleware = AuthenticationMiddleware()
        self.session_middleware = SessionMiddleware()
        
    def _process_request(self, request):
        self.session_middleware.process_request(request)
        self.auth_middleware.process_request(request)
        self.middleware.process_request(request)
        
    def _process_response(self, request, response):
        self.middleware.process_response(request, response)
        self.session_middleware.process_response(request, response)
        
    def test_middleware(self):
        request = HttpRequest()
        
        request.COOKIES['key'] = 'foo'
        self._process_request(request)
        self.failIf('key' in request.COOKIES)
        
        response = HttpResponse()
        request = HttpRequest()
        self._process_request(request)
        response.set_cookie('key', 'foo')
        self._process_response(request, response)
        signed_val = response.cookies['key'].value
        self.failIfEqual(signed_val, 'foo')
        
        request.COOKIES['key'] = signed_val
        self._process_request(request)
        self.failUnlessEqual(request.COOKIES['key'], 'foo')
예제 #5
0
파일: tests.py 프로젝트: EmadMokhtar/django
    def test_session_delete_on_end(self):
        request = self.request_factory.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])
        )
        # SessionMiddleware sets 'Vary: Cookie' to prevent the 'Set-Cookie'
        # from being cached.
        self.assertEqual(response['Vary'], 'Cookie')
예제 #6
0
파일: tests.py 프로젝트: mattseymour/django
    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,
                '""' if sys.version_info >= (3, 5) else '',
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )
예제 #7
0
파일: tests.py 프로젝트: nim65s/django
    def test_session_delete_on_end_with_custom_domain(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)

        # Check that the cookie was deleted, not recreated.
        # A deleted cookie header with a custom domain looks like:
        #  Set-Cookie: sessionid=; Domain=.example.local;
        #              expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/
        self.assertEqual(
            "Set-Cookie: {}={}; Domain=.example.local; expires=Thu, "
            "01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/".format(
                settings.SESSION_COOKIE_NAME, '""' if sys.version_info >= (3, 5) else ""
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME]),
        )
예제 #8
0
파일: tests.py 프로젝트: GeyseR/django
    def test_session_delete_on_end_with_custom_domain_and_path(self):
        request = self.request_factory.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])
        )
예제 #9
0
파일: tests.py 프로젝트: GeyseR/django
 def test_samesite_session_cookie(self):
     request = self.request_factory.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')
예제 #10
0
파일: tests.py 프로젝트: GeyseR/django
    def test_session_update_error_redirect(self):
        path = '/foo/'
        request = self.request_factory.get(path)
        response = HttpResponse()
        middleware = SessionMiddleware()

        request.session = DatabaseSession()
        request.session.save(must_create=True)
        request.session.delete()

        msg = (
            "The request's session was deleted before the request completed. "
            "The user may have logged out in a concurrent request, for example."
        )
        with self.assertRaisesMessage(SuspiciousOperation, msg):
            # Handle the response through the middleware. It will try to save
            # the deleted session which will cause an UpdateError that's caught
            # and raised as a SuspiciousOperation.
            middleware.process_response(request, response)
예제 #11
0
파일: tests.py 프로젝트: GeyseR/django
    def test_secure_session_cookie(self):
        request = self.request_factory.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)
예제 #12
0
    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.assertTrue(response.cookies[settings.SESSION_COOKIE_NAME]["secure"])
예제 #13
0
파일: tests.py 프로젝트: GeyseR/django
    def test_empty_session_saved(self):
        """
        If a session is emptied of data but still has a key, it should still
        be updated.
        """
        request = self.request_factory.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')
예제 #14
0
    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.assertFalse(response.cookies[settings.SESSION_COOKIE_NAME]["httponly"])

        self.assertNotIn(http_cookies.Morsel._reserved["httponly"], str(response.cookies[settings.SESSION_COOKIE_NAME]))
예제 #15
0
파일: tests.py 프로젝트: 101studio/django
    def test_httponly_session_cookie(self):
        settings.SESSION_COOKIE_HTTPONLY = True

        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.assertTrue(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])
예제 #16
0
    def test_httponly_session_cookie(self):
        request = self.request_factory.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]))
예제 #17
0
    def test_secure_session_cookie(self):
        settings.SESSION_COOKIE_SECURE = True

        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.assertTrue(
            response.cookies[settings.SESSION_COOKIE_NAME]['secure'])
예제 #18
0
    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)

        # Check that the value wasn't saved above.
        self.assertNotIn("hello", request.session.load())
예제 #19
0
파일: tests.py 프로젝트: zizaipai/django
    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.assertFalse(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])

        self.assertNotIn('httponly',
                         str(response.cookies[settings.SESSION_COOKIE_NAME]))
예제 #20
0
파일: tests.py 프로젝트: zizaipai/django
    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)

        # Check that the value wasn't saved above.
        self.assertNotIn('hello', request.session.load())
예제 #21
0
파일: tests.py 프로젝트: GeyseR/django
    def test_session_save_on_500(self):
        request = self.request_factory.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())
예제 #22
0
파일: tests.py 프로젝트: mattseymour/django
    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.assertFalse(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])

        self.assertNotIn(cookies.Morsel._reserved['httponly'],
                         str(response.cookies[settings.SESSION_COOKIE_NAME]))
예제 #23
0
    def test_flush_empty_without_session_cookie_doesnt_set_cookie(self):
        request = self.request_factory.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')
예제 #24
0
    def test_session_update_error_redirect(self):
        path = '/foo/'
        request = RequestFactory().get(path)
        response = HttpResponse()
        middleware = SessionMiddleware()

        request.session = DatabaseSession()
        request.session.save(must_create=True)
        request.session.delete()

        # Handle the response through the middleware. It will try to save the
        # deleted session which will cause an UpdateError that's caught and
        # results in a redirect to the original page.
        response = middleware.process_response(request, response)

        # Check that the response is a redirect.
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], path)
예제 #25
0
    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)
        #if it isn't in the cookie, that's fine (Python 2.5). 
        if 'httponly' in settings.SESSION_COOKIE_NAME:
            self.assertFalse(
               response.cookies[settings.SESSION_COOKIE_NAME]['httponly'])

        self.assertNotIn('httponly', 
                         str(response.cookies[settings.SESSION_COOKIE_NAME]))
예제 #26
0
파일: tests.py 프로젝트: Alias4bb/django
    def test_session_update_error_redirect(self):
        path = '/foo/'
        request = RequestFactory().get(path)
        response = HttpResponse()
        middleware = SessionMiddleware()

        request.session = DatabaseSession()
        request.session.save(must_create=True)
        request.session.delete()

        # Handle the response through the middleware. It will try to save the
        # deleted session which will cause an UpdateError that's caught and
        # results in a redirect to the original page.
        response = middleware.process_response(request, response)

        # Check that the response is a redirect.
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['Location'], path)
예제 #27
0
class OauthSessionMiddleware(object):
    #TODO: сделать сессию переиспользуемой

    def __init__(self):
        self.header = "HTTP_AUTHORIZATION"
        self.session_middleware = SessionMiddleware()
        engine = import_module(settings.SESSION_ENGINE)
        self.SessionStore = engine.SessionStore

    def process_request(self, request):
        try:
            auth_header = request.META[self.header]
        except KeyError:
            return self.session_middleware.process_request(request)

        token = ''
        if auth_header.startswith('token'):
            auth_header_parts = auth_header.split()
            if len(auth_header_parts) < 2:
                return
            token = auth_header_parts[1]

        if not token:
            return self.session_middleware.process_request(request)

        request.session = self.SessionStore(session_key=token)

    def process_response(self, request, response):
        authorization = request.META.get('HTTP_AUTHORIZATION', None)
        if authorization:
            response['Authorization'] = authorization
        else:
            return self.session_middleware.process_response(request, response)

        try:
            modified = request.session.modified
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if response.status_code != 500:
                    request.session.save()
        except AttributeError:
            pass

        return response
예제 #28
0
class OauthSessionMiddleware(object):
    #TODO: сделать сессию переиспользуемой

    def __init__(self):
        self.header = "HTTP_AUTHORIZATION"
        self.session_middleware = SessionMiddleware()
        engine = import_module(settings.SESSION_ENGINE)
        self.SessionStore = engine.SessionStore

    def process_request(self, request):
        try:
            auth_header = request.META[self.header]
        except KeyError:
            return self.session_middleware.process_request(request)

        token = ''
        if auth_header.startswith('token'):
            auth_header_parts = auth_header.split()
            if len(auth_header_parts) < 2:
                return
            token = auth_header_parts[1]

        if not token:
            return self.session_middleware.process_request(request)

        request.session = self.SessionStore(session_key=token)

    def process_response(self, request, response):
        authorization = request.META.get('HTTP_AUTHORIZATION', None)
        if authorization:
            response['Authorization'] = authorization
        else:
            return self.session_middleware.process_response(request, response)

        try:
            modified = request.session.modified
            if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                if response.status_code != 500:
                    request.session.save()
        except AttributeError:
            pass

        return response
예제 #29
0
파일: tests.py 프로젝트: zizaipai/django
    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)

        # Check that 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: {0}=; 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]))
예제 #30
0
    def test_empty_session_saved(self):
        """
        If a session is emptied of data but still has a key, it should still
        be updated.
        """
        def response_set_session(request):
            # Set a session key and some data.
            request.session["foo"] = "bar"
            return HttpResponse("Session test")

        request = self.request_factory.get("/")
        middleware = SessionMiddleware(response_set_session)

        # Handle the response through the middleware.
        response = middleware(request)
        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.headers["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.headers["Vary"], "Cookie")
예제 #31
0
    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)

        # Check that 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]),
        )
예제 #32
0
class CookielessSessionMiddleware(object):
    """ Django snippets julio carlos and Ivscar 
        http://djangosnippets.org/snippets/1540/
        Plus django.session.middleware combined

        Install by replacing 
        'django.contrib.sessions.middleware.SessionMiddleware'
        with 'cookieless.middleware.CookielessSessionMiddleware'

        NB: Remember only decorated methods are cookieless
        cookieless sessions get the no_cookies = True key added
    """

    def __init__(self):
        """ Add regex for auto inserts and an instance of
            the standard django.contrib.sessions middleware
        """
        self.settings = getattr(settings, 'COOKIELESS', DEFAULT_SETTINGS)
        self._re_links = re.compile(LINKS_RE, re.I)
        self._re_forms = re.compile('</form>', re.I)
        self._re_body = re.compile('</body>', re.I)
        self._sesh = CryptSession()
        self.standard_session = SessionMiddleware()
        self.engine = import_module(settings.SESSION_ENGINE)


    def process_request(self, request):
        """ Check if we have the session key from a cookie, 
            if not check post, and get if allowed
            If decryption fails 
            (ie secret is wrong because of other setting restrictions)
            decrypt may not return a real key so
            test for that and start a new session if so
            NB: Use resolve to check view for no_cookies 
                - because its before view is processed
        """
        name = settings.SESSION_COOKIE_NAME
        session_key = ''
        match = resolve(request.path)
        no_cookies = False
        
        if match and getattr(match.func, 'no_cookies', False):
            no_cookies = True
            if request.POST:
                session_key = self._sesh.decrypt(request, 
                                                 request.POST.get(name, None))
            if not session_key and self.settings.get('USE_GET', False):
                session_key = self._sesh.decrypt(request, 
                                                 request.GET.get(name, ''))
        else:
            session_key = request.COOKIES.get(name, '')

        try:
            request.session = self.engine.SessionStore(session_key)
        except:
            pass
        # NB: engine may work but return empty key less session
        try:
            session_key = request.session.session_key
        except:
            session_key = ''

        # If the session_key isn't tied to a session - create a new one
        if not session_key:
            request.session = self.engine.SessionStore() 
            if no_cookies:
                request.session['no_cookies'] = True
                # Flag it here so we can send created session signal 
                # with data later on in process_response
                request.session['created_cookieless'] = True
            request.session.save()


    def process_response(self, request, response):
        """
        Copied from contrib.session.middleware with no_cookies switch added ...
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        NB: request.COOKIES are the sent ones and response.cookies the set ones!
        """
        if getattr(request, 'no_cookies', False):
            if request.COOKIES:
                if self.settings.get('NO_COOKIE_PERSIST', False):
                    # Don't persist a session with cookieless for any session 
                    # thats been set against a cookie 
                    # - may be attached to a user - so always start a new separate one
                    cookie_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, '')
                    if cookie_key == request.session.session_key:
                        request.session = self.engine.SessionStore()
                        request.session['no_cookies'] = True
                        request.session['created_cookieless'] = True
                        request.session.save()
                if self.settings.get('DELETE_COOKIES', False):
                    # Blat any existing cookies
                    for key in request.COOKIES.keys():
                        response.delete_cookie(key)

            # Dont set any new cookies
            if hasattr(response, 'cookies'):
                response.cookies.clear()

            # cookieless - do same as standard process response
            #              but dont set the cookie
            if self.settings.get('REWRITE', False):
                response = self.nocookies_response(request, response)
            # Check for created flag for signal and turn off
            created = request.session.get('created_cookieless', False)
            if created:
                request.session['created_cookieless'] = False
            try:
                # accessed = request.session.accessed
                modified = request.session.modified
            except AttributeError:
                pass
            else:
                if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                    try:
                        # Save the session data 
                        request.session.save()
                    except:
                        # Ensure all keys are strings - required by move to JSON serializer with 1.6
                        for key in request.session.keys():
                            if type(key) not in (type(''), type(u'')):
                                request.session[str(key)] = str(request.session[key])
                                del request.session[key]
                            #elif type(value) not in (type(''), type(u''), type(True)):
                            #    request.session[key] = str(request.session[key])
                        request.session.save()
                    cookieless_signal.send(sender=request, created=created)
            return response
        else:
            return self.standard_session.process_response(request, response)

    def nocookies_response(self, request, response):
        """ Option to rewrite forms and urls to add session automatically """
        name = settings.SESSION_COOKIE_NAME
        session_key = ''
        if request.session.session_key and \
           not request.path.startswith(self.settings.get('EXCLUDE_DIR', '/admin')):  
            session_key = self._sesh.encrypt(request, request.session.session_key) 

            if self.settings.get('USE_GET', False) and session_key:
                if type(response) is HttpResponseRedirect:
                    host = request.META.get('HTTP_HOST', 'localhost')
                    redirect_url = [x[1] for x in response.items() if x[0] == "Location"][0]
                    if redirect_url.find(host) > -1:
                        redirect_url = self._sesh.prepare_url(redirect_url)
                        return HttpResponseRedirect('%s%s=%s' % (redirect_url, name, 
                                                             session_key)) 
                    else:
                        return HttpResponseRedirect(redirect_url)

            def new_url(match):
                anchor_value = ""
                if match.groupdict().get("anchor"): 
                    anchor_value = match.groupdict().get("anchor")
                return_str = '<a%shref="%s%s=%s%s"%s>' % (
                                 match.groupdict()['pre_href'],
                                 self._sesh.prepare_url(match.groupdict()['in_href']),
                                 name,
                                 session_key,
                                 anchor_value,
                                 match.groupdict()['post_href']
                                 )
                return return_str                                 

            if self.settings.get('USE_GET', False):            
                try:
                    response.content = self._re_links.sub(new_url, response.content)
                except:
                    pass

            # Check in case response has already got a manual session_id inserted
            repl_form = '<input type="hidden" name="%s"' % name
            if hasattr(response, 'content') and response.content.find(repl_form) == -1:
                repl_form = '''%s value="%s" />
                               </form>''' % (repl_form, session_key)
                try:
                    response.content = self._re_forms.sub(repl_form, response.content)
                except:
                    pass
            
            return response
        else:
            return response
예제 #33
0
파일: views.py 프로젝트: pnhoang/osqa
def signup(request):
    #this view works through forum and mediawiki (using apache include virtual injection)
    if request.is_include_virtual and request.REQUEST.get('was_posted','false')=='true':
        POST_INCLUDE_VIRTUAL = True
        POST_DATA = request.GET
    else:
        POST_INCLUDE_VIRTUAL = False
        if request.method == 'POST':
            POST_DATA = request.POST
        else:
            POST_DATA = None

    if POST_DATA:
        form = RegisterForm(POST_DATA)
        if form.is_valid():
            data = form.cleaned_data
            login_name = data['login_name']
            password = data['password']
            first_name = data['first_name']
            last_name = data['last_name']
            screen_name = data['screen_name']
            user_title = data['user_title']
            email = data['email']
            next = data['next']

            #register mediawiki user
            user_real_name = u'%s %s' % (first_name,last_name)
            mwu = MWUser(
                           user_name=login_name,
                           user_first_name = first_name,
                           user_last_name = last_name,
                           user_title = user_title,
                           user_email = email,
                           user_real_name=user_real_name
                        )
            mwu.set_default_options()
            mwu.save()
            #password may need user id so reload it
            mwu = MWUser.objects.get(user_name = login_name)
            mwu.set_password_and_token(password)
            mwu.save()

            #create log message
            mwu_creation_log = Logging(
                                        log_type='newusers',
                                        log_action='create',
                                        log_timestamp=time.strftime(MW_TS),
                                        log_params=str(mwu.user_id),
                                        log_namespace=2,
                                        log_user=mwu,
                                        log_deleted=0,
                                        )
            mwu_creation_log.save()
            mwu_creation_log.show_in_recent_changes(ip=request.META['REMOTE_ADDR'])
            print 'creation log saved'

            #register local user
            User.objects.create_user(screen_name, email, password)
            u = authenticate(username=screen_name, password=password)
            login(request,u)
            u.mediawiki_user = mwu
            u.save()

            #save email feed settings
            subscribe = SimpleEmailSubscribeForm(POST_DATA)
            if subscribe.is_valid():
                subscribe.save(user=u)

            #save external login data
            eld = ExternalLoginData(external_username=login_name, user=u)
            eld.save()

            transaction.commit()#commit so that user becomes visible on the wiki side

            #check password through API and load MW HTTP header session data
            api.check_password(login_name,password)

            print 'wiki login worked'

            #create welcome message on the forum
            u.message_set.create(message=_('Welcome to the OSQA community!'))
            print 'about to send confirmation email'
            send_welcome_email(request, mwu, u)

            if POST_INCLUDE_VIRTUAL:
                questions = Question.objects.exclude(deleted=True, closed=True, answer_accepted=True)
                questions = questions.order_by('-last_activity_at')[:5]
                response = render_to_response('mediawiki/thanks_for_joining.html', \
                                            {
                                                'wiki_user':mwu,
                                                'user':u,
                                                'questions':questions,
                                            },
                                            context_instance = RequestContext(request))
                api.set_login_cookies(response, u)
                #call session middleware now to get the django login cookies
                from django.contrib.sessions.middleware import SessionMiddleware
                sm = SessionMiddleware()
                response = sm.process_response(request,response)
                cookies = response.cookies
                for c in cookies.values():
                    response.write(c.js_output())
            else:
                response = HttpResponseRedirect(next)
                api.set_login_cookies(response, u)

            #set cookies so that user is logged in in the wiki too
            transaction.commit()
            return response
    else:
        form = RegisterForm()

    transaction.commit()
    if request.is_include_virtual:
        template_name = 'mediawiki/mediawiki_signup_content.html'
    else:
        template_name = 'mediawiki/mediawiki_signup.html'
    return render_to_response(template_name,{'form':form},\
                            context_instance=RequestContext(request))
예제 #34
0
class CookielessSessionMiddleware:
    """ Django snippets julio carlos and Ivscar
        http://djangosnippets.org/snippets/1540/
        Plus django.session.middleware combined

        Install by replacing
        'django.contrib.sessions.middleware.SessionMiddleware'
        with 'cookieless.middleware.CookielessSessionMiddleware'

        NB: Remember only decorated methods are cookieless
        cookieless sessions get the no_cookies = True key added
    """
    def __init__(self, get_response=None):
        """ Add regex for auto inserts and an instance of
            the standard django.contrib.sessions middleware
        """
        self.settings = getattr(settings, "COOKIELESS", DEFAULT_SETTINGS)
        self._re_links = re.compile(LINKS_RE, re.I)
        self._re_forms = re.compile("</form>", re.I)
        self._re_body = re.compile("</body>", re.I)
        self._sesh = CryptSession()
        self.standard_session = SessionMiddleware()

        self.get_response = get_response
        engine = import_module(settings.SESSION_ENGINE)
        self.SessionStore = engine.SessionStore

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        self.process_request(request)
        response = self.get_response(request)
        # Code to be executed for each request/response after
        # the view is called.
        response = self.process_response(request, response)
        return response

    def process_request(self, request):
        """ Check if we have the session key from a cookie,
            if not check post, and get if allowed
            If decryption fails
            (ie secret is wrong because of other setting restrictions)
            decrypt may not return a real key so
            test for that and start a new session if so
            NB: Use resolve to check view for no_cookies
                - because its before view is processed
        """
        name = settings.SESSION_COOKIE_NAME
        session_key = ""
        match = resolve(request.path)
        no_cookies = False

        if match and getattr(match.func, "no_cookies", False):
            no_cookies = True
            if request.POST:
                session_key = self._sesh.decrypt(request,
                                                 request.POST.get(name, None))
            if not session_key and self.settings.get("USE_GET", False):
                session_key = self._sesh.decrypt(request,
                                                 request.GET.get(name, ""))
        else:
            session_key = request.COOKIES.get(name, "")

        try:
            request.session = self.SessionStore(session_key)
        except:
            pass
        # NB: engine may work but return empty key less session
        try:
            session_key = request.session.session_key
        except:
            session_key = ""

        # If the session_key isn't tied to a session - create a new one
        if not session_key:
            request.session = self.SessionStore()
            if no_cookies:
                request.session["no_cookies"] = True
                # Flag it here so we can send created session signal
                # with data later on in process_response
                request.session["created_cookieless"] = True
            self.session_save(request.session)

    def session_save(self, session):
        """Ensure all keys are strings - required by move to JSON serializer with 1.6"""
        for key in session.keys():
            if type(key) not in (type(""), type(u""), type(True)):
                session[str(key)] = str(session[key])
                del session[key]
        session.save()

    def process_response(self, request, response):
        """
        Copied from contrib.session.middleware with no_cookies switch added ...
        If request.session was modified, or if the configuration is to save the
        session every time, save the changes and set a session cookie.
        NB: request.COOKIES are the sent ones and response.cookies the set ones!
        """
        if getattr(request, "no_cookies", False):
            if request.COOKIES:
                if self.settings.get("NO_COOKIE_PERSIST", False):
                    # Don't persist a session with cookieless for any session
                    # thats been set against a cookie
                    # - may be attached to a user - so always start a new separate one
                    cookie_key = request.COOKIES.get(
                        settings.SESSION_COOKIE_NAME, "")
                    if cookie_key == request.session.session_key:
                        request.session = self.SessionStore()
                        request.session["no_cookies"] = True
                        request.session["created_cookieless"] = True
                        self.session_save(request.session)
                if self.settings.get("DELETE_COOKIES", False):
                    # Blat any existing cookies
                    for key in request.COOKIES.keys():
                        response.delete_cookie(key)

            # Dont set any new cookies
            if hasattr(response, "cookies"):
                response.cookies.clear()

            # cookieless - do same as standard process response
            #              but dont set the cookie
            if self.settings.get("REWRITE", False):
                response = self.nocookies_response(request, response)
            # Check for created flag for signal and turn off
            created = request.session.get("created_cookieless", False)
            if created:
                request.session["created_cookieless"] = False
            try:
                # accessed = request.session.accessed
                modified = request.session.modified
            except AttributeError:
                pass
            else:
                if modified or settings.SESSION_SAVE_EVERY_REQUEST:
                    self.session_save(request.session)
                    cookieless_signal.send(sender=request, created=created)
            return response
        else:
            return self.standard_session.process_response(request, response)

    def nocookies_response(self, request, response):
        """ Option to rewrite forms and urls to add session automatically """
        name = settings.SESSION_COOKIE_NAME
        session_key = ""
        if request.session.session_key and not request.path.startswith(
                self.settings.get("EXCLUDE_DIR", "/admin")):
            session_key = self._sesh.encrypt(request,
                                             request.session.session_key)

            if self.settings.get("USE_GET", False) and session_key:
                if type(response) is HttpResponseRedirect or type(
                        response) is django.http.response.HttpResponseRedirect:
                    host = request.META.get("HTTP_HOST", "localhost")
                    redirect_url = [
                        x[1] for x in response.items() if x[0] == "Location"
                    ][0]
                    if (redirect_url.find('https://') == 0
                            or redirect_url.find('http://') == 0
                            or redirect_url.find('//') == 0):
                        return HttpResponseRedirect(redirect_url)

                    redirect_url = self._sesh.prepare_url(redirect_url)
                    return HttpResponseRedirect(
                        "%s%s=%s" % (redirect_url, name, session_key))

            def new_url(match):
                anchor_value = ""
                if match.groupdict().get("anchor"):
                    anchor_value = match.groupdict().get("anchor")
                href_value = ""
                if match.groupdict().get("in_href"):
                    href_value = match.groupdict().get("in_href")

                if (href_value.find('https://') == 0
                        or href_value.find('http://') == 0
                        or href_value.find('//') == 0
                        or href_value.find('javascript:') == 0):
                    return_str = '<a%shref="%s"%s>' % (
                        match.groupdict()["pre_href"],
                        href_value,
                        match.groupdict()["post_href"],
                    )
                else:
                    return_str = '<a%shref="%s%s=%s%s"%s>' % (
                        match.groupdict()["pre_href"],
                        self._sesh.prepare_url(href_value),
                        name,
                        session_key,
                        anchor_value,
                        match.groupdict()["post_href"],
                    )

                return return_str

            if self.settings.get("USE_GET", False):
                try:
                    response.content = self._re_links.sub(
                        new_url, response.content.decode()).encode()
                except:
                    pass

            # Check in case response has already got a manual session_id inserted
            repl_form = '<input type="hidden" name="%s"' % name
            if (hasattr(response, "content")
                    and repl_form not in response.content.decode()):
                repl_form = """%s value="%s" />
                               </form>""" % (
                    repl_form,
                    session_key,
                )
                try:
                    response.content = self._re_forms.sub(
                        repl_form, response.content.decode()).encode()
                except:
                    pass
            response['Content-Length'] = len(response.content)
            return response
        else:
            response['Content-Length'] = len(response.content)
            return response