You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.4 KiB

  1. from django.core import mail
  2. from django.core.signing import TimestampSigner
  3. from hc.test import BaseTestCase
  4. from hc.accounts.models import Credential
  5. from hc.api.models import TokenBucket
  6. class SudoModeTestCase(BaseTestCase):
  7. def setUp(self):
  8. super().setUp()
  9. self.c = Credential.objects.create(user=self.alice, name="Alices Key")
  10. self.url = f"/accounts/set_password/"
  11. def test_it_sends_code(self):
  12. self.client.login(username="[email protected]", password="password")
  13. r = self.client.get(self.url)
  14. self.assertContains(r, "We have sent a confirmation code")
  15. # A code should have been sent
  16. self.assertEqual(len(mail.outbox), 1)
  17. email = mail.outbox[0]
  18. self.assertEqual(email.to[0], "[email protected]")
  19. self.assertIn("Confirmation code", email.subject)
  20. def test_it_accepts_code(self):
  21. self.client.login(username="[email protected]", password="password")
  22. session = self.client.session
  23. session["sudo_code"] = TimestampSigner().sign("123456")
  24. session.save()
  25. r = self.client.post(self.url, {"sudo_code": "123456"})
  26. self.assertRedirects(r, self.url)
  27. # sudo mode should now be active
  28. self.assertIn("sudo", self.client.session)
  29. def test_it_rejects_incorrect_code(self):
  30. self.client.login(username="[email protected]", password="password")
  31. session = self.client.session
  32. session["sudo_code"] = TimestampSigner().sign("123456")
  33. session.save()
  34. r = self.client.post(self.url, {"sudo_code": "000000"})
  35. self.assertContains(r, "Not a valid code.")
  36. # sudo mode should *not* be active
  37. self.assertNotIn("sudo", self.client.session)
  38. def test_it_passes_through_if_sudo_mode_is_active(self):
  39. self.client.login(username="[email protected]", password="password")
  40. session = self.client.session
  41. session["sudo"] = TimestampSigner().sign("active")
  42. session.save()
  43. r = self.client.get(self.url)
  44. self.assertContains(r, "Please pick a password")
  45. def test_it_uses_rate_limiting(self):
  46. self.client.login(username="[email protected]", password="password")
  47. obj = TokenBucket(value=f"sudo-{self.alice.id}")
  48. obj.tokens = 0
  49. obj.save()
  50. r = self.client.get(self.url)
  51. self.assertContains(r, "Too Many Requests")