This repository has been archived on 2023-08-12. You can view files and clone it, but cannot push or open issues or pull requests.
authentic2-gnm/src/authentic2_gnm/management/commands/sync-cut.py

99 lines
4.1 KiB
Python

# authentic2_gnm - Authentic2 plugin for GNM
# Copyright (C) 2017-2018 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 __future__ import print_function
import datetime
import requests
from django.conf import settings
from django.core.management.base import BaseCommand
from authentic2.utils.template import Template
from authentic2_auth_oidc.models import OIDCProvider, OIDCAccount
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--delta', metavar='DELTA', type=int, default=300)
def handle(self, *args, **options):
verbose = int(options['verbosity']) > 0
delta = options['delta']
# check all existing users
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
url = settings.CUT_API_BASE_URL + 'users/synchronization/'
cut_users = OIDCProvider.objects.get(slug='cut')
unknown_uuids = []
auth = (cut_users.client_id, cut_users.client_secret)
for accounts in chunks(OIDCAccount.objects.filter(provider=cut_users), 100):
subs = [x.sub for x in accounts]
resp = requests.post(url, json={'known_uuids': subs}, auth=auth)
resp.raise_for_status()
unknown_uuids.extend(resp.json().get('unknown_uuids'))
for account in OIDCAccount.objects.filter(sub__in=unknown_uuids):
if verbose:
print('disabling', account.user.email, account.user.ou)
account.user.email = account.user.email + '.%s.invalid' % (
datetime.datetime.now().strftime('%Y-%m-%dT%H-%M-%S'))
account.user.save()
OIDCAccount.objects.filter(sub__in=unknown_uuids).delete()
# update recently modified users
url = settings.CUT_API_BASE_URL + 'users/?modified__gt=%s' % (
datetime.datetime.now() - datetime.timedelta(seconds=delta)).strftime('%Y-%m-%dT%H:%M:%S')
resp = requests.get(url, auth=settings.CUT_API_CREDENTIALS)
resp.raise_for_status()
for user_dict in resp.json()['results']:
try:
account = OIDCAccount.objects.get(user__email=user_dict['email'])
except OIDCAccount.DoesNotExist:
continue
had_changes = False
for claim in cut_users.claim_mappings.all():
if '{{' in claim.claim or '{%' in claim.claim:
template = Template(claim.claim)
attribute_value = template.render(context=user_dict)
else:
attribute_value = user_dict.get(claim.claim)
try:
old_attribute_value = getattr(account.user, claim.attribute)
except AttributeError:
try:
old_attribute_value = getattr(account.user.attributes, claim.attribute)
except AttributeError:
old_attribute_value = None
if old_attribute_value == attribute_value:
continue
had_changes = True
setattr(account.user, claim.attribute, attribute_value)
try:
setattr(account.user.attributes, claim.attribute, attribute_value)
except AttributeError:
pass
if had_changes:
if verbose:
print('had changes, saving %r' % account.user)
account.user.save()