from django.conf import settings
from django.contrib.auth.models import Group
from django.dispatch import receiver
from django_cas_ng.signals import cas_user_authenticated

@receiver(cas_user_authenticated)
def update_created_user(sender, **kwargs):

    created = kwargs.get('created', False)
    user = kwargs.get('user', None)
    attributes = kwargs.get('attributes', {})

    if not created or not user:
        return

    user.first_name = attributes.get('first_name','')
    user.last_name = attributes.get('last_name', '')
    cas_user_group_name = getattr(settings, 'CAS_USER_DEFAULT_GROUP', None)
    if cas_user_group_name and cas_user_group_name not in [g.name for g in user.groups.all()]:
        cas_user_group, _ = Group.objects.get_or_create(name=cas_user_group_name)
        user.groups.add(cas_user_group)
    user.save()
