auth_fc: clean accounts of deleted users (#48168)

This commit is contained in:
Benjamin Dauvergne 2020-11-02 14:25:14 +01:00
parent c56e4d684a
commit 0e24a314f4
3 changed files with 140 additions and 89 deletions

View File

@ -14,92 +14,4 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from . import app_settings
import django.apps
from django import template
class Plugin(object):
def redirect_logout_list(self, request, **kwargs):
from django.urls import reverse
from . import utils
url = utils.build_logout_url(request, next_url=reverse('auth_logout'))
# url is assumed empty if no active session on the OP.
if url:
return [url]
return []
def registration_form_prefill(self, request):
from . import utils
if app_settings.enable_registration_form_prefill:
return [utils.get_mapped_attributes(request)]
return []
class AppConfig(django.apps.AppConfig):
name = __name__
def get_a2_plugin(self):
return Plugin()
def ready(self):
from .api_views import fc_unlink
from authentic2.api_views import UsersAPI
UsersAPI.fc_unlink = fc_unlink
def a2_hook_api_modify_serializer(self, view, serializer):
from rest_framework import serializers
from authentic2.utils import make_url
from . import app_settings
if not app_settings.enable:
return
request = view.request
if 'full' not in request.GET:
return
if view.__class__.__name__ == 'UsersAPI':
def get_franceconnect(user):
linked = user.fc_accounts.exists()
return {
'linked': linked,
'link_url': make_url('fc-login-or-link', request=request, absolute=True),
'unlink_url': make_url('fc-unlink', request=request, absolute=True),
}
serializer.get_franceconnect = get_franceconnect
serializer.fields['franceconnect'] = serializers.SerializerMethodField()
def a2_hook_manager_user_data(self, view, user):
context = {'user': user}
return [template.loader.get_template('authentic2_auth_fc/manager_user_sidebar.html').render(context)]
def a2_hook_user_can_reset_password(self, user):
if user.fc_accounts.exists():
return True
return None
def a2_hook_user_can_change_password(self, user, request, **kwargs):
from authentic2.utils import get_authentication_events
if not request:
return True
try:
session = request.session
except AttributeError:
return True
if session and 'fc_id_token' in session:
for authentication_event in get_authentication_events(request=request):
if authentication_event['how'] == 'france-connect':
return False
return True
default_app_config = '%s.%s' % (__name__, 'AppConfig')
default_app_config = '%s.apps.AppConfig' % __name__

View File

@ -0,0 +1,118 @@
# authentic2-auth-fc - authentic2 authentication for FranceConnect
# Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
from . import app_settings
import django.apps
from django import template
class Plugin(object):
def redirect_logout_list(self, request, **kwargs):
from django.urls import reverse
from . import utils
url = utils.build_logout_url(request, next_url=reverse('auth_logout'))
# url is assumed empty if no active session on the OP.
if url:
return [url]
return []
def registration_form_prefill(self, request):
from . import utils
if app_settings.enable_registration_form_prefill:
return [utils.get_mapped_attributes(request)]
return []
class AppConfig(django.apps.AppConfig):
name = 'authentic2_auth_fc'
def get_a2_plugin(self):
return Plugin()
def a2_hook_api_modify_serializer(self, view, serializer):
from rest_framework import serializers
from authentic2.utils import make_url
from . import app_settings
if not app_settings.enable:
return
request = view.request
if 'full' not in request.GET:
return
if view.__class__.__name__ == 'UsersAPI':
def get_franceconnect(user):
linked = user.fc_accounts.exists()
return {
'linked': linked,
'link_url': make_url('fc-login-or-link', request=request, absolute=True),
'unlink_url': make_url('fc-unlink', request=request, absolute=True),
}
serializer.get_franceconnect = get_franceconnect
serializer.fields['franceconnect'] = serializers.SerializerMethodField()
def a2_hook_manager_user_data(self, view, user):
context = {'user': user}
return [template.loader.get_template('authentic2_auth_fc/manager_user_sidebar.html').render(context)]
def a2_hook_user_can_reset_password(self, user):
if user.fc_accounts.exists():
return True
return None
def a2_hook_user_can_change_password(self, user, request, **kwargs):
from authentic2.utils import get_authentication_events
if not request:
return True
try:
session = request.session
except AttributeError:
return True
if session and 'fc_id_token' in session:
for authentication_event in get_authentication_events(request=request):
if authentication_event['how'] == 'france-connect':
return False
return True
def ready(self):
from .api_views import fc_unlink
from authentic2.api_views import UsersAPI
UsersAPI.fc_unlink = fc_unlink
from django.db.models.signals import pre_save
from authentic2.custom_user.models import DeletedUser
pre_save.connect(
self.pre_save_deleted_user,
sender=DeletedUser)
def pre_save_deleted_user(self, sender, instance, **kwargs):
'''Delete and copy FcAccount to old_data'''
from .models import FcAccount
fc_accounts = FcAccount.objects.filter(user__uuid=instance.old_uuid).order_by('id')
for fc_account in fc_accounts:
instance.old_data = instance.old_data or {}
instance.old_data.setdefault('fc_accounts', []).append({
'sub': fc_account.sub,
})

View File

@ -25,6 +25,8 @@ from django.urls import reverse
from django.utils.six.moves.urllib import parse as urlparse
from django.utils.timezone import now
from authentic2.custom_user.models import DeletedUser
from authentic2_auth_fc import models
from authentic2_auth_fc.utils import requests_retry_session
@ -379,3 +381,22 @@ def test_user_info_incomplete_already_linked(settings, app, franceconnect, simpl
response = response.click(href='callback')
response = franceconnect.handle_authorization(app, response.location, status=302)
assert 'FranceConnect account is already' in app.cookies['messages']
def test_save_account_on_delete_user(db):
user = User.objects.create()
models.FcAccount.objects.create(user=user, sub='1234')
models.FcAccount.objects.create(user=user, sub='4567', order=1)
user.mark_as_deleted()
User.objects.cleanup(threshold=0, timestamp=now() + datetime.timedelta(seconds=1))
assert models.FcAccount.objects.count() == 0
deleted_user = DeletedUser.objects.get()
assert deleted_user.old_data.get('fc_accounts') == [
{
'sub': '1234',
},
{
'sub': '4567',
}
]