test_views.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. from django.contrib import auth
  5. from django.middleware.csrf import get_token, rotate_token
  6. from django.test.client import RequestFactory
  7. from django.utils import six
  8. from mock import Mock, patch
  9. from django_browserid import views
  10. from django_browserid.tests import mock_browserid, TestCase
  11. class JSONViewTests(TestCase):
  12. def test_http_method_not_allowed(self):
  13. class TestView(views.JSONView):
  14. def get(self, request, *args, **kwargs):
  15. return 'asdf'
  16. response = TestView().http_method_not_allowed()
  17. self.assertEqual(response.status_code, 405)
  18. self.assertTrue(set(['GET']).issubset(set(response['Allow'].split(', '))))
  19. self.assert_json_equals(response.content, {'error': 'Method not allowed.'})
  20. def test_http_method_not_allowed_allowed_methods(self):
  21. class GetPostView(views.JSONView):
  22. def get(self, request, *args, **kwargs):
  23. return 'asdf'
  24. def post(self, request, *args, **kwargs):
  25. return 'qwer'
  26. response = GetPostView().http_method_not_allowed()
  27. self.assertTrue(set(['GET', 'POST']).issubset(set(response['Allow'].split(', '))))
  28. class GetPostPutDeleteHeadView(views.JSONView):
  29. def get(self, request, *args, **kwargs):
  30. return 'asdf'
  31. def post(self, request, *args, **kwargs):
  32. return 'qwer'
  33. def put(self, request, *args, **kwargs):
  34. return 'qwer'
  35. def delete(self, request, *args, **kwargs):
  36. return 'qwer'
  37. def head(self, request, *args, **kwargs):
  38. return 'qwer'
  39. response = GetPostPutDeleteHeadView().http_method_not_allowed()
  40. expected_methods = set(['GET', 'POST', 'PUT', 'DELETE', 'HEAD'])
  41. actual_methods = set(response['Allow'].split(', '))
  42. self.assertTrue(expected_methods.issubset(actual_methods))
  43. class GetNextTests(TestCase):
  44. def setUp(self):
  45. self.factory = RequestFactory()
  46. def test_no_param(self):
  47. """If next isn't in the POST params, return None."""
  48. request = self.factory.post('/')
  49. self.assertEqual(views._get_next(request), None)
  50. def test_is_safe(self):
  51. """Return the value of next if it is considered safe."""
  52. request = self.factory.post('/', {'next': '/asdf'})
  53. request.get_host = lambda: 'myhost'
  54. with patch.object(views, 'is_safe_url', return_value=True) as is_safe_url:
  55. self.assertEqual(views._get_next(request), '/asdf')
  56. is_safe_url.assert_called_with('/asdf', host='myhost')
  57. def test_isnt_safe(self):
  58. """If next isn't safe, return None."""
  59. request = self.factory.post('/', {'next': '/asdf'})
  60. request.get_host = lambda: 'myhost'
  61. with patch.object(views, 'is_safe_url', return_value=False) as is_safe_url:
  62. self.assertEqual(views._get_next(request), None)
  63. is_safe_url.assert_called_with('/asdf', host='myhost')
  64. class VerifyTests(TestCase):
  65. def setUp(self):
  66. self.factory = RequestFactory()
  67. def verify(self, request_type, **kwargs):
  68. """
  69. Call the verify view function. Kwargs are passed as GET or POST
  70. arguments.
  71. """
  72. if request_type == 'get':
  73. request = self.factory.get('/browserid/verify', kwargs)
  74. else:
  75. request = self.factory.post('/browserid/verify', kwargs)
  76. verify_view = views.Verify.as_view()
  77. with patch.object(auth, 'login'):
  78. response = verify_view(request)
  79. return response
  80. def test_no_assertion(self):
  81. """If no assertion is given, return a failure result."""
  82. with self.settings(LOGIN_REDIRECT_URL_FAILURE='/fail'):
  83. response = self.verify('post', blah='asdf')
  84. self.assertEqual(response.status_code, 403)
  85. self.assert_json_equals(response.content, {'redirect': '/fail'})
  86. @mock_browserid(None)
  87. def test_auth_fail(self):
  88. """If authentication fails, redirect to the failure URL."""
  89. with self.settings(LOGIN_REDIRECT_URL_FAILURE='/fail'):
  90. response = self.verify('post', assertion='asdf')
  91. self.assertEqual(response.status_code, 403)
  92. self.assert_json_equals(response.content, {'redirect': '/fail'})
  93. @mock_browserid(None)
  94. def test_auth_fail_named_url(self):
  95. """
  96. If authentication fails, redirect to the failure URL, and resolve
  97. named URLs.
  98. """
  99. with self.settings(LOGIN_REDIRECT_URL_FAILURE='test_url'):
  100. response = self.verify('post', assertion='asdf')
  101. self.assertEqual(response.status_code, 403)
  102. self.assert_json_equals(response.content, {'redirect': '/some-dummy-url/'})
  103. @mock_browserid('test@example.com')
  104. def test_auth_success_redirect_success(self):
  105. """If authentication succeeds, redirect to the success URL."""
  106. user = auth.models.User.objects.create_user('asdf', 'test@example.com')
  107. request = self.factory.post('/browserid/verify', {'assertion': 'asdf'})
  108. with self.settings(LOGIN_REDIRECT_URL='/success'):
  109. with patch('django_browserid.views.auth.login') as login:
  110. verify = views.Verify.as_view()
  111. response = verify(request)
  112. login.assert_called_with(request, user)
  113. self.assertEqual(response.status_code, 200)
  114. self.assert_json_equals(response.content,
  115. {'email': 'test@example.com', 'redirect': '/success'})
  116. @mock_browserid('test@example.com')
  117. def test_auth_success_redirect_success_named_url(self):
  118. """
  119. If authentication succeeds, redirect to the success URL, and resolve
  120. named urls.
  121. """
  122. user = auth.models.User.objects.create_user('asdf', 'test@example.com')
  123. request = self.factory.post('/browserid/verify', {'assertion': 'asdf'})
  124. with self.settings(LOGIN_REDIRECT_URL='test_url'):
  125. with patch('django_browserid.views.auth.login') as login:
  126. verify = views.Verify.as_view()
  127. response = verify(request)
  128. self.assertEqual(response.status_code, 200)
  129. self.assert_json_equals(response.content,
  130. {'email': 'test@example.com', 'redirect': '/some-dummy-url/'})
  131. def test_sanity_checks(self):
  132. """Run sanity checks on all incoming requests."""
  133. with patch('django_browserid.views.sanity_checks') as sanity_checks:
  134. self.verify('post')
  135. self.assertTrue(sanity_checks.called)
  136. @patch('django_browserid.views.auth.login')
  137. def test_login_success_no_next(self, *args):
  138. """
  139. If _get_next returns None, use success_url for the redirect
  140. parameter.
  141. """
  142. view = views.Verify()
  143. view.request = self.factory.post('/')
  144. view.user = Mock(email='a@b.com')
  145. with patch('django_browserid.views._get_next', return_value=None) as _get_next:
  146. with patch.object(views.Verify, 'success_url', '/?asdf'):
  147. response = view.login_success()
  148. self.assert_json_equals(response.content, {'email': 'a@b.com', 'redirect': '/?asdf'})
  149. _get_next.assert_called_with(view.request)
  150. @patch('django_browserid.views.auth.login')
  151. def test_login_success_next(self, *args):
  152. """
  153. If _get_next returns a URL, use it for the redirect parameter.
  154. """
  155. view = views.Verify()
  156. view.request = self.factory.post('/')
  157. view.user = Mock(email='a@b.com')
  158. with patch('django_browserid.views._get_next', return_value='/?qwer') as _get_next:
  159. with patch.object(views.Verify, 'success_url', '/?asdf'):
  160. response = view.login_success()
  161. self.assert_json_equals(response.content, {'email': 'a@b.com', 'redirect': '/?qwer'})
  162. _get_next.assert_called_with(view.request)
  163. class LogoutTests(TestCase):
  164. def setUp(self):
  165. self.factory = RequestFactory()
  166. _get_next_patch = patch('django_browserid.views._get_next')
  167. self._get_next = _get_next_patch.start()
  168. self.addCleanup(_get_next_patch.stop)
  169. def test_redirect(self):
  170. """Include LOGOUT_REDIRECT_URL in the response."""
  171. request = self.factory.post('/')
  172. logout = views.Logout.as_view()
  173. self._get_next.return_value = None
  174. with patch.object(views.Logout, 'redirect_url', '/test/foo'):
  175. with patch('django_browserid.views.auth.logout') as auth_logout:
  176. response = logout(request)
  177. auth_logout.assert_called_with(request)
  178. self.assertEqual(response.status_code, 200)
  179. self.assert_json_equals(response.content, {'redirect': '/test/foo'})
  180. def test_redirect_named_url(self):
  181. """
  182. Include LOGOUT_REDIRECT_URL in the response, and resolve named URLs.
  183. """
  184. request = self.factory.post('/')
  185. logout = views.Logout.as_view()
  186. self._get_next.return_value = None
  187. with self.settings(LOGOUT_REDIRECT_URL='test_url'):
  188. with patch('django_browserid.views.auth.logout') as auth_logout:
  189. response = logout(request)
  190. self.assertEqual(response.status_code, 200)
  191. self.assert_json_equals(response.content, {'redirect': '/some-dummy-url/'})
  192. def test_redirect_next(self):
  193. """
  194. If _get_next returns a URL, use it for the redirect parameter.
  195. """
  196. request = self.factory.post('/')
  197. logout = views.Logout.as_view()
  198. self._get_next.return_value = '/test/bar'
  199. with patch.object(views.Logout, 'redirect_url', '/test/foo'):
  200. with patch('django_browserid.views.auth.logout'):
  201. response = logout(request)
  202. self.assert_json_equals(response.content, {'redirect': '/test/bar'})
  203. class CsrfTokenTests(TestCase):
  204. def setUp(self):
  205. self.factory = RequestFactory()
  206. self.view = views.CsrfToken()
  207. def test_session_csrf(self):
  208. request = self.factory.get('/browserid/csrf/')
  209. request.csrf_token = 'asdf'
  210. response = self.view.get(request)
  211. self.assertEqual(response.status_code, 200)
  212. self.assertEqual(response.content, b'asdf')
  213. def test_django_csrf(self):
  214. request = self.factory.get('/browserid/csrf/')
  215. rotate_token(request)
  216. token = get_token(request)
  217. response = self.view.get(request)
  218. self.assertEqual(response.status_code, 200)
  219. self.assertEqual(response.content, six.b(token))
  220. def test_never_cache(self):
  221. request = self.factory.get('/browserid/csrf/')
  222. response = self.view.get(request)
  223. self.assertTrue('max-age=0' in response['Cache-Control'])