Ejemplo n.º 1
0
 def form_valid(self, form):
     profile = self.request.user.profile
     if (UserProfilesSettings.for_site(
         self.request.site).activate_dob) and not (
         UserProfilesSettings.for_site(
             self.request.site).capture_dob_on_reg):
             profile.date_of_birth = form.cleaned_data["date_of_birth"]
     if (UserProfilesSettings.for_site(
         self.request.site).activate_display_name) and not (
         UserProfilesSettings.for_site(
             self.request.site).capture_display_name_on_reg):
             profile.alias = form.cleaned_data["alias"]
     if (UserProfilesSettings.for_site(
         self.request.site).activate_gender) and not (
         UserProfilesSettings.for_site(
             self.request.site).capture_gender_on_reg):
             profile.gender = form.cleaned_data["gender"]
     if (UserProfilesSettings.for_site(
         self.request.site).activate_location) and not (
         UserProfilesSettings.for_site(
             self.request.site).capture_location_on_reg):
             profile.location = form.cleaned_data["location"]
     if (UserProfilesSettings.for_site(
         self.request.site).activate_education_level) and not (
         UserProfilesSettings.for_site(
             self.request.site).capture_education_level_on_reg):
             profile.education_level = form.cleaned_data["education_level"]
     profile.save()
     return HttpResponseRedirect(form.cleaned_data.get('next', '/'))
Ejemplo n.º 2
0
 def form_valid(self, form):
     profile = self.request.user.profile
     if (UserProfilesSettings.for_site(self.request.site).activate_dob
         ) and not (UserProfilesSettings.for_site(
             self.request.site).capture_dob_on_reg):
         profile.date_of_birth = form.cleaned_data["date_of_birth"]
     if (UserProfilesSettings.for_site(
             self.request.site).activate_display_name
         ) and not (UserProfilesSettings.for_site(
             self.request.site).capture_display_name_on_reg):
         profile.alias = form.cleaned_data["alias"]
     if (UserProfilesSettings.for_site(self.request.site).activate_gender
         ) and not (UserProfilesSettings.for_site(
             self.request.site).capture_gender_on_reg):
         profile.gender = form.cleaned_data["gender"]
     if (UserProfilesSettings.for_site(self.request.site).activate_location
         ) and not (UserProfilesSettings.for_site(
             self.request.site).capture_location_on_reg):
         profile.location = form.cleaned_data["location"]
     if (UserProfilesSettings.for_site(
             self.request.site).activate_education_level
         ) and not (UserProfilesSettings.for_site(
             self.request.site).capture_education_level_on_reg):
         profile.education_level = form.cleaned_data["education_level"]
     profile.save()
     return HttpResponseRedirect(form.cleaned_data.get('next', '/'))
Ejemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        questions = kwargs.pop("questions", [])
        request = kwargs.pop("request", [])
        super(RegistrationForm, self).__init__(*args, **kwargs)
        if not request:
            site = Site.objects.get(is_default_site=True)
            self.profile_settings = UserProfilesSettings.for_site(site)
        else:
            self.profile_settings = UserProfilesSettings.for_site(request.site)

        self.fields['mobile_number'].required = (
            self.profile_settings.mobile_number_required and
            self.profile_settings.show_mobile_number_field and
            self.profile_settings.country_code)

        self.fields['email'].required = (
            self.profile_settings.email_required and
            self.profile_settings.show_email_field)
        self.fields['alias'].required = (
            self.profile_settings.activate_display_name and
            self.profile_settings.capture_display_name_on_reg and
            self.profile_settings.display_name_required)
        self.fields['date_of_birth'].required = (
            self.profile_settings.activate_dob and
            self.profile_settings.capture_dob_on_reg and
            self.profile_settings.dob_required)
        self.fields['gender'].required = (
            self.profile_settings.activate_gender and
            self.profile_settings.capture_gender_on_reg and
            self.profile_settings.gender_required)
        self.fields['location'].required = (
            self.profile_settings.activate_location and
            self.profile_settings.capture_location_on_reg and
            self.profile_settings.location_required)
        self.fields['education_level'].required = (
            self.profile_settings.activate_education_level and
            self.profile_settings.capture_education_level_on_reg and
            self.profile_settings.activate_education_level_required)

        # Security questions fields are created dynamically.
        # This allows any number of security questions to be specified
        for index, question in enumerate(questions):
            self.fields["question_%s" % index] = forms.CharField(
                label=question.title,
                widget=forms.TextInput(
                    attrs=dict(
                        max_length=150,
                    )
                )
            )
            self.fields["question_%s" % index].required = (
                self.profile_settings.show_security_question_fields and
                self.profile_settings.security_questions_required
            )
Ejemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        request = kwargs.pop("request", [])
        super(DoneForm, self).__init__(*args, **kwargs)
        if not request:
            site = Site.objects.get(is_default_site=True)
            profile_settings = UserProfilesSettings.for_site(site)
        else:
            profile_settings = UserProfilesSettings.for_site(request.site)

        if self.fields.get('mobile_number'):
            self.fields['mobile_number'].required = (
                profile_settings.mobile_number_required
                and profile_settings.show_mobile_number_field
                and profile_settings.country_code)

        if self.fields.get('email'):
            self.fields['email'].required = (profile_settings.email_required
                                             and
                                             profile_settings.show_email_field)

        if self.fields.get('alias'):
            self.fields['alias'].required = (
                profile_settings.activate_display_name
                and not profile_settings.capture_display_name_on_reg
                and profile_settings.display_name_required)

        if self.fields.get('date_of_birth'):
            self.fields['date_of_birth'].required = (
                profile_settings.activate_dob
                and not profile_settings.capture_dob_on_reg
                and profile_settings.dob_required)

        if self.fields.get('gender'):
            self.fields['gender'].required = (
                profile_settings.activate_gender
                and not profile_settings.capture_gender_on_reg
                and profile_settings.gender_required)

        if self.fields.get('location'):
            self.fields['location'].required = (
                profile_settings.activate_location
                and not profile_settings.capture_location_on_reg
                and profile_settings.location_required)

        if self.fields.get('education_level'):
            self.fields['education_level'].required = (
                profile_settings.activate_education_level
                and not profile_settings.capture_education_level_on_reg
                and profile_settings.activate_education_level_required)
Ejemplo n.º 5
0
    def __init__(self, *args, **kwargs):
        request = kwargs.pop("request", [])
        super(DoneForm, self).__init__(*args, **kwargs)
        if not request:
            site = Site.objects.get(is_default_site=True)
            profile_settings = UserProfilesSettings.for_site(site)
        else:
            profile_settings = UserProfilesSettings.for_site(request.site)

        if self.fields.get('mobile_number'):
            self.fields['mobile_number'].required = (
                profile_settings.mobile_number_required and
                profile_settings.show_mobile_number_field and
                profile_settings.country_code)

        if self.fields.get('email'):
            self.fields['email'].required = (
                profile_settings.email_required and
                profile_settings.show_email_field)

        if self.fields.get('alias'):
            self.fields['alias'].required = (
                profile_settings.activate_display_name and
                not profile_settings.capture_display_name_on_reg and
                profile_settings.display_name_required)

        if self.fields.get('date_of_birth'):
            self.fields['date_of_birth'].required = (
                profile_settings.activate_dob and
                not profile_settings.capture_dob_on_reg and
                profile_settings.dob_required)

        if self.fields.get('gender'):
            self.fields['gender'].required = (
                profile_settings.activate_gender and
                not profile_settings.capture_gender_on_reg and
                profile_settings.gender_required)

        if self.fields.get('location'):
            self.fields['location'].required = (
                profile_settings.activate_location and
                not profile_settings.capture_location_on_reg and
                profile_settings.location_required)

        if self.fields.get('education_level'):
            self.fields['education_level'].required = (
                profile_settings.activate_education_level and
                not profile_settings.capture_education_level_on_reg and
                profile_settings.activate_education_level_required)
Ejemplo n.º 6
0
    def __init__(self, *args, **kwargs):
        questions = kwargs.pop("questions", [])
        request = kwargs.pop("request", [])
        super(RegistrationForm, self).__init__(*args, **kwargs)
        if not request:
            site = Site.objects.get(is_default_site=True)
            self.profile_settings = UserProfilesSettings.for_site(site)
        else:
            self.profile_settings = UserProfilesSettings.for_site(request.site)

        self.fields['mobile_number'].required = (
            self.profile_settings.mobile_number_required
            and self.profile_settings.show_mobile_number_field
            and self.profile_settings.country_code)

        self.fields['email'].required = (
            self.profile_settings.email_required
            and self.profile_settings.show_email_field)
        self.fields['alias'].required = (
            self.profile_settings.activate_display_name
            and self.profile_settings.capture_display_name_on_reg
            and self.profile_settings.display_name_required)
        self.fields['date_of_birth'].required = (
            self.profile_settings.activate_dob
            and self.profile_settings.capture_dob_on_reg
            and self.profile_settings.dob_required)
        self.fields['gender'].required = (
            self.profile_settings.activate_gender
            and self.profile_settings.capture_gender_on_reg
            and self.profile_settings.gender_required)
        self.fields['location'].required = (
            self.profile_settings.activate_location
            and self.profile_settings.capture_location_on_reg
            and self.profile_settings.location_required)
        self.fields['education_level'].required = (
            self.profile_settings.activate_education_level
            and self.profile_settings.capture_education_level_on_reg
            and self.profile_settings.activate_education_level_required)

        # Security questions fields are created dynamically.
        # This allows any number of security questions to be specified
        for index, question in enumerate(questions):
            self.fields["question_%s" % index] = forms.CharField(
                label=question.title,
                widget=forms.TextInput(attrs=dict(max_length=150, )))
            self.fields["question_%s" % index].required = (
                self.profile_settings.show_security_question_fields
                and self.profile_settings.security_questions_required)
Ejemplo n.º 7
0
    def setUp(self):
        self.main = self.mk_main(title='main1',
                                 slug='main1',
                                 path='00010002',
                                 url_path='/main1/')
        self.main2 = self.mk_main(title='main2',
                                  slug='main2',
                                  path='00010003',
                                  url_path='/main2/')
        self.client = Client(HTTP_HOST=self.main.get_site().hostname)

        for main in Main.objects.all():
            profile_settings = UserProfilesSettings.for_site(main.get_site())
            profile_settings.show_security_question_fields = True
            profile_settings.security_questions_required = True
            profile_settings.num_security_questions = 2
            profile_settings.activate_gender = True
            profile_settings.capture_gender_on_reg = True
            profile_settings.gender_required = True
            profile_settings.save()

            security_index = SecurityQuestionIndexPage.objects.descendant_of(
                main).first()
            for i in range(1, 3):
                question = SecurityQuestion(title='question_{0}'.format(i))
                security_index.add_child(instance=question)
                question.save_revision().publish()
Ejemplo n.º 8
0
 def setUp(self):
     self.main = self.mk_main(
         title='main1', slug='main1', path='00010002', url_path='/main1/')
     self.client = Client(HTTP_HOST=self.main.get_site().hostname)
     profile_settings = UserProfilesSettings.for_site(self.main.get_site())
     profile_settings.activate_gender = True
     profile_settings.capture_gender_on_reg = True
     profile_settings.gender_required = True
     profile_settings.save()
Ejemplo n.º 9
0
 def is_valid(self):
     if 'mobile_number' in self.data:
         if not self.data['mobile_number'].startswith('+'):
             site = Site.objects.get(is_default_site=True)
             profile_settings = UserProfilesSettings.for_site(site)
             number = self.data['mobile_number']
             if number:
                 if number.startswith('0'):
                     number = number[1:]
                 number = profile_settings.country_code + \
                     number
             self.data = self.data.copy()
             self.data['mobile_number'] = number
     valid = super(EditProfileForm, self).is_valid()
     return valid
Ejemplo n.º 10
0
 def is_valid(self):
     if 'mobile_number' in self.data:
         if not self.data['mobile_number'].startswith('+'):
             site = Site.objects.get(is_default_site=True)
             profile_settings = UserProfilesSettings.for_site(site)
             number = self.data['mobile_number']
             if number:
                 if number.startswith('0'):
                     number = number[1:]
                 number = profile_settings.country_code + \
                     number
             self.data = self.data.copy()
             self.data['mobile_number'] = number
     valid = super(EditProfileForm, self).is_valid()
     return valid
Ejemplo n.º 11
0
def validate_no_email_or_phone(input):
    site = Site.objects.get(is_default_site=True)
    profile_settings = UserProfilesSettings.for_site(site)

    regexes = []
    if profile_settings.prevent_phone_number_in_username:
        regexes.append(REGEX_PHONE)

    if profile_settings.prevent_email_in_username:
        regexes.append(REGEX_EMAIL)

    for regex in regexes:
        match = re.search(regex, input)
        if match:
            return False

    return True
Ejemplo n.º 12
0
    def test_if_date_of_birth_required_but_not_on_reg(self):
        site = Site.objects.get(is_default_site=True)
        profile_settings = UserProfilesSettings.for_site(site)
        profile_settings.activate_dob = True
        profile_settings.capture_dob_on_reg = False
        profile_settings.dob_required = True
        profile_settings.save()

        form_data = {
            'username': '******',
            'password': '******',
            'terms_and_conditions': True
        }
        form = RegistrationForm(data=form_data, questions=[
            self.question,
        ])
        self.assertEqual(form.is_valid(), True)
Ejemplo n.º 13
0
def set_site_settings(apps, schema_editor):
    for site in Site.objects.all():
        settings = UserProfilesSettings.for_site(site)

        settings.show_security_question_fields = True
        settings.security_questions_required = True
        settings.num_security_questions = 1

        settings.activate_display_name = True
        settings.capture_display_name_on_reg = True
        settings.display_name_required = True

        settings.activate_gender = True
        settings.capture_gender_on_reg = True
        settings.gender_required = True

        settings.save()
Ejemplo n.º 14
0
def validate_no_email_or_phone(input):
    site = Site.objects.get(is_default_site=True)
    profile_settings = UserProfilesSettings.for_site(site)

    regexes = []
    if profile_settings.prevent_phone_number_in_username:
        regexes.append(REGEX_PHONE)

    if profile_settings.prevent_email_in_username:
        regexes.append(REGEX_EMAIL)

    for regex in regexes:
        match = re.search(regex, input)
        if match:
            return False

    return True
Ejemplo n.º 15
0
    def test_if_date_of_birth_required_but_not_on_reg(self):
        site = Site.objects.get(is_default_site=True)
        profile_settings = UserProfilesSettings.for_site(site)
        profile_settings.activate_dob = True
        profile_settings.capture_dob_on_reg = False
        profile_settings.dob_required = True
        profile_settings.save()

        form_data = {
            'username': '******',
            'password': '******',
            'terms_and_conditions': True
        }
        form = RegistrationForm(
            data=form_data,
            questions=[self.question, ]
        )
        self.assertEqual(form.is_valid(), True)
Ejemplo n.º 16
0
    def test_if_alias_on_reg_is_not_on_form_done(self):
        site = Site.objects.get(is_default_site=True)
        profile_settings = UserProfilesSettings.for_site(site)
        profile_settings.activate_display_name = True
        profile_settings.capture_display_name_on_reg = True
        profile_settings.display_name_required = True
        profile_settings.activate_dob = True

        profile_settings.save()

        yesterday = timezone.now() - timedelta(days=1)
        form_data = {
            'date_of_birth_year': yesterday.year,
            'date_of_birth_month': yesterday.month,
            'date_of_birth_day': yesterday.day,
        }
        form = DoneForm(data=form_data, )
        self.assertEqual(form.is_valid(), True)
Ejemplo n.º 17
0
def get_validation_msg_fragment():
    site = Site.objects.get(is_default_site=True)
    profile_settings = UserProfilesSettings.for_site(site)

    invalid_msg = ''

    if getattr(profile_settings, 'prevent_email_in_username', False) \
            and getattr(profile_settings, 'prevent_phone_number_in_username',
                        False):
        invalid_msg = 'phone number or email address'

    elif getattr(profile_settings, 'prevent_phone_number_in_username', False):
        invalid_msg = 'phone number'

    elif getattr(profile_settings, 'prevent_email_in_username', False):
        invalid_msg = 'email address'

    return invalid_msg
Ejemplo n.º 18
0
def get_validation_msg_fragment():
    site = Site.objects.get(is_default_site=True)
    profile_settings = UserProfilesSettings.for_site(site)

    invalid_msg = ''

    if getattr(profile_settings, 'prevent_email_in_username', False) \
            and getattr(profile_settings, 'prevent_phone_number_in_username',
                        False):
        invalid_msg = 'phone number or email address'

    elif getattr(profile_settings, 'prevent_phone_number_in_username', False):
        invalid_msg = 'phone number'

    elif getattr(profile_settings, 'prevent_email_in_username', False):
        invalid_msg = 'email address'

    return invalid_msg
Ejemplo n.º 19
0
    def get_form_kwargs(self):
        # add security questions for form field generation
        # the security questions should be a random subset of
        # all the questions the user has answered
        kwargs = super(ForgotPasswordView, self).get_form_kwargs()
        profile_settings = UserProfilesSettings.for_site(self.request.site)
        self.security_questions = SecurityQuestion.objects.descendant_of(
            self.request.site.root_page).live().filter(
                language__is_main_language=True)

        context = {"request": self.request}
        translated_questions = get_pages(context, self.security_questions,
                                         self.request.LANGUAGE_CODE)
        kwargs["questions"] = translated_questions[:profile_settings.
                                                   num_security_questions]
        # limit security questions - done here because query in get_pages()
        # cannot be performed once queryset is sliced into a list
        self.security_questions = self.security_questions[:profile_settings.
                                                          num_security_questions]
        return kwargs
Ejemplo n.º 20
0
    def test_if_alias_on_reg_is_not_on_form_done(self):
        site = Site.objects.get(is_default_site=True)
        profile_settings = UserProfilesSettings.for_site(site)
        profile_settings.activate_display_name = True
        profile_settings.capture_display_name_on_reg = True
        profile_settings.display_name_required = True
        profile_settings.activate_dob = True

        profile_settings.save()

        yesterday = timezone.now() - timedelta(days=1)
        form_data = {
            'date_of_birth_year': yesterday.year,
            'date_of_birth_month': yesterday.month,
            'date_of_birth_day': yesterday.day,
        }
        form = DoneForm(
            data=form_data,
        )
        self.assertEqual(form.is_valid(), True)
Ejemplo n.º 21
0
    def get_form_kwargs(self):
        # add security questions for form field generation
        # the security questions should be a random subset of
        # all the questions the user has answered
        kwargs = super(ForgotPasswordView, self).get_form_kwargs()
        profile_settings = UserProfilesSettings.for_site(self.request.site)
        self.security_questions = SecurityQuestion.objects.descendant_of(
            self.request.site.root_page).live().filter(
            language__is_main_language=True
        )

        context = {"request": self.request}
        translated_questions = get_pages(
            context, self.security_questions, self.request.LANGUAGE_CODE
        )
        kwargs["questions"] = translated_questions[
            :profile_settings.num_security_questions]
        # limit security questions - done here because query in get_pages()
        # cannot be performed once queryset is sliced into a list
        self.security_questions = self.security_questions[
            :profile_settings.num_security_questions]
        return kwargs
Ejemplo n.º 22
0
def profile_warning_message(request, panels):
    profile_settings = UserProfilesSettings.for_site(request.site)
    if not profile_settings.country_code and \
            profile_settings.show_mobile_number_field:
        panels[:] = [ProfileWarningMessagee(request)]
Ejemplo n.º 23
0
def profile_warning_message(request, panels):
    profile_settings = UserProfilesSettings.for_site(request.site)
    if not profile_settings.country_code and \
            profile_settings.show_mobile_number_field:
        panels[:] = [ProfileWarningMessagee(request)]
Ejemplo n.º 24
0
    def form_valid(self, form):
        error_message = "The username and security question(s) combination " \
                        + "do not match."
        profile_settings = UserProfilesSettings.for_site(self.request.site)

        if "forgot_password_attempts" not in self.request.session:
            self.request.session["forgot_password_attempts"] = \
                profile_settings.password_recovery_retries

        # max retries exceeded
        if self.request.session["forgot_password_attempts"] <= 0:
            form.add_error(None,
                           _("Too many attempts. Please try again later."))
            return self.render_to_response({'form': form})

        username = form.cleaned_data["username"]
        try:
            user = User.objects.get(profile__migrated_username=username,
                                    profile__site=self.request.site)
            username = user.username
        except User.DoesNotExist:
            try:
                user = User.objects.get(username=username,
                                        profile__site=self.request.site)
            except User.DoesNotExist:
                self.request.session['forgot_password_attempts'] += 1
                form.add_error(
                    'username',
                    _('The username that you entered appears to be '
                      'invalid. Please try again.'))
                return self.render_to_response({'form': form})

        if not user.is_active:
            # add non_field_error
            form.add_error(None, _(error_message))
            self.request.session["forgot_password_attempts"] -= 1
            return self.render_to_response({'form': form})

        # check security question answers
        answer_checks = []
        for i in range(profile_settings.num_security_questions):
            user_answer = form.cleaned_data.get("question_%s" % (i, ))
            try:
                saved_answer = user.profile.securityanswer_set.get(
                    user=user.profile, question=self.security_questions[i])
                answer_checks.append(saved_answer.check_answer(user_answer))
            except SecurityAnswer.DoesNotExist:
                form.add_error(
                    None,
                    _("There are no security questions "
                      "stored against your profile."))
                return self.render_to_response({'form': form})

        # redirect to reset password page if username and security
        # questions were matched
        if all(answer_checks):
            token = default_token_generator.make_token(user)
            q = QueryDict(mutable=True)
            q["user"] = username
            q["token"] = token
            reset_password_url = "{0}?{1}".format(
                reverse("molo.profiles:reset_password"), q.urlencode())
            return HttpResponseRedirect(reset_password_url)
        else:
            form.add_error(None, _(error_message))
            self.request.session["forgot_password_attempts"] -= 1
            return self.render_to_response({'form': form})
Ejemplo n.º 25
0
    def form_valid(self, form):
        error_message = "The username and security question(s) combination " \
                        + "do not match."
        profile_settings = UserProfilesSettings.for_site(self.request.site)

        if "forgot_password_attempts" not in self.request.session:
            self.request.session["forgot_password_attempts"] = \
                profile_settings.password_recovery_retries

        # max retries exceeded
        if self.request.session["forgot_password_attempts"] <= 0:
            form.add_error(
                None,
                _("Too many attempts. Please try again later.")
            )
            return self.render_to_response({'form': form})

        username = form.cleaned_data["username"]
        try:
            user = User.objects.get(
                profile__migrated_username=username,
                profile__site=self.request.site)
            username = user.username
        except User.DoesNotExist:
            try:
                user = User.objects.get(
                    username=username, profile__site=self.request.site)
            except User.DoesNotExist:
                self.request.session['forgot_password_attempts'] += 1
                form.add_error('username',
                               _('The username that you entered appears to be '
                                 'invalid. Please try again.'))
                return self.render_to_response({'form': form})

        if not user.is_active:
            # add non_field_error
            form.add_error(None, _(error_message))
            self.request.session["forgot_password_attempts"] -= 1
            return self.render_to_response({'form': form})

        # check security question answers
        answer_checks = []
        for i in range(profile_settings.num_security_questions):
            user_answer = form.cleaned_data["question_%s" % (i,)]
            try:
                saved_answer = user.profile.securityanswer_set.get(
                    user=user.profile,
                    question=self.security_questions[i]
                )
                answer_checks.append(saved_answer.check_answer(user_answer))
            except SecurityAnswer.DoesNotExist:
                form.add_error(
                    None,
                    _("There are no security questions "
                      "stored against your profile."))
                return self.render_to_response({'form': form})

        # redirect to reset password page if username and security
        # questions were matched
        if all(answer_checks):
            token = default_token_generator.make_token(user)
            q = QueryDict(mutable=True)
            q["user"] = username
            q["token"] = token
            reset_password_url = "{0}?{1}".format(
                reverse("molo.profiles:reset_password"), q.urlencode()
            )
            return HttpResponseRedirect(reset_password_url)
        else:
            form.add_error(None, _(error_message))
            self.request.session["forgot_password_attempts"] -= 1
            return self.render_to_response({'form': form})