hobo/hobo/multitenant/utils.py

36 lines
1.2 KiB
Python

import logging
from django.conf import settings
from django.db import DatabaseError
from django.db.transaction import atomic
from hobo.agent.common.models import Role
def provision_user_groups(user, uuids):
if not 'hobo.agent.common' in settings.INSTALLED_APPS:
return
logger = logging.getLogger(__name__)
existing_pks = user.groups.values_list('pk', flat=True)
not_found = set(uuids)
for role in Role.objects.filter(uuid__in=uuids).exclude(pk__in=existing_pks):
not_found.discard(role.uuid)
if role.pk in existing_pks:
continue
user.groups.through.objects.get_or_create(group=role, user=user)
logger.info('adding role %s to %s (%s)', role, user, user.pk)
qs = user.groups.through.objects.filter(user=user, group__role__isnull=False).exclude(
group__role__uuid__in=uuids
)
for rel in qs:
try:
with atomic():
rel.delete()
except DatabaseError:
pass
else:
logger.info('removed role %s from %s (%s)', rel.group, user, user.pk)
for uuid in not_found:
logger.warning('role %s of user %s does not exist', uuid, user)