Exemple #1
0
 class Meta:
     model = GroupEmail
     fields = ['homepage', 'name', 'is_guide_email']
     widgets = {
         'homepage': bootstrap.TextInput(attrs={'size': 50}),
         'name': bootstrap.TextInput(attrs={'size': 50}),
     }
Exemple #2
0
 class Meta:
     model = AdminRegion
     fields = ('name', 'homepage', 'organisation_country', 'is_active')
     widgets = {
         'homepage': bootstrap.TextInput(attrs={'size': 50}),
         'organisation_country': bootstrap.Select2(),
         'name': bootstrap.TextInput(attrs={'size': 50}),
     }
Exemple #3
0
 class Meta:
     model = Application
     fields = ('title', 'url', 'notes', 'is_active', 'is_internal')
     widgets = {
         'title': bootstrap.TextInput(attrs={'size': 50}),
         'notes': bootstrap.Textarea(attrs={'rows': '5'}),
         'url': bootstrap.TextInput(attrs={'size': 50}),
         'is_active': bootstrap.CheckboxInput(),
         'is_internal': bootstrap.CheckboxInput(),
     }
Exemple #4
0
    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'
            }),
        }
Exemple #5
0
class ContactForm(forms.Form):
    name = forms.CharField(label=_("Name"),
                           max_length=100,
                           widget=bootstrap.TextInput())
    email = forms.EmailField(label=_("Email address"),
                             max_length=75,
                             widget=bootstrap.TextInput())
    subject = forms.CharField(label=_("Subject"), widget=bootstrap.TextInput())
    message = forms.CharField(label=_("Message"),
                              widget=bootstrap.Textarea(attrs={
                                  'cols': 40,
                                  'rows': 5
                              }))
    captcha = ReCaptchaField()
Exemple #6
0
 class Meta:
     model = Client
     fields = ('application', 'uuid', 'client_secret', 'name', 'type',
               'redirect_uris', 'post_logout_redirect_uris', 'notes',
               'is_active', 'scopes')
     widgets = {
         'application': bootstrap.HiddenInput(),
         'name': bootstrap.TextInput(attrs={'size': 50}),
         'client_secret': bootstrap.TextInput(attrs={'readonly': True}),
         'notes': bootstrap.Textarea(attrs={'rows': '3'}),
         'redirect_uris': bootstrap.Textarea(attrs={'rows': '3'}),
         'post_logout_redirect_uris':
         bootstrap.Textarea(attrs={'rows': '3'}),
         'is_active': bootstrap.CheckboxInput(),
     }
Exemple #7
0
 class Meta:
     model = OrganisationPhoneNumber
     fields = ('phone_type', 'phone')
     widgets = {
         'phone_type': bootstrap.Select(),
         'phone': bootstrap.TextInput(attrs={'size': 50}),
     }
Exemple #8
0
class AuthenticationTokenForm(forms.Form):
    labels = {
        'otp_token': capfirst(_("one-time password")),
    }
    otp_token = forms.IntegerField(
        label=labels.get('otp_token'),
        min_value=1,
        max_value=int('9' * totp_digits()),
        widget=bootstrap.TextInput(
            attrs={
                'placeholder': labels.get('otp_token'),
                'autofocus': True,
                'autocomplete': 'one-time-code',
                'class': 'form-control-lg'
            }))

    def __init__(self, **kwargs):
        self.user = kwargs.pop('user')
        self.device = None
        super().__init__(**kwargs)

    def clean(self):
        if self.user is None:
            raise forms.ValidationError(_('User is none'))

        token = self.cleaned_data.get('otp_token')
        self.device = self._verify_token(token)
        if self.device is None:
            raise forms.ValidationError(_('One-time code does not match.'))

        return self.cleaned_data

    def _verify_token(self, token):
        device = match_token(self.user, token)
        return device
Exemple #9
0
 class Meta:
     model = OrganisationPicture
     fields = ('picture', 'title', 'description', 'order')
     widgets = {
         'title': bootstrap.TextInput(attrs={'size': 50}),
         'description': bootstrap.Textarea(),
         'picture': bootstrap.ImageWidget(),
     }
Exemple #10
0
 class Meta:
     model = UserPhoneNumber
     fields = ('phone_type', 'phone', 'primary')
     widgets = {
         'phone_type': bootstrap.Select(),
         'phone': bootstrap.TextInput(attrs={'size': 50}),
         'primary': bootstrap.CheckboxInput()
     }
Exemple #11
0
 class Meta:
     model = UserAddress
     fields = ('primary', 'address_type', 'addressee', 'street_address',
               'city', 'city_native', 'postal_code', 'country', 'region')
     widgets = {
         'primary': bootstrap.CheckboxInput(),
         'address_type': bootstrap.Select(),
         'addressee': bootstrap.TextInput(attrs={'size': 50}),
         'street_address': bootstrap.Textarea(attrs={
             'cols': 50,
             'rows': 2
         }),
         'city': bootstrap.TextInput(attrs={'size': 50}),
         'city_native': bootstrap.TextInput(attrs={'size': 50}),
         'postal_code': bootstrap.TextInput(attrs={'size': 50}),
         'country': bootstrap.Select2(),
         'region': bootstrap.TextInput(attrs={'size': 50}),
     }
Exemple #12
0
class EmailAuthenticationForm(AuthenticationForm):
    labels = {
        'username': capfirst(_("Email address or Username")),
        'password': capfirst(_("Password"))
    }
    username = forms.CharField(
        max_length=75,
        error_messages={
            'required': _('Please enter your Email address or Username.')
        },
        label=labels.get('username'),
        widget=bootstrap.TextInput(
            attrs={
                'placeholder': labels.get('username'),
                'autofocus': True,
                'autocapitalize': 'none',
                'class': 'form-control-lg',
                'autocomplete': 'username'
            }))
    password = forms.CharField(
        label=labels.get('password'),
        error_messages={'required': _('Please enter your Password.')},
        widget=bootstrap.PasswordInput(
            attrs={
                'placeholder': labels.get('password'),
                'class': 'form-control-lg',
                'autocomplete': 'current-password'
            }))
    remember_me = forms.BooleanField(
        label=_('Remember me'),
        help_text=string_format(
            _('Stay logged in for %(days)d days'),
            {'days': timedelta(seconds=settings.SESSION_COOKIE_AGE).days}),
        required=False,
        widget=bootstrap.CheckboxInput())
    error_messages = {
        'invalid_login':
        _("Please enter a correct %(username)s and password. Note that both fields may be case-sensitive."
          ),
        'inactive':
        _("This account is inactive."),
        'expired':
        _("This account has expired. Please contact the user administrator in your organisation %s."
          ),
        'whitespaces':
        _("Please enter your Email address or Username without whitespaces at the beginning or end."
          ),
    }

    def clean_username(self):
        # check if there are whitespaces at the beginning or end of the username
        data = self.cleaned_data['username']
        if data and data != data.strip():
            raise forms.ValidationError(self.error_messages['whitespaces'],
                                        code='whitespaces')
        return data
Exemple #13
0
    class Meta:
        model = OrganisationCountry

        fields = ('association', 'homepage', 'country_groups', 'country',
                  'is_active')
        widgets = {
            'homepage': bootstrap.TextInput(attrs={'size': 50}),
            'association': bootstrap.Select(),
            'country': bootstrap.Select2(),
        }
Exemple #14
0
class TOTPDeviceForm(CredentialSetupForm):
    token = forms.IntegerField(
        label=_("One-time code"),
        min_value=0,
        max_value=int('9' * totp_digits()),
        widget=bootstrap.TextInput(attrs={'autofocus': True}))
    key = forms.CharField(label=_('Key'), widget=forms.HiddenInput())

    error_messages = {
        'invalid_token': _('Invalid token value: %(token)s.'),
    }

    def __init__(self, user, issuer, **kwargs):
        super().__init__(**kwargs)
        self.digits = totp_digits()
        self.user = user
        self.issuer = issuer
        self.device = None

    @property
    def qr_code(self):
        key = self.data.get('key', self.initial['key'])
        rawkey = unhexlify(key.encode('ascii'))
        b32key = b32encode(rawkey).decode('utf-8')
        return get_qrcode_data_url(b32key, force_str(self.user), self.issuer)

    def clean(self):
        cd = super().clean()
        if 'token' in cd:
            token = cd.get("token")
            self.device = TOTPDevice(user=self.user,
                                     key=cd['key'],
                                     digits=self.digits,
                                     tolerance=2)

            if not self.device.verify_token(token):
                raise forms.ValidationError(
                    self.error_messages['invalid_token'],
                    params={'token': token})

    def save(self):
        self.device.confirmed = True
        self.device.name = self.cleaned_data['name']
        self.device.save()
        if not hasattr(self.user, 'sso_auth_profile'):
            Profile.objects.create(user=self.user,
                                   default_device_id=self.device.device_id,
                                   is_otp_enabled=True)

        return self.device
Exemple #15
0
class SendMailForm(forms.Form):
    subject = forms.CharField(label=_("Subject"),
                              required=True,
                              max_length=1024,
                              widget=bootstrap.TextInput())
    message = forms.CharField(label=_("Message"),
                              required=True,
                              max_length=4096,
                              widget=bootstrap.Textarea(attrs={
                                  'cols': 40,
                                  'rows': 20
                              }))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        self.instance = kwargs.pop('instance')
        super().__init__(*args, **kwargs)
Exemple #16
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
Exemple #17
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
Exemple #18
0
 class Meta:
     model = OrganisationAddress
     fields = ('address_type', 'addressee', 'careof', 'street_address',
               'city', 'city_native', 'postal_code', 'country', 'region')
     widgets = {
         'address_type': bootstrap.Select(attrs={'class': 'address_type'}),
         'addressee': bootstrap.TextInput(attrs={'size': 50}),
         'careof': bootstrap.TextInput(attrs={'size': 50}),
         'street_address': bootstrap.Textarea(attrs={
             'cols': 50,
             'rows': 2
         }),
         'city': bootstrap.TextInput(attrs={'size': 50}),
         'city_native': bootstrap.TextInput(attrs={'size': 50}),
         'postal_code': bootstrap.TextInput(attrs={'size': 50}),
         'region': bootstrap.TextInput(attrs={'size': 50}),
     }
Exemple #19
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
Exemple #20
0
class CredentialSetupForm(forms.Form):
    name = forms.CharField(
        max_length=255,
        required=False,
        widget=bootstrap.TextInput(),
        help_text=_("The human-readable name of this device."))
Exemple #21
0
class UserSelfRegistrationForm(forms.Form):
    """
    used in for the user self registration
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'duplicate_email': _("A user with that email address already exists."),
    }
    first_name = forms.CharField(
        label=_('First name'),
        required=True,
        max_length=30,
        widget=bootstrap.TextInput(
            attrs={'placeholder': capfirst(_('first name'))}))
    last_name = forms.CharField(
        label=_('Last name'),
        required=True,
        max_length=30,
        widget=bootstrap.TextInput(
            attrs={'placeholder': capfirst(_('last name'))}))
    email = forms.EmailField(label=_('Email'),
                             required=True,
                             widget=bootstrap.EmailInput())
    picture = Base64ImageField(
        label=_('Your picture'),
        help_text=
        _('Please use a photo of your face. We are using it also to validate your registration.'
          ),
        widget=bootstrap.ClearableBase64ImageWidget(
            attrs={
                'max_file_size': User.MAX_PICTURE_SIZE,
                'width': User.PICTURE_WIDTH,
                'height': User.PICTURE_HEIGHT,
            }))
    known_person1_first_name = forms.CharField(label=_("First name"),
                                               max_length=100,
                                               widget=bootstrap.TextInput())
    known_person1_last_name = forms.CharField(label=_("Last name"),
                                              max_length=100,
                                              widget=bootstrap.TextInput())
    known_person2_first_name = forms.CharField(label=_("First name"),
                                               max_length=100,
                                               widget=bootstrap.TextInput())
    known_person2_last_name = forms.CharField(label=_("Last name"),
                                              max_length=100,
                                              widget=bootstrap.TextInput())
    about_me = forms.CharField(
        label=_('About me'),
        required=False,
        help_text=
        _('If you would like to tell us something about yourself, please do so in this box.'
          ),
        widget=bootstrap.Textarea(attrs={
            'cols': 40,
            'rows': 5
        }))
    country = forms.ModelChoiceField(
        queryset=Country.objects.filter(active=True),
        label=_("Country"),
        widget=bootstrap.Select2())
    city = forms.CharField(label=_("City"),
                           max_length=100,
                           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())
    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)))

    def clean_email(self):
        # Check if email is unique,
        email = self.cleaned_data["email"]
        try:
            get_user_model().objects.get_by_email(email)
        except ObjectDoesNotExist:
            return email
        raise forms.ValidationError(self.error_messages['duplicate_email'])

    def clean(self):
        """
        if the user clicks the edit_again button a ValidationError is raised, to
        display the form again. (see post_post method in FormPreview)
        """
        edit_again = self.data.get("_edit_again")
        if edit_again:
            raise forms.ValidationError('_edit_again', '_edit_again')

        return super().clean()

    @staticmethod
    def save_data(data, username_generator=default_username_generator):

        new_user = get_user_model()()
        new_user.username = username_generator(data.get('first_name'),
                                               data.get('last_name'))
        new_user.first_name = data.get('first_name')
        new_user.last_name = data.get('last_name')
        new_user.language = data.get('language')
        new_user.timezone = data.get('timezone')
        new_user.gender = data.get('gender')
        new_user.dob = data.get('dob')
        new_user.is_active = False
        new_user.set_unusable_password()
        if 'picture' in data:
            new_user.picture = data.get('picture')

        new_user.save()

        new_user.create_primary_email(email=data.get('email'))

        user_address = UserAddress()
        user_address.primary = True
        user_address.user = new_user
        user_address.address_type = 'home'
        user_address.country = data['country']
        user_address.city = data['city']
        user_address.addressee = "%s %s" % (data.get('first_name'),
                                            data.get('last_name'))
        user_address.save()

        registration_profile = RegistrationProfile.objects.create(
            user=new_user)
        registration_profile.about_me = data['about_me']
        registration_profile.known_person1_first_name = data[
            'known_person1_first_name']
        registration_profile.known_person1_last_name = data[
            'known_person1_last_name']
        registration_profile.known_person2_first_name = data[
            'known_person2_first_name']
        registration_profile.known_person2_last_name = data[
            'known_person2_last_name']
        registration_profile.save()
        return registration_profile
Exemple #22
0
class ClientForm(BaseForm):
    can_access_all_users = forms.BooleanField(label=_('Can access all users'),
                                              required=False,
                                              widget=bootstrap.CheckboxInput())
    type = forms.ChoiceField(
        label=_('Type'),
        help_text=mark_safe_lazy(
            _("Confidential client (can store a secret) or public client for <a href='https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowSteps'>authorisation code flow</a> "
              "or service account client with <a href='https://datatracker.ietf.org/doc/html/rfc6749#section-4.4'>client credentials grant</a>."
              )),
        required=True,
        choices=ALLOWED_CLIENT_TYPES,
        widget=bootstrap.Select())
    uuid = forms.UUIDField(
        label=_('Client ID'),
        required=True,
        initial=uuid.uuid4,
        widget=bootstrap.TextInput(attrs={'readonly': True}))
    scopes = forms.MultipleChoiceField(label=_('Scopes'),
                                       required=False,
                                       initial=['openid'],
                                       choices=ALLOWED_SCOPES,
                                       widget=bootstrap.Select2Multiple())

    class Meta:
        model = Client
        fields = ('application', 'uuid', 'client_secret', 'name', 'type',
                  'redirect_uris', 'post_logout_redirect_uris', 'notes',
                  'is_active', 'scopes')
        widgets = {
            'application': bootstrap.HiddenInput(),
            'name': bootstrap.TextInput(attrs={'size': 50}),
            'client_secret': bootstrap.TextInput(attrs={'readonly': True}),
            'notes': bootstrap.Textarea(attrs={'rows': '3'}),
            'redirect_uris': bootstrap.Textarea(attrs={'rows': '3'}),
            'post_logout_redirect_uris':
            bootstrap.Textarea(attrs={'rows': '3'}),
            'is_active': bootstrap.CheckboxInput(),
        }

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')  # remove custom user keyword
        # initialize scopes
        if kwargs.get('instance'):
            instance = kwargs['instance']
            if instance.scopes:
                kwargs['initial']['scopes'] = instance.scopes.split()
            kwargs['initial'][
                'can_access_all_users'] = instance.has_access_to_all_users

        super().__init__(*args, **kwargs)

    def clean_scopes(self):
        scopes = self.cleaned_data['scopes']
        return ' '.join(scopes)

    def clean(self):
        cleaned_data = super().clean()
        client_type = cleaned_data.get("type")
        client_secret = cleaned_data.get("client_secret")
        redirect_uris = cleaned_data.get("redirect_uris")
        if client_type in ['web', 'service']:
            if not client_secret:
                self.add_error(
                    'client_secret',
                    ValidationError(
                        "A client secret is required for this client type."))
        if client_type == "native":
            cleaned_data['client_secret'] = ''
        if client_type in ['web', 'native']:
            if not redirect_uris:
                self.add_error(
                    'redirect_uris',
                    ValidationError(
                        "A redirect uri is required for this client type."))
        else:
            cleaned_data['redirect_uris'] = ''
            cleaned_data['post_logout_redirect_uris'] = ''
        return self.cleaned_data

    def save(self, commit=True):
        instance = super().save(commit)
        # service clients need a user associated with
        if self.instance.type == 'service':
            instance.ensure_service_user_exists()

            can_access_all_users = self.cleaned_data['can_access_all_users']
            if can_access_all_users is not None:
                instance.set_access_to_all_users(can_access_all_users,
                                                 self.user)
        else:
            self.instance.remove_service_user()

        return instance
Exemple #23
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
Exemple #24
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
Exemple #25
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"]])
Exemple #26
0
 class Meta:
     model = Device
     fields = ['name']
     widgets = {'name': bootstrap.TextInput()}
Exemple #27
0
class UserAddForm(mixins.UserRolesMixin, mixins.UserNoteMixin,
                  forms.ModelForm):
    """
    form for SSO User Admins for adding users in the frontend
    """
    email = forms.EmailField(label=_('Email'),
                             required=True,
                             widget=bootstrap.EmailInput())
    first_name = forms.CharField(
        label=_('First name'),
        required=True,
        widget=bootstrap.TextInput(
            attrs={'placeholder': capfirst(_('first name'))}))
    last_name = forms.CharField(
        label=_('Last name'),
        required=True,
        widget=bootstrap.TextInput(
            attrs={'placeholder': capfirst(_('last name'))}))
    gender = forms.ChoiceField(label=_('Gender'),
                               required=True,
                               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)))
    notes = forms.CharField(label=_("Notes"),
                            required=False,
                            max_length=1024,
                            widget=bootstrap.Textarea(attrs={
                                'cols': 40,
                                'rows': 10
                            }))
    organisations = forms.ModelChoiceField(
        queryset=None,
        required=settings.SSO_ORGANISATION_REQUIRED,
        label=_("Organisation"),
        widget=bootstrap.Select2())
    application_roles = forms.ModelMultipleChoiceField(
        queryset=None,
        required=False,
        widget=bootstrap.FilteredSelectMultiple(_("Application roles")),
        label=_("Additional application roles"),
        help_text=mixins.UserRolesMixin.application_roles_help)

    role_profiles = forms.ModelMultipleChoiceField(
        queryset=None,
        required=False,
        widget=bootstrap.CheckboxSelectMultiple(),
        label=_("Role profiles"),
        help_text=mixins.UserRolesMixin.role_profiles_help)

    error_messages = {
        'duplicate_email': _("A user with that email address already exists."),
    }

    class Meta:
        model = User
        fields = ("first_name", "last_name", 'gender', 'dob', 'notes',
                  'application_roles', 'role_profiles')

    def __init__(self, request, *args, **kwargs):
        self.request = request
        user = request.user
        super().__init__(*args, **kwargs)
        self.fields[
            'application_roles'].queryset = user.get_administrable_application_roles(
            )
        self.fields[
            'role_profiles'].queryset = user.get_administrable_role_profiles()
        self.fields['organisations'].queryset = user.get_administrable_user_organisations(). \
            filter(is_active=True, association__is_selectable=True)
        if not user.has_perm("accounts.access_all_users"):
            self.fields['organisations'].required = True

    def clean_email(self):
        # Check if email is unique,
        email = self.cleaned_data["email"]
        try:
            User.objects.get_by_email(email)
            raise forms.ValidationError(self.error_messages['duplicate_email'])
        except ObjectDoesNotExist:
            pass

        return email

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(get_random_string(40))
        user.username = default_username_generator(
            capfirst(self.cleaned_data.get('first_name')),
            capfirst(self.cleaned_data.get('last_name')))

        organisation = self.cleaned_data["organisations"]
        if is_validation_period_active(organisation):
            user.valid_until = now() + datetime.timedelta(
                days=settings.SSO_VALIDATION_PERIOD_DAYS)
        user.save()

        # use mixin to send notification
        self.user = user
        current_user = self.request.user
        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)

        self.create_note_if_required(current_user, self.cleaned_data)
        user.create_primary_email(email=self.cleaned_data["email"])
        return user