From b3c96ea29f89fcbbd78a0dc1ba83e700dbd79ab8 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Fri, 16 Jul 2021 10:57:24 +0200 Subject: [PATCH 3/3] misc: block user without required_on_login attributes (#24056) Superuser are exempted from the restriction. --- src/authentic2/custom_user/models.py | 12 ++++++ src/authentic2/middleware.py | 14 +++++++ .../authentic2/accounts_edit_required.html | 10 +++++ src/authentic2/urls.py | 1 + src/authentic2/views.py | 23 ++++++++++++ tests/middlewares/__init__.py | 0 .../test_required_on_login_restriction.py | 37 +++++++++++++++++++ tests/test_user_manager.py | 2 +- 8 files changed, 98 insertions(+), 1 deletion(-) 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/middleware.py b/src/authentic2/middleware.py index 076a23da..7834095b 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. 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..66b80645 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') 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