class OrganisationRegionAdminCreateForm(EmailForwardMixin, OrganisationRegionAdminForm): """ A form for a regional admin to create new centers the selectable countries are limited to the countries from the regions with additionally email_forward field """ email_forward = EmailFieldLower( required=True, label=_("Email forwarding address"), help_text=_( 'The primary email forwarding address for the organisation'), widget=bootstrap.EmailInput()) def clean(self): super().clean() # check email forward return self.check_email_forward() def save(self, commit=True): """ creating a new center with a forward address """ instance = super().save(commit) return self.save_email_forward(instance)
class Meta: model = UserEmail fields = ('email', 'primary', 'confirmed') widgets = { 'email': bootstrap.EmailInput(), 'primary': bootstrap.CheckboxInput(), 'confirmed': bootstrap.CheckboxInput() }
class PasswordResetForm(DjangoPasswordResetForm): """ changes from django default PasswordResetForm: * validates that the email exists and shows an error message if not. * adds an expiration_date to the rendering context """ error_messages = { 'unknown': _("That email address doesn't have an associated user account. Are you sure you've registered?" ), 'unusable': _("The user account associated with this email address cannot reset the password." ), 'not_activated': _("You can not reset your password jet, because your account is waiting for initial " "activation."), } email = forms.EmailField(label=_("Email"), max_length=254, widget=bootstrap.EmailInput()) def clean_email(self): """ Validates that an active user exists with the given email address. """ email = self.cleaned_data["email"] try: user = User.objects.get_by_confirmed_or_primary_email(email) if user.has_usable_password() and user.is_active: return email # no user with this email and a usable password found raise forms.ValidationError(self.error_messages['unusable']) except ObjectDoesNotExist: raise forms.ValidationError(self.error_messages['unknown']) def save(self, domain_override=None, subject_template_name='registration/password_reset_subject.txt', email_template_name='registration/password_reset_email.html', use_https=False, token_generator=default_token_generator, from_email=None, request=None, html_email_template_name='registration/password_reset_email.html', extra_email_context=None): email = self.cleaned_data["email"] current_site = get_current_site(request) site_name = settings.SSO_SITE_NAME domain = current_site.domain user = User.objects.get_by_confirmed_or_primary_email(email) # Make sure that no email is sent to a user that actually has # a password marked as unusable if not user.has_usable_password(): logger.error("user has unusable password") expiration_date = now() + datetime.timedelta( seconds=settings.PASSWORD_RESET_TIMEOUT) c = { 'first_name': user.first_name, 'email': user.primary_email(), 'domain': domain, 'site_name': site_name, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'user': user, 'token': token_generator.make_token(user), 'protocol': 'https' if use_https else 'http', 'expiration_date': expiration_date } subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = loader.render_to_string(email_template_name, c) html_message = None # loader.render_to_string(html_email_template_name, c) user.email_user(subject, message, from_email, html_message=html_message)
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
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
class GroupEmailForm(BaseForm): email_value = EmailFieldLower(required=True, label=_("Email address"), widget=bootstrap.EmailInput()) permission = forms.ChoiceField(label=_('Permission'), choices=Email.PERMISSION_CHOICES, widget=bootstrap.Select()) is_active = forms.BooleanField(required=False, label=_("Active"), widget=bootstrap.CheckboxInput()) class Meta: model = GroupEmail fields = ['homepage', 'name', 'is_guide_email'] widgets = { 'homepage': bootstrap.TextInput(attrs={'size': 50}), 'name': bootstrap.TextInput(attrs={'size': 50}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) try: email = self.instance.email self.fields['is_active'].initial = email.is_active self.fields['email_value'].initial = force_str(email) self.fields['permission'].initial = email.permission except ObjectDoesNotExist: self.fields['is_active'].initial = True def clean_email_value(self): """ the new email address must .. """ email_value = self.cleaned_data['email_value'] if Email.objects.filter(email=email_value).exclude( groupemail=self.instance).exists(): msg = _('The email address already exists') raise ValidationError(msg) return email_value def save(self, commit=True): cd = self.changed_data if 'email_value' in cd or 'permission' in cd or 'is_active' in cd: created = False try: email = self.instance.email except ObjectDoesNotExist: email = Email(email_type=GROUP_EMAIL_TYPE) created = True email.is_active = self.cleaned_data['is_active'] email.email = self.cleaned_data['email_value'] email.permission = self.cleaned_data['permission'] email.save() if created: self.instance.email = email instance = super().save(commit) return instance