Beispiel #1
0
Datei: forms.py Projekt: g10f/sso
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if self.instance.organisation_country:
            self.fields['organisation_country'] = bootstrap.ReadOnlyField(
                initial=self.instance.organisation_country, label=_("Country"))
        if self.instance.admin_region:
            self.fields['admin_region'] = bootstrap.ReadOnlyField(
                initial=self.instance.admin_region, label=_("Admin region"))

        self.fields['email_value'].initial = force_str(self.instance.email)
        self.fields[
            'center_type'].initial = self.instance.get_center_type_display()
        self.fields['name'].initial = self.instance.name
        self.fields['is_active'].initial = self.instance.is_active
Beispiel #2
0
class CenterSelfProfileForm(forms.Form):
    """
    Form for a user which represents a center
    """
    account_type = bootstrap.ReadOnlyField(label=_("Account type"))
    username = bootstrap.ReadOnlyField(label=_("Username"))
    email = bootstrap.ReadOnlyField(label=_('Email address'))
    language = forms.ChoiceField(
        label=_("Language"),
        required=False,
        choices=(BLANK_CHOICE_DASH +
                 sorted(list(settings.LANGUAGES), key=lambda x: x[1])),
        widget=bootstrap.Select2())
    timezone = forms.ChoiceField(
        label=_("Timezone"),
        required=False,
        choices=BLANK_CHOICE_DASH +
        list(zip(pytz.common_timezones, pytz.common_timezones)),
        widget=bootstrap.Select2())

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('instance')
        object_data = model_to_dict(self.user)
        object_data['account_type'] = _(
            'Organisation Account') if self.user.is_center else _(
                'Member Account')
        object_data['email'] = force_str(self.user.primary_email())
        initial = kwargs.get('initial', {})
        object_data.update(initial)
        kwargs['initial'] = object_data
        super().__init__(*args, **kwargs)

        if self.user.organisations.exists():
            organisation = ', '.join(
                [str(x) for x in self.user.organisations.all()])
            organisation_field = bootstrap.ReadOnlyField(
                initial=organisation, label=_("Organisation"))
            self.fields['organisation'] = organisation_field

    def save(self):
        cd = self.cleaned_data
        self.user.language = cd['language']
        self.user.timezone = cd['timezone']
        self.user.save()
Beispiel #3
0
Datei: forms.py Projekt: g10f/sso
 def __init__(self, *args, **kwargs):
     self.user = kwargs.pop('user')  # remove custom user keyword
     super().__init__(*args, **kwargs)
     if self.instance.email:
         self.fields['email_value'].initial = force_str(self.instance.email)
     else:
         self.fields['email_value'].initial = SSO_ORGANISATION_EMAIL_DOMAIN
     if self.instance.pk is not None and self.instance.country:
         # readonly field for the update form
         self.fields['country_text'] = bootstrap.ReadOnlyField(
             initial=force_str(self.instance.country), label=_("Country"))
         self.fields['association_text'] = bootstrap.ReadOnlyField(
             initial=force_str(self.instance.association),
             label=_("Association"))
         del self.fields['association']
         del self.fields['country']
     else:
         self.fields[
             'association'].queryset = self.user.get_administrable_associations(
             )
Beispiel #4
0
Datei: forms.py Projekt: g10f/sso
class OrganisationCenterAdminForm(OrganisationBaseForm):
    email_value = bootstrap.ReadOnlyField(label=_("Email address"))
    center_type = bootstrap.ReadOnlyField(label=_("Organisation type"))
    name = bootstrap.ReadOnlyField(label=_("Name"))
    is_active = bootstrap.ReadOnlyYesNoField(label=_("Active"))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if self.instance.organisation_country:
            self.fields['organisation_country'] = bootstrap.ReadOnlyField(
                initial=self.instance.organisation_country, label=_("Country"))
        if self.instance.admin_region:
            self.fields['admin_region'] = bootstrap.ReadOnlyField(
                initial=self.instance.admin_region, label=_("Admin region"))

        self.fields['email_value'].initial = force_str(self.instance.email)
        self.fields[
            'center_type'].initial = self.instance.get_center_type_display()
        self.fields['name'].initial = self.instance.name
        self.fields['is_active'].initial = self.instance.is_active
Beispiel #5
0
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('instance')
        object_data = model_to_dict(self.user)
        initial = kwargs.get('initial', {})
        object_data.update(initial)
        kwargs['initial'] = object_data
        super().__init__(*args, **kwargs)

        organisation_field = bootstrap.ReadOnlyField(
            initial=', '.join([str(x) for x in self.user.organisations.all()]),
            label=_("Organisation"),
            help_text=
            _('Please use the contact form for a request to change this value.'
              ))
        self.fields['organisation'] = organisation_field
Beispiel #6
0
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        self.user = kwargs.pop('instance')
        user_data = model_to_dict(self.user)
        user_data['account_type'] = _(
            'Organisation Account') if self.user.is_center else _(
                'Member Account')
        user_data['status'] = _('active') if self.user.is_active else _(
            'blocked')
        user_data['email'] = force_str(self.user.primary_email())
        user_data['role_profiles'] = [
            str(role_profile.id)
            for role_profile in self.user.role_profiles.all()
        ]
        user_data['application_roles'] = [
            application_role.id
            for application_role in self.user.application_roles.all()
        ]
        initial = kwargs.get('initial', {})
        initial.update(user_data)
        kwargs['initial'] = initial
        super().__init__(*args, **kwargs)

        self.fields['application_roles'].choices = []
        app_roles_by_profile = ApplicationRole.objects.filter(
            roleprofile__user__id=self.user.pk).only("id")
        for application_role in self.request.user.get_administrable_application_roles(
        ):
            app_role_text = str(application_role)
            if application_role in app_roles_by_profile:
                app_role_text += " *"
            self.fields['application_roles'].choices.append(
                (application_role.id, app_role_text))

        self.fields['role_profiles'].choices = [
            (role_profile.id, role_profile) for role_profile in
            self.request.user.get_administrable_role_profiles()
        ]

        if self.user.organisations.exists():
            organisation = ', '.join(
                [str(x) for x in self.user.organisations.all()])
            organisation_field = bootstrap.ReadOnlyField(
                initial=organisation, label=_("Organisation"))
            self.fields['organisation'] = organisation_field
Beispiel #7
0
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('instance')
        object_data = model_to_dict(self.user)
        object_data['account_type'] = _(
            'Organisation Account') if self.user.is_center else _(
                'Member Account')
        object_data['email'] = force_str(self.user.primary_email())
        initial = kwargs.get('initial', {})
        object_data.update(initial)
        kwargs['initial'] = object_data
        super().__init__(*args, **kwargs)

        if self.user.organisations.exists():
            organisation = ', '.join(
                [str(x) for x in self.user.organisations.all()])
            organisation_field = bootstrap.ReadOnlyField(
                initial=organisation, label=_("Organisation"))
            self.fields['organisation'] = organisation_field
Beispiel #8
0
class EmailManagerInlineForm(BaseTabularInlineForm):
    """
    inline form for administrating the admins
    """
    manager_email = forms.CharField(
        max_length=254,
        label=_('Email'),
        widget=bootstrap.TextInput(attrs={'size': 50}))
    name = bootstrap.ReadOnlyField(label=_('Name'), initial='')

    class Meta:
        model = GroupEmailManager
        fields = ()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        try:
            manager = self.instance.manager
            self.fields['manager_email'].initial = manager.primary_email()
            self.fields['name'].initial = "%s %s" % (manager.first_name,
                                                     manager.last_name)
        except ObjectDoesNotExist:
            pass

    def clean_manager_email(self):
        manager_email = self.cleaned_data['manager_email']
        if not get_user_model().objects.filter(
                useremail__email=manager_email).exists():
            msg = _('The user does not exists')
            raise ValidationError(msg)

        return manager_email

    def save(self, commit=True):
        if 'manager_email' in self.changed_data:
            manager_email = self.cleaned_data['manager_email']
            manager = get_user_model().objects.get(
                useremail__email=manager_email)
            self.instance.manager = manager

        instance = super().save(commit)

        return instance
Beispiel #9
0
class ApplicationAdminForm(BaseTabularInlineForm):
    admin_email = forms.CharField(
        max_length=254,
        label=_('Email'),
        widget=bootstrap.TextInput(attrs={'size': 50}))
    name = bootstrap.ReadOnlyField(label=_('Name'), initial='')

    form_text = _("Application Admin ")

    class Meta:
        model = ApplicationAdmin
        fields = ()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        try:
            admin = self.instance.admin
            self.fields['admin_email'].initial = admin.primary_email()
            self.fields['name'].initial = "%s %s" % (admin.first_name,
                                                     admin.last_name)
        except ObjectDoesNotExist:
            pass

    def clean_admin_email(self):
        admin_email = self.cleaned_data['admin_email']
        if not get_user_model().objects.filter(
                useremail__email=admin_email).exists():
            msg = _('The user does not exists')
            raise ValidationError(msg)

        return admin_email

    def save(self, commit=True):
        if 'admin_email' in self.changed_data:
            admin_email = self.cleaned_data['admin_email']
            admin = get_user_model().objects.get(useremail__email=admin_email)
            self.instance.admin = admin
            add_app_admin_group(user=admin)
        instance = super().save(commit)
        return instance
Beispiel #10
0
class CenterProfileForm(mixins.UserRolesMixin, mixins.UserNoteMixin,
                        forms.Form):
    """
    Form for SSO Staff for editing Center Accounts
    """
    account_type = bootstrap.ReadOnlyField(label=_("Account type"))
    status = bootstrap.ReadOnlyField(label=_('Status'))
    username = bootstrap.ReadOnlyField(label=_("Username"))
    email = bootstrap.ReadOnlyField(label=_('Email address'))
    notes = forms.CharField(label=_("Notes"),
                            required=False,
                            max_length=1024,
                            widget=bootstrap.Textarea(attrs={
                                'cols': 40,
                                'rows': 10
                            }))
    application_roles = forms.MultipleChoiceField(
        required=False,
        widget=bootstrap.FilteredSelectMultiple(_("Application roles")),
        label=_("Additional application roles"),
        help_text=mixins.UserRolesMixin.application_roles_help)
    role_profiles = forms.MultipleChoiceField(
        required=False,
        widget=bootstrap.CheckboxSelectMultiple(),
        label=_("Role profiles"),
        help_text=mixins.UserRolesMixin.role_profiles_help)

    created_by_user = forms.CharField(
        label=_("Created by"),
        required=False,
        widget=bootstrap.TextInput(attrs={'disabled': ''}))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        self.user = kwargs.pop('instance')
        user_data = model_to_dict(self.user)
        user_data['account_type'] = _(
            'Organisation Account') if self.user.is_center else _(
                'Member Account')
        user_data['status'] = _('active') if self.user.is_active else _(
            'blocked')
        user_data['email'] = force_str(self.user.primary_email())
        user_data['role_profiles'] = [
            str(role_profile.id)
            for role_profile in self.user.role_profiles.all()
        ]
        user_data['application_roles'] = [
            application_role.id
            for application_role in self.user.application_roles.all()
        ]
        initial = kwargs.get('initial', {})
        initial.update(user_data)
        kwargs['initial'] = initial
        super().__init__(*args, **kwargs)

        self.fields['application_roles'].choices = []
        app_roles_by_profile = ApplicationRole.objects.filter(
            roleprofile__user__id=self.user.pk).only("id")
        for application_role in self.request.user.get_administrable_application_roles(
        ):
            app_role_text = str(application_role)
            if application_role in app_roles_by_profile:
                app_role_text += " *"
            self.fields['application_roles'].choices.append(
                (application_role.id, app_role_text))

        self.fields['role_profiles'].choices = [
            (role_profile.id, role_profile) for role_profile in
            self.request.user.get_administrable_role_profiles()
        ]

        if self.user.organisations.exists():
            organisation = ', '.join(
                [str(x) for x in self.user.organisations.all()])
            organisation_field = bootstrap.ReadOnlyField(
                initial=organisation, label=_("Organisation"))
            self.fields['organisation'] = organisation_field

    def save(self, extend_validity=False, activate=None):
        cd = self.cleaned_data
        current_user = self.request.user
        self.update_user_m2m_fields('application_roles', current_user)
        self.update_user_m2m_fields('role_profiles', current_user)
        if activate is not None:
            self.user.is_active = activate

        self.create_note_if_required(current_user, cd, activate,
                                     extend_validity)

        self.user.save()
        return self.user
Beispiel #11
0
class UserProfileForm(mixins.UserRolesMixin, mixins.UserNoteMixin, forms.Form):
    """
    Form for SSO Staff
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'duplicate_email': _("A user with that email address already exists."),
    }
    username = forms.CharField(label=_("Username"),
                               max_length=40,
                               validators=[UnicodeUsernameValidator()],
                               widget=bootstrap.TextInput())
    valid_until = bootstrap.ReadOnlyField(label=_("Valid until"))
    first_name = forms.CharField(label=_('First name'),
                                 max_length=30,
                                 widget=bootstrap.TextInput())
    last_name = forms.CharField(label=_('Last name'),
                                max_length=30,
                                widget=bootstrap.TextInput())
    gender = forms.ChoiceField(label=_('Gender'),
                               required=False,
                               choices=(BLANK_CHOICE_DASH +
                                        User.GENDER_CHOICES),
                               widget=bootstrap.Select())
    dob = forms.DateField(label=_('Date of birth'),
                          required=False,
                          widget=bootstrap.SelectDateWidget(
                              years=range(datetime.datetime.now().year - 100,
                                          datetime.datetime.now().year + 1)))
    status = bootstrap.ReadOnlyField(label=_('Status'))
    organisations = forms.ModelChoiceField(
        queryset=None,
        required=settings.SSO_ORGANISATION_REQUIRED,
        label=_("Organisation"),
        widget=bootstrap.Select2())
    application_roles = forms.MultipleChoiceField(
        required=False,
        widget=bootstrap.FilteredSelectMultiple(_("Application roles")),
        label=_("Additional application roles"),
        help_text=mixins.UserRolesMixin.application_roles_help)
    notes = forms.CharField(label=_("Notes"),
                            required=False,
                            max_length=1024,
                            widget=bootstrap.Textarea(attrs={
                                'cols': 40,
                                'rows': 10
                            }))
    role_profiles = forms.MultipleChoiceField(
        required=False,
        widget=bootstrap.CheckboxSelectMultiple(),
        label=_("Role profiles"),
        help_text=mixins.UserRolesMixin.role_profiles_help)
    created_by_user = forms.CharField(
        label=_("Created by"),
        required=False,
        widget=bootstrap.TextInput(attrs={'disabled': ''}))
    last_modified_by_user = forms.CharField(
        label=_("Last modified by"),
        required=False,
        widget=bootstrap.TextInput(attrs={'disabled': ''}))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        self.user = kwargs.pop('instance')
        user_data = model_to_dict(self.user)
        user_data['status'] = _('active') if self.user.is_active else _(
            'blocked')
        user_data['role_profiles'] = [
            role_profile.id for role_profile in self.user.role_profiles.all()
        ]
        user_data['application_roles'] = [
            application_role.id
            for application_role in self.user.application_roles.all()
        ]

        if self.user.organisations.count() == 1:
            user_data['organisations'] = self.user.organisations.first()

        initial = kwargs.get('initial', {})
        initial.update(user_data)

        initial[
            'created_by_user'] = self.user.created_by_user if self.user.created_by_user else ''
        initial[
            'last_modified_by_user'] = self.user.last_modified_by_user if self.user.last_modified_by_user else ''

        kwargs['initial'] = initial
        super().__init__(*args, **kwargs)

        self.fields['application_roles'].choices = []
        app_roles_by_profile = ApplicationRole.objects.filter(
            roleprofile__user__id=self.user.pk).only("id")
        for application_role in self.request.user.get_administrable_application_roles(
        ):
            app_role_text = str(application_role)
            if application_role in app_roles_by_profile:
                app_role_text += " *"
            self.fields['application_roles'].choices.append(
                (application_role.id, app_role_text))
        self.fields['role_profiles'].choices = [
            (role_profile.id, role_profile) for role_profile in
            self.request.user.get_administrable_role_profiles()
        ]
        if self.user.organisations.count() > 1:
            self.fields['organisations'] = forms.ModelMultipleChoiceField(
                queryset=None,
                required=settings.SSO_ORGANISATION_REQUIRED,
                widget=bootstrap.SelectMultipleWithCurrently(
                    currently=', '.join(
                        [str(x) for x in self.user.organisations.all()])),
                label=_("Organisation"))
        self.fields['organisations'].queryset = self.request.user.get_administrable_user_organisations(). \
            filter(is_active=True, association__is_selectable=True)

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            get_user_model().objects.exclude(pk=self.user.pk).get(
                username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    def save(self,
             extend_validity=False,
             activate=None,
             remove_org=False,
             make_member=False):
        cd = self.cleaned_data
        current_user = self.request.user
        if remove_org:
            new_orgs = set()
            removed_orgs = list(self.user.organisations.all())
        else:
            removed_orgs = None
            new_orgs = None

        self.update_user_m2m_fields('organisations',
                                    current_user,
                                    new_value_set=new_orgs)
        self.update_user_m2m_fields('application_roles', current_user)
        self.update_user_m2m_fields('role_profiles', current_user)

        if remove_org:
            self.user.remove_organisation_related_permissions()

        self.user.username = cd['username']
        self.user.first_name = cd['first_name']
        self.user.last_name = cd['last_name']
        self.user.gender = cd['gender']
        self.user.dob = cd['dob']
        if activate is not None:
            self.user.is_active = activate

        self.create_note_if_required(current_user, cd, activate,
                                     extend_validity, removed_orgs)

        if make_member:
            dwbn_member_profile = RoleProfile.objects.get_by_natural_key(
                uuid=settings.SSO_DEFAULT_MEMBER_PROFILE_UUID)
            self.user.role_profiles.add(dwbn_member_profile)

        if extend_validity or make_member:
            # enable brand specific modification
            valid_until = now() + datetime.timedelta(
                days=settings.SSO_VALIDATION_PERIOD_DAYS)
            extend_user_validity.send_robust(sender=self.__class__,
                                             user=self.user,
                                             valid_until=valid_until,
                                             admin=self.request.user)
            self.user.valid_until = valid_until

        self.user.save()

        return self.user
Beispiel #12
0
class UserSelfProfileForm(forms.Form):
    """
    Form for the user himself to change editable values
    """
    username = bootstrap.ReadOnlyField(label=_("Username"))
    valid_until = bootstrap.ReadOnlyField(label=_("Valid until"))
    first_name = forms.CharField(label=_('First name'),
                                 max_length=30,
                                 widget=bootstrap.TextInput())
    last_name = forms.CharField(label=_('Last name'),
                                max_length=30,
                                widget=bootstrap.TextInput())
    picture = Base64ImageField(
        label=_('Your picture'),
        required=False,
        help_text=_('Please use a photo of your face.'),
        widget=bootstrap.ClearableBase64ImageWidget(
            attrs={
                'max_file_size': settings.SSO_USER_MAX_PICTURE_SIZE,
                'width': settings.SSO_USER_PICTURE_WIDTH,
                'height': settings.SSO_USER_PICTURE_HEIGHT,
            }))
    gender = forms.ChoiceField(label=_('Gender'),
                               required=False,
                               choices=(BLANK_CHOICE_DASH +
                                        User.GENDER_CHOICES),
                               widget=bootstrap.Select())
    dob = forms.DateField(label=_('Date of birth'),
                          required=False,
                          widget=bootstrap.SelectDateWidget(
                              years=range(datetime.datetime.now().year - 100,
                                          datetime.datetime.now().year + 1)))
    homepage = forms.URLField(label=_('Homepage'),
                              required=False,
                              max_length=512,
                              widget=bootstrap.TextInput())
    language = forms.ChoiceField(
        label=_("Language"),
        required=False,
        choices=(BLANK_CHOICE_DASH +
                 sorted(list(settings.LANGUAGES), key=lambda x: x[1])),
        widget=bootstrap.Select2())
    timezone = forms.ChoiceField(
        label=_("Timezone"),
        required=False,
        choices=BLANK_CHOICE_DASH +
        list(zip(pytz.common_timezones, pytz.common_timezones)),
        widget=bootstrap.Select2())

    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
    }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('instance')
        object_data = model_to_dict(self.user)
        initial = kwargs.get('initial', {})
        object_data.update(initial)
        kwargs['initial'] = object_data
        super().__init__(*args, **kwargs)

        organisation_field = bootstrap.ReadOnlyField(
            initial=', '.join([str(x) for x in self.user.organisations.all()]),
            label=_("Organisation"),
            help_text=
            _('Please use the contact form for a request to change this value.'
              ))
        self.fields['organisation'] = organisation_field

    def clean_organisation(self):
        if self.user.organisations.exists():
            # if already assigned to an organisation return None, (readonly use case)
            return None
        else:
            return self.cleaned_data['organisation']

    def save(self):
        cd = self.cleaned_data
        if (not self.initial['first_name'] and not self.initial['last_name']) and cd.get('first_name') \
            and cd.get('last_name'):
            # should be a streaming user, which has no initial first_name and last_name
            # we create the new username because the streaming user has his email as username
            self.user.username = default_username_generator(
                capfirst(cd.get('first_name')), capfirst(cd.get('last_name')))

        self.user.first_name = cd['first_name']
        self.user.last_name = cd['last_name']

        if 'picture' in self.changed_data:
            self.user.picture.delete(save=False)
        self.user.picture = cd['picture'] if cd['picture'] else None

        self.user.dob = cd.get('dob', None)
        self.user.gender = cd['gender']
        self.user.homepage = cd['homepage']
        self.user.language = cd['language']
        self.user.timezone = cd['timezone']

        self.user.save()

        if 'organisation' in cd and cd['organisation']:
            # user selected an organisation, this can only happen if the user before had
            # no organisation (see clean_organisation).
            self.user.set_organisations([cd["organisation"]])
Beispiel #13
0
class RegistrationProfileForm(mixins.UserRolesMixin, forms.Form):
    """
    Form for organisation and region admins
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'duplicate_email': _("A user with that email address already exists."),
    }

    username = forms.CharField(label=_("Username"),
                               max_length=30,
                               widget=bootstrap.TextInput())
    notes = forms.CharField(label=_("Notes"),
                            required=False,
                            max_length=1024,
                            widget=bootstrap.Textarea(attrs={
                                'cols': 40,
                                'rows': 10
                            }))
    first_name = forms.CharField(label=_('First name'),
                                 max_length=30,
                                 widget=bootstrap.TextInput())
    last_name = forms.CharField(label=_('Last name'),
                                max_length=30,
                                widget=bootstrap.TextInput())
    email = forms.EmailField(
        label=_('Email address'),
        required=False,
        widget=bootstrap.TextInput(attrs={'disabled': ''}))
    date_registered = bootstrap.ReadOnlyField(label=_("Date registered"))
    country = bootstrap.ReadOnlyField(label=_("Country"))
    city = bootstrap.ReadOnlyField(label=_("City"))
    language = bootstrap.ReadOnlyField(label=_("Language"))
    timezone = bootstrap.ReadOnlyField(label=_("Timezone"))
    gender = forms.ChoiceField(label=_('Gender'),
                               required=False,
                               choices=(BLANK_CHOICE_DASH +
                                        User.GENDER_CHOICES),
                               widget=bootstrap.Select())
    dob = forms.CharField(label=_("Date of birth"),
                          required=False,
                          widget=bootstrap.TextInput(attrs={'disabled': ''}))
    about_me = forms.CharField(label=_('About me'),
                               required=False,
                               widget=bootstrap.Textarea(attrs={
                                   'cols': 40,
                                   'rows': 5,
                                   'readonly': 'readonly'
                               }))
    known_person1_first_name = forms.CharField(label=_("First name"),
                                               max_length=100,
                                               required=False,
                                               widget=bootstrap.TextInput())
    known_person1_last_name = forms.CharField(label=_("Last name"),
                                              max_length=100,
                                              required=False,
                                              widget=bootstrap.TextInput())
    known_person2_first_name = forms.CharField(label=_("First name"),
                                               max_length=100,
                                               required=False,
                                               widget=bootstrap.TextInput())
    known_person2_last_name = forms.CharField(label=_("Last name"),
                                              max_length=100,
                                              required=False,
                                              widget=bootstrap.TextInput())
    last_modified_by_user = forms.CharField(
        label=_("Last modified by"),
        required=False,
        widget=bootstrap.TextInput(attrs={'disabled': ''}))
    organisations = forms.ModelChoiceField(
        queryset=None,
        label=_("Organisation"),
        widget=bootstrap.Select2(),
        required=settings.SSO_ORGANISATION_REQUIRED)
    application_roles = forms.ModelMultipleChoiceField(
        queryset=None,
        required=False,
        widget=bootstrap.FilteredSelectMultiple(_("Application roles")),
        label=_("Additional application roles"),
        help_text=mixins.UserRolesMixin.application_roles_help)
    check_back = forms.BooleanField(
        label=_("Check back"),
        help_text=_('Designates if there are open questions to check.'),
        required=False,
        disabled=True)
    is_access_denied = forms.BooleanField(
        label=_("Access denied"),
        help_text=_('Designates if access is denied to the user.'),
        required=False,
        disabled=True)
    is_stored_permanently = forms.BooleanField(
        label=_("Store permanantly"),
        help_text=_(
            'Keep stored in database to prevent re-registration of denied user.'
        ),
        required=False)
    role_profiles = forms.MultipleChoiceField(
        required=False,
        widget=bootstrap.CheckboxSelectMultiple(),
        label=_("Role profiles"),
        help_text=mixins.UserRolesMixin.role_profiles_help)

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            get_user_model().objects.exclude(pk=self.user.pk).get(
                username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        self.registrationprofile = kwargs.pop('instance')
        self.user = self.registrationprofile.user

        registrationprofile_data = model_to_dict(self.registrationprofile)

        user_data = model_to_dict(self.user)
        if self.user.language:
            user_data['language'] = self.user.get_language_display()
        try:
            # after registration, the user should have exactly 1 center
            user_data['organisations'] = self.user.organisations.first()
        except ObjectDoesNotExist:
            # center is optional
            # logger.error("User without center?", exc_info=1)
            pass

        # initialize form correctly
        user_data['role_profiles'] = [
            str(role_profile.id)
            for role_profile in self.user.role_profiles.all()
        ]

        address_data = {}
        if self.user.useraddress_set.exists():
            useraddress = self.user.useraddress_set.first()
            address_data = model_to_dict(useraddress)
            address_data['country'] = useraddress.country

        initial = kwargs.get('initial', {})
        initial.update(registrationprofile_data)
        initial.update(user_data)
        initial.update(address_data)

        initial['email'] = self.user.primary_email()
        last_modified_by_user = self.registrationprofile.last_modified_by_user
        initial[
            'last_modified_by_user'] = last_modified_by_user if last_modified_by_user else ''
        kwargs['initial'] = initial

        super().__init__(*args, **kwargs)
        current_user = self.request.user
        self.fields[
            'application_roles'].queryset = current_user.get_administrable_application_roles(
            )
        # self.fields['role_profiles'].queryset = current_user.get_administrable_role_profiles()
        self.fields['role_profiles'].choices = [
            (role_profile.id, role_profile)
            for role_profile in current_user.get_administrable_role_profiles()
        ]
        self.fields[
            'organisations'].queryset = current_user.get_administrable_user_organisations(
            )

    def save(self):
        cd = self.cleaned_data
        current_user = self.request.user
        # registrationprofile data
        self.registrationprofile.known_person1_first_name = cd[
            'known_person1_first_name']
        self.registrationprofile.known_person1_last_name = cd[
            'known_person1_last_name']
        self.registrationprofile.known_person2_first_name = cd[
            'known_person2_first_name']
        self.registrationprofile.known_person2_last_name = cd[
            'known_person2_last_name']

        self.registrationprofile.save()

        # user data
        self.user.username = cd['username']
        self.user.first_name = cd['first_name']
        self.user.last_name = cd['last_name']
        self.user.is_stored_permanently = cd['is_stored_permanently']

        if cd['notes']:
            UserNote.objects.create_note(user=self.user,
                                         notes=[cd['notes']],
                                         created_by_user=current_user)

        # userprofile data
        self.update_user_m2m_fields('organisations', current_user)
        self.update_user_m2m_fields('application_roles', current_user)
        self.update_user_m2m_fields('role_profiles', current_user)

        organisation = self.cleaned_data['organisations']
        if is_validation_period_active(organisation):
            # a new registered user is valid_until from now for the validation period
            self.user.valid_until = now() + datetime.timedelta(
                days=settings.SSO_VALIDATION_PERIOD_DAYS)
        self.user.save()

        return self.registrationprofile
Beispiel #14
0
Datei: forms.py Projekt: g10f/sso
class OrganisationBaseForm(BaseForm):
    google_maps_url = bootstrap.ReadOnlyField(label=_("Google Maps"))

    class Meta:
        model = Organisation

        fields = ('name_native', 'homepage', 'source_urls', 'google_plus_page',
                  'facebook_page', 'twitter_page', 'founded',
                  'coordinates_type', 'is_private', 'is_live', 'location',
                  'neighbour_distance', 'transregional_distance', 'timezone')
        years_to_display = range(datetime.datetime.now().year - 100,
                                 datetime.datetime.now().year + 1)
        widgets = {
            'homepage':
            bootstrap.URLInput(attrs={'size': 50}),
            'source_urls':
            bootstrap.Textarea(attrs={'rows': '3'}),
            'google_plus_page':
            bootstrap.URLInput(attrs={'size': 50}),
            'facebook_page':
            bootstrap.URLInput(attrs={'size': 50}),
            'twitter_page':
            bootstrap.URLInput(attrs={'size': 50}),
            'association':
            bootstrap.Select(),
            'name':
            bootstrap.TextInput(attrs={'size': 50}),
            'name_native':
            bootstrap.TextInput(attrs={'size': 50}),
            'founded':
            bootstrap.SelectDateWidget(years=years_to_display),
            'coordinates_type':
            bootstrap.Select(),
            'center_type':
            bootstrap.Select(),
            'is_private':
            bootstrap.CheckboxInput(),
            'is_active':
            bootstrap.CheckboxInput(),
            'is_live':
            bootstrap.CheckboxInput(),
            'timezone':
            bootstrap.Select2(),
            'location':
            bootstrap.OSMWidget(),
            'neighbour_distance':
            bootstrap.TextInput(attrs={
                'type': 'number',
                'step': '0.001'
            }),
            'transregional_distance':
            bootstrap.TextInput(attrs={
                'type': 'number',
                'step': '0.001'
            }),
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')  # remove custom user keyword
        super().__init__(*args, **kwargs)
        if self.instance.location:
            self.fields[
                'google_maps_url'].initial = self.instance.google_maps_url

    def clean(self):
        cleaned_data = super().clean()

        # check combination of coordinates_type location
        coordinates_type = cleaned_data['coordinates_type']
        location = cleaned_data['location']
        if location and coordinates_type == '':
            msg = _("Please select a coordinates type.")
            self.add_error(
                'coordinates_type',
                ValidationError(msg,
                                params={'active': 'organisationaddress_set'}))
        if not location and coordinates_type:
            cleaned_data['coordinates_type'] = ''

        return cleaned_data