From 6c76439eb595c3ec4fd3a09fd59fa49d3ebbb680 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Fri, 16 Jul 2021 10:57:24 +0200 Subject: [PATCH 3/4] misc: block user without required_on_login attributes (#24056) Superuser are exempted from the restriction. --- src/authentic2/custom_user/models.py | 12 ++++++ src/authentic2/idp/saml/saml2_endpoints.py | 12 ++++++ src/authentic2/middleware.py | 18 ++++++++- .../authentic2/accounts_edit_required.html | 10 +++++ src/authentic2/urls.py | 1 + src/authentic2/views.py | 26 +++++++++++++ src/authentic2_auth_fc/views.py | 1 + src/authentic2_idp_cas/views.py | 1 + src/authentic2_idp_oidc/views.py | 3 ++ tests/middlewares/__init__.py | 0 .../test_required_on_login_restriction.py | 37 +++++++++++++++++++ tests/test_user_manager.py | 2 +- 12 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 src/authentic2/templates/authentic2/accounts_edit_required.html create mode 100644 tests/middlewares/__init__.py create mode 100644 tests/middlewares/test_required_on_login_restriction.py diff --git a/src/authentic2/custom_user/models.py b/src/authentic2/custom_user/models.py index c3f60f2e..711de9b5 100644 --- a/src/authentic2/custom_user/models.py +++ b/src/authentic2/custom_user/models.py @@ -400,6 +400,18 @@ class User(AbstractBaseUser, PermissionMixin): deleted_user.save() return super().delete(**kwargs) + def get_missing_required_on_login_attributes(self): + attributes = Attribute.objects.filter(required_on_login=True, disabled=False).order_by( + 'order', 'label' + ) + + missing = [] + for attribute in attributes: + value = getattr(self.attributes, attribute.name, None) + if not value: + missing.append(attribute) + return missing + class DeletedUser(models.Model): deleted = models.DateTimeField(verbose_name=_('Deletion date'), auto_now_add=True) diff --git a/src/authentic2/idp/saml/saml2_endpoints.py b/src/authentic2/idp/saml/saml2_endpoints.py index 2c4fd393..9059bca3 100644 --- a/src/authentic2/idp/saml/saml2_endpoints.py +++ b/src/authentic2/idp/saml/saml2_endpoints.py @@ -1126,6 +1126,9 @@ def finish_slo(request): return return_saml2_response(request, logout, title=_('You are being redirected to "%s"') % provider.name) +finish_slo.no_view_restriction = True + + def return_logout_error(request, logout, error): logout.buildResponseMsg() set_saml2_response_responder_status_code(logout.response, error) @@ -1445,6 +1448,9 @@ def slo(request): return a2_views.logout(request, next_url=next_url, do_local=False, check_referer=False) +slo.no_view_restriction = True + + def icon_url(name): return '%s/authentic2/images/%s.png' % (settings.STATIC_URL, name) @@ -1529,6 +1535,9 @@ def idp_slo(request, provider_id=None): return HttpResponseRedirect(logout.msgUrl) +idp_slo.no_view_restriction = True + + def process_logout_response(request, logout, soap_response, next): logger.debug('logout response is %r', soap_response) try: @@ -1570,6 +1579,9 @@ def slo_return(request): return process_logout_response(request, logout, get_saml2_query_request(request), next) +slo_return.no_view_restriction = True + + # Helpers # Mapping to generate the metadata file, must be kept in sync with the url diff --git a/src/authentic2/middleware.py b/src/authentic2/middleware.py index 3b0516a8..3dae2d95 100644 --- a/src/authentic2/middleware.py +++ b/src/authentic2/middleware.py @@ -126,6 +126,10 @@ class ViewRestrictionMiddleware(MiddlewareMixin): if view: return view + view = self.check_required_on_login_attribute_restriction(request, user) + if view: + return view + for plugin in plugins.get_plugins(): if hasattr(plugin, 'check_view_restrictions'): view = plugin.check_view_restrictions(request, user) @@ -136,6 +140,16 @@ class ViewRestrictionMiddleware(MiddlewareMixin): request.session['last_password_reset_check'] = now return None + def check_required_on_login_attribute_restriction(self, request, user): + # do not bother superuser with this + if user.is_superuser: + return None + + missing = user.get_missing_required_on_login_attributes() + if missing: + return 'profile_required_edit' + return None + def check_password_reset_view_restriction(self, request, user): # If user is authenticated and a password_reset_flag is set, force # redirect to password change and show a message. @@ -161,8 +175,8 @@ class ViewRestrictionMiddleware(MiddlewareMixin): if url_name == view: return - # prevent blocking people when they logout - if url_name == 'auth_logout': + # prevent blocking some views, like logout views + if getattr(request.resolver_match.func, 'no_view_restriction', False): return return utils_misc.redirect_and_come_back(request, view) diff --git a/src/authentic2/templates/authentic2/accounts_edit_required.html b/src/authentic2/templates/authentic2/accounts_edit_required.html new file mode 100644 index 00000000..597523d8 --- /dev/null +++ b/src/authentic2/templates/authentic2/accounts_edit_required.html @@ -0,0 +1,10 @@ +{% extends "authentic2/accounts_edit.html" %} +{% load i18n %} + +{% block content %} +{% block required-attributes-message %} +
{% trans "The following informations are required if you want to use this service:"%} {% for attribute in view.missing_attributes %}{{ attribute.label }}{% if not forloop.last %}, {% endif %}{% endfor %} +
+{% endblock %} +{{ block.super }} +{% endblock %} diff --git a/src/authentic2/urls.py b/src/authentic2/urls.py index bb4764a7..9781a735 100644 --- a/src/authentic2/urls.py +++ b/src/authentic2/urls.py @@ -58,6 +58,7 @@ accounts_urlpatterns = [ ), url(r'^logged-in/$', views.logged_in, name='logged-in'), url(r'^edit/$', views.edit_profile, name='profile_edit'), + url(r'^edit/required/$', views.edit_required_profile, name='profile_required_edit'), url(r'^edit/(?P[-\w]+)/$', views.edit_profile, name='profile_edit_with_scope'), url(r'^change-email/$', views.email_change, name='email-change'), url(r'^change-email/verify/$', views.email_change_verify, name='email-change-verify'), diff --git a/src/authentic2/views.py b/src/authentic2/views.py index c049ec99..a04240e7 100644 --- a/src/authentic2/views.py +++ b/src/authentic2/views.py @@ -157,6 +157,29 @@ edit_profile = decorators.setting_enabled('A2_PROFILE_CAN_EDIT_PROFILE')( ) +class EditRequired(EditProfile): + template_names = ['authentic2/accounts_edit_required.html'] + + def dispatch(self, request, *args, **kwargs): + self.missing_attributes = request.user.get_missing_required_on_login_attributes() + if not self.missing_attributes: + return utils_misc.redirect(request, self.get_success_url()) + return super().dispatch(request, *args, **kwargs) + + @classmethod + def get_fields(cls, scopes=None): + # only show the required fields + attribute_names = models.Attribute.objects.filter(required_on_login=True, disabled=False).values_list( + 'name', flat=True + ) + + fields, labels = utils_misc.get_fields_and_labels(attribute_names) + return fields, labels + + +edit_required_profile = login_required(EditRequired.as_view()) + + class EmailChangeView(cbv.TemplateNamesMixin, FormView): template_names = ['profiles/email_change.html', 'authentic2/change_email.html'] title = _('Email Change') @@ -607,6 +630,9 @@ def logout(request, next_url=None, do_local=True, check_referer=True): return response +logout.no_view_restriction = True + + def login_password_profile(request, *args, **kwargs): context = kwargs.pop('context', {}) can_change_password = utils_misc.user_can_change_password(request=request) diff --git a/src/authentic2_auth_fc/views.py b/src/authentic2_auth_fc/views.py index f7c65c55..a47202e5 100644 --- a/src/authentic2_auth_fc/views.py +++ b/src/authentic2_auth_fc/views.py @@ -572,3 +572,4 @@ class LogoutReturnView(View): logout = LogoutReturnView.as_view() +logout.no_view_restriction = True diff --git a/src/authentic2_idp_cas/views.py b/src/authentic2_idp_cas/views.py index 7190f708..04f4f361 100644 --- a/src/authentic2_idp_cas/views.py +++ b/src/authentic2_idp_cas/views.py @@ -469,6 +469,7 @@ class LogoutView(View): login = LoginView.as_view() logout = LogoutView.as_view() +logout.no_view_restriction = True _continue = ContinueView.as_view() validate = ValidateView.as_view() service_validate = ServiceValidateView.as_view() diff --git a/src/authentic2_idp_oidc/views.py b/src/authentic2_idp_oidc/views.py index 0b0cd1fd..4714550c 100644 --- a/src/authentic2_idp_oidc/views.py +++ b/src/authentic2_idp_oidc/views.py @@ -811,3 +811,6 @@ def logout(request): # FIXME: do something with id_token_hint id_token_hint = request.GET.get('id_token_hint') return a2_logout(request, next_url=post_logout_redirect_uri, do_local=False, check_referer=False) + + +logout.no_view_restriction = True diff --git a/tests/middlewares/__init__.py b/tests/middlewares/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/middlewares/test_required_on_login_restriction.py b/tests/middlewares/test_required_on_login_restriction.py new file mode 100644 index 00000000..4ce75c7e --- /dev/null +++ b/tests/middlewares/test_required_on_login_restriction.py @@ -0,0 +1,37 @@ +# authentic2 - versatile identity manager +# Copyright (C) 2021 Entr'ouvert +# +# This program is free software: you can redistribute it and/or modify it +# under the terms of the GNU Affero General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +from authentic2.models import Attribute + +from ..utils import login + + +def test_simple(app, db, simple_user): + Attribute.objects.create( + name='cgu_2021', + label='J\'accepte les conditions générales d\'utilisation', + kind='boolean', + required_on_login=True, + user_visible=True, + ) + resp = login(app, simple_user, path='/accounts/') + assert resp.location == '/accounts/edit/required/?next=/accounts/' + resp = resp.follow() + resp.form.set('cgu_2021', True) + resp = resp.form.submit() + assert resp.location == '/accounts/' + resp = resp.follow() + assert 'les conditions générales d\'utilisation\xa0:\nTrue' in resp.pyquery.text() diff --git a/tests/test_user_manager.py b/tests/test_user_manager.py index 3dd9f98c..52441ffd 100644 --- a/tests/test_user_manager.py +++ b/tests/test_user_manager.py @@ -338,7 +338,7 @@ def test_export_csv(settings, app, superuser, django_assert_num_queries): # overspending memory for the queryset cache, 4 queries by batches num_queries = int(4 + 4 * (user_count / DEFAULT_BATCH_SIZE + bool(user_count % DEFAULT_BATCH_SIZE))) # export task also perform one query to set trigram an another to get users count - num_queries += 2 + num_queries += 3 with django_assert_num_queries(num_queries): response = response.click('CSV') -- 2.32.0.rc0