healthchecks/hc/accounts/tests/test_remote_user_header_login.py
Shea Polansky 54a95a0ee2
Add http header auth (#457)
* Add HTTP header authentiation backend/middleware

* Add docs for remote header auth

* Improve docs on external auth

* Add warning for unknown  REMOTE_USER_HEADER_TYPE

* Move active check for header auth to middleware
Add extra header type sanity check to the backend

* Add test cases for remote header login

* Improve header-based authentication

- remove the 'ID' mode
- add CustomHeaderBackend to AUTHENTICATION_BACKENDS conditionally
- rewrite CustomHeaderBackend and CustomHeaderMiddleware to
use less inherited code
- add more test cases

Co-authored-by: Pēteris Caune <cuu508@gmail.com>
2020-12-09 11:25:56 +02:00

57 lines
2.3 KiB
Python

from unittest.mock import patch
from django.contrib.auth.models import User
from django.test.utils import override_settings
from hc.test import BaseTestCase
@override_settings(
REMOTE_USER_HEADER="AUTH_USER",
AUTHENTICATION_BACKENDS=("hc.accounts.backends.CustomHeaderBackend",),
)
class RemoteUserHeaderTestCase(BaseTestCase):
@override_settings(REMOTE_USER_HEADER=None)
def test_it_does_nothing_when_not_configured(self):
r = self.client.get("/accounts/profile/", AUTH_USER="alice@example.org")
self.assertRedirects(r, "/accounts/login/?next=/accounts/profile/")
def test_it_logs_user_in(self):
r = self.client.get("/accounts/profile/", AUTH_USER="alice@example.org")
self.assertContains(r, "alice@example.org")
def test_it_does_nothing_when_header_not_set(self):
r = self.client.get("/accounts/profile/")
self.assertRedirects(r, "/accounts/login/?next=/accounts/profile/")
def test_it_does_nothing_when_header_is_empty_string(self):
r = self.client.get("/accounts/profile/", AUTH_USER="")
self.assertRedirects(r, "/accounts/login/?next=/accounts/profile/")
def test_it_creates_user(self):
r = self.client.get("/accounts/profile/", AUTH_USER="dave@example.org")
self.assertContains(r, "dave@example.org")
q = User.objects.filter(email="dave@example.org")
self.assertTrue(q.exists())
def test_it_logs_out_another_user_when_header_is_empty_string(self):
self.client.login(remote_user_email="bob@example.org")
r = self.client.get("/accounts/profile/", AUTH_USER="")
self.assertRedirects(r, "/accounts/login/?next=/accounts/profile/")
def test_it_logs_out_another_user(self):
self.client.login(remote_user_email="bob@example.org")
r = self.client.get("/accounts/profile/", AUTH_USER="alice@example.org")
self.assertContains(r, "alice@example.org")
def test_it_handles_already_logged_in_user(self):
self.client.login(remote_user_email="alice@example.org")
with patch("hc.accounts.middleware.auth") as mock_auth:
r = self.client.get("/accounts/profile/", AUTH_USER="alice@example.org")
self.assertFalse(mock_auth.authenticate.called)
self.assertContains(r, "alice@example.org")