Repository navigation
[ENG-12611] Admin auth middleware #11989
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
brianjgeiger
merged 2 commits into
CenterForOpenScience:feature/pbs-26-20
from
adlius:admin-auth-middleware
Oct 29, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| from django.contrib.auth.views import redirect_to_login | ||
| from django.core.exceptions import PermissionDenied | ||
| from django.urls import reverse | ||
|
|
||
|
|
||
| class AdminLoginRequiredMiddleware: | ||
| """Require an active staff user for every admin view not marked with ``login_not_required``. | ||
| Anonymous users are sent to the admin login page; signed-in users who aren't staff get a 403. | ||
| """ | ||
|
|
||
| def __init__(self, get_response): | ||
| self.get_response = get_response | ||
|
|
||
| def __call__(self, request): | ||
| return self.get_response(request) | ||
|
|
||
| def process_view(self, request, view_func, view_args, view_kwargs): | ||
| if not getattr(view_func, 'login_required', True): | ||
| return None | ||
| if not request.user.is_authenticated: | ||
| return redirect_to_login(request.get_full_path(), reverse('auth:login')) | ||
| if not request.user.is_staff: | ||
| raise PermissionDenied | ||
| return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import pytest | ||
| from django.contrib.auth.models import AnonymousUser, Permission | ||
| from django.contrib.contenttypes.models import ContentType | ||
| from django.core.exceptions import PermissionDenied | ||
| from django.test import RequestFactory | ||
| from django.urls import resolve, reverse | ||
|
|
||
| from admin.base import settings as admin_settings | ||
| from admin.base.middleware import AdminLoginRequiredMiddleware | ||
| from admin.common_auth.views import LoginView | ||
| from admin_tests.utilities import all_admin_views, as_view_func, protected_views, public_views | ||
| from osf.models import AbstractNode, OSFUser | ||
| from osf_tests.factories import AuthUserFactory | ||
|
|
||
| pytestmark = pytest.mark.django_db | ||
|
|
||
| LOGIN_REDIRECT_PREFIX = f"{reverse('auth:login', urlconf='admin.base.urls')}?next=" | ||
|
|
||
|
|
||
| def process_view(view_func, user): | ||
| request = RequestFactory().get('/fake_path') | ||
| request.user = user | ||
| middleware = AdminLoginRequiredMiddleware(lambda r: None) | ||
| return middleware.process_view(request, view_func, (), {}) | ||
|
|
||
|
|
||
| def staff_user(**kwargs): | ||
| user = AuthUserFactory(**kwargs) | ||
| user.is_staff = True | ||
| user.save() | ||
| return user | ||
|
|
||
|
|
||
| @pytest.mark.urls('admin.base.urls') | ||
| class TestAdminLoginRequiredMiddleware: | ||
|
|
||
| @pytest.mark.parametrize('view', protected_views()) | ||
| def test_anonymous_user_is_sent_to_login(self, view): | ||
| response = process_view(as_view_func(view), AnonymousUser()) | ||
| assert response.status_code == 302 | ||
| assert response.url.startswith(LOGIN_REDIRECT_PREFIX) | ||
|
|
||
| @pytest.mark.parametrize('view', protected_views()) | ||
| def test_non_staff_user_is_denied(self, view): | ||
| with pytest.raises(PermissionDenied): | ||
| process_view(as_view_func(view), OSFUser(is_active=True, is_staff=False)) | ||
|
|
||
| def test_staff_user_passes(self): | ||
| assert process_view(resolve('/nodes/').func, staff_user()) is None | ||
|
|
||
| def test_django_admin_site_requires_login(self): | ||
| response = process_view(resolve('/admin/').func, AnonymousUser()) | ||
| assert response.status_code == 302 | ||
| assert response.url.startswith(LOGIN_REDIRECT_PREFIX) | ||
|
|
||
| def test_login_is_public(self): | ||
| assert process_view(as_view_func(LoginView), AnonymousUser()) is None | ||
|
|
||
| def test_only_login_is_public(self): | ||
| public = {view for view in all_admin_views() if not getattr(as_view_func(view), 'login_required', True)} | ||
| assert public == public_views() | ||
|
|
||
|
|
||
| @pytest.mark.urls('admin.base.urls') | ||
| class TestAdminLoginRequiredMiddlewareEnabled: | ||
| """ | ||
| Each request gets a different response from /nodes/ without AdminLoginRequiredMiddleware: the view itself | ||
| returns 403 to anonymous users and lets in a non-staff user who holds osf.view_node. | ||
| """ | ||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def admin_middleware(self, settings): | ||
| settings.MIDDLEWARE = admin_settings.MIDDLEWARE | ||
|
|
||
| def test_middleware_is_in_admin_settings(self): | ||
| middleware = list(admin_settings.MIDDLEWARE) | ||
| assert 'admin.base.middleware.AdminLoginRequiredMiddleware' in middleware | ||
|
|
||
| def test_anonymous_request_is_redirected_to_login(self, client): | ||
| response = client.get('/nodes/') | ||
| assert response.status_code == 302 | ||
| assert response.url == f'{LOGIN_REDIRECT_PREFIX}/nodes/' | ||
|
|
||
| def test_non_staff_request_is_denied(self, client): | ||
| user = AuthUserFactory() | ||
| user.user_permissions.add(Permission.objects.get( | ||
| codename='view_node', | ||
| content_type=ContentType.objects.get_for_model(AbstractNode), | ||
| )) | ||
| client.force_login(user) | ||
| response = client.get('/nodes/') | ||
| assert response.status_code == 403 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of this, should we use the information from https://github.com/CenterForOpenScience/osf.io/pull/11989/changes#diff-96ba09f60ecd239a0ddc3a3c4c50ebb990141852057b3c8059a736ce11421676R45 to determine the public views, so we know those lists are synchronized?
From a practical perspective, it shouldn't matter too much, because this list will have to be updated to get tests to pass if a view is added that's unprotected, so we could let it through as is. Thoughts?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we add a view that is marked as a public view by accident, then the test would fail. If we make this getter fetch public views automatically, then it would rely on the
login_requiredattribute of the view, which could be something done by mistake.