Ejemplo n.º 1
0
 def recover_password(self, request):
     if request.data.get('email'):
         form = ResetPasswordForm({'email': request.data.get('email')})
     if form.is_valid():
         form.save(request)
         return Response("reset password sent to email", status=status.HTTP_400_BAD_REQUEST)
     return Response("Error", status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 2
0
 def post(self, request, format=None):
     formset = ResetPasswordForm(request.data)
     if formset.is_valid():
         formset.save(request)
         return Response(
             {'detail': 'An email has been sent to your email address.'})
     return Response({'detail': 'Email was not provided.'},
                     status=status.HTTP_400_BAD_REQUEST)
 def test_user_email_domain_unicode_collision(self):
     User = get_user_model()
     User.objects.create_user('mike123', '*****@*****.**', 'test123')
     User.objects.create_user('mike456', 'mike@ıxample.org', 'test123')
     data = {'email': 'mike@ıxample.org'}
     form = ResetPasswordForm(data)
     self.assertTrue(form.is_valid())
     form.save(self.global_request)
     self.assertEqual(len(mail.outbox), 1)
     self.assertEqual(mail.outbox[0].to, ['mike@ıxample.org'])
Ejemplo n.º 4
0
 def test_user_email_domain_unicode_collision(self):
     User = get_user_model()
     User.objects.create_user("mike123", "*****@*****.**", "test123")
     User.objects.create_user("mike456", "mike@ıxample.org", "test123")
     data = {"email": "mike@ıxample.org"}
     form = ResetPasswordForm(data)
     self.assertTrue(form.is_valid())
     form.save(self.global_request)
     self.assertEqual(len(mail.outbox), 1)
     self.assertEqual(mail.outbox[0].to, ["mike@ıxample.org"])
Ejemplo n.º 5
0
    def post(self, request):
        serializer = RequestPasswordResetInputSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        email = serializer.validated_data.get('email')

        with transaction.atomic(), clear_messages(request):
            form = ResetPasswordForm(data={'email': email})
            form_valid_or_raise(form)
            form.save(request=request)
            return Response({})
Ejemplo n.º 6
0
    def activate_account(modeladmin, request, queryset):
        for u in queryset:
            from allauth.account.forms import ResetPasswordForm

            rp_form = ResetPasswordForm({'email': u.email})
            rp_form.is_valid()
            # rp_form.fields['email'] = u.email
            # rp_form.clean_email()
            rp_form.save(request)

            u.is_active = True
            u.save()
Ejemplo n.º 7
0
 def post(self, request):
     reset_form = ResetPasswordForm(data=request.data)
     if not reset_form.is_valid():
         raise ValidationError(reset_form.errors)
     # Set some values to trigger the send_email method.
     opts = {
         'use_https': request.is_secure(),
         'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'),
         'request': request,
     }
     reset_form.save(**opts)
     return Response({})
Ejemplo n.º 8
0
    def post(self, request):
        try:
            assert 'email' in request.data
            form = ResetPasswordForm(request.data)
            if form.is_valid():
                form.save()
            else:
                raise ValidationError("Invalid email address")

        except AssertionError:
            return Response({'detail': "'email' field is not provided"},
                            status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 9
0
class RecoveryPasswordSerializer(serializers.Serializer):
    """
    Serializer for requesting a password reset e-mail.
    """
    email = serializers.EmailField()

    def validate_email(self, email):
        self.form = ResetPasswordForm(data=self.initial_data)
        if not self.form.is_valid():
            raise serializers.ValidationError(self.form.errors['email'])
        return email

    def save(self):
        request = self.context.get('request')
        self.form.save(request)
Ejemplo n.º 10
0
def add_users_to_semester(request, pk=None):
    sem_users = UserSemester.objects.filter(
        semester_id=pk).order_by('user__last_name')
    user_form = UserForm()
    if request.method == 'POST':
        if request.POST.get('hidden_type') == 'upload':
            return upload_users(request, pk, sem_users)
        elif request.POST.get('hidden_type') == 'email':
            reset_password_email(request)
            semester = Semester.objects.get(pk=pk)
            form = AddUsersToSemesterForm()
        elif request.POST.get('hidden_type') == 'one_user':
            form = AddUsersToSemesterForm()
            semester = Semester.objects.get(pk=pk)
            user_form = UserForm(request.POST)
            if user_form.is_valid():
                user_form.save(commit=True)
                email = user_form.cleaned_data['email']
                reset_pass_form = ResetPasswordForm({'email': email})
                if reset_pass_form.is_valid():
                    reset_pass_form.save(request)
                messages.success(request, 'User was added successfully!')
                return HttpResponseRedirect(
                    reverse('management:upload_users', kwargs={'pk': pk}))
            else:
                messages.warning(request, 'Please correct the error.')

    else:
        semester = Semester.objects.get(pk=pk)
        form = AddUsersToSemesterForm()
    return render(
        request, 'management/upload_users.html', {
            'form': form,
            'semester': semester,
            'users': sem_users,
            'user_form': user_form
        })
Ejemplo n.º 11
0
def add_users_to_semester(request, pk=None):
    sem_users = UserSemester.objects.filter(semester_id=pk)
    if request.method == 'POST':
        form = AddUsersToSemesterForm(request.POST, request.FILES)
        if form.is_valid():
            semester_obj = Semester.objects.get(id=int(pk))

            file_handle = request.FILES['file']
            user_list_record = file_handle.get_records()
            user_titles_array = file_handle.get_array()[0]

            mandatory_titles = settings.STUDENTS_MANDATORY_FIELDS
            message = 'your Excel file does not have these titles:'
            excel_titles = []
            for key, value in mandatory_titles.items():
                if value not in user_titles_array:
                    message = message + (' ' + value + ',')
                    excel_titles.append(value)

            if len(excel_titles) == 0:
                user_creation_error = ''
                user_add_sem_error = ''
                sem_user_added = [
                ]  # list of users that already existed and were added to semester
                sem_user_created = [
                ]  # list of newly created users and added to semester
                already_existing_users = []

                for student in user_list_record:
                    prepared_dict = {
                        'student_no': student[mandatory_titles['student_no']],
                        'email': student[mandatory_titles['email']],
                        'first_name': student[mandatory_titles['first_name']],
                        'last_name': student[mandatory_titles['last_name']],
                        'username': student[mandatory_titles['username']],
                        'password': User.objects.make_random_password()
                    }

                    empty_valued_titles, filled_value_titles = divide_empty_and_full_dic_values(
                        prepared_dict)

                    if len(empty_valued_titles) > 0:
                        messages.error(
                            request,
                            ('The record with title \"{0}\" and'
                             ' value \"{1}\" has an empty value '
                             'for one or more mandatary field/fields').format(
                                 filled_value_titles[0][0],
                                 filled_value_titles[0][1]))
                        continue
                    elif not validate_email(
                            student[mandatory_titles['email']]):
                        messages.error(request, (
                            'System could not save the '
                            'record with email \"{0}\" because the email address does not have'
                            'a valid format').format(
                                student[mandatory_titles['email']]))
                        continue

                    error_message = '\"{0}({1})\", '.format(
                        prepared_dict['email'], prepared_dict['student_no'])
                    try:
                        obj = User.objects.get(
                            student_no=prepared_dict['student_no'],
                            email=prepared_dict['email'],
                            username=prepared_dict['username'])
                        semester_user_obj, created = UserSemester.objects.get_or_create(
                            user=obj, semester=semester_obj)
                        if created:
                            sem_user_added.append(semester_user_obj)
                        else:
                            already_existing_users.append(semester_user_obj)
                    except User.DoesNotExist:
                        try:
                            obj = User.objects.create(
                                first_name=prepared_dict['first_name'],
                                last_name=prepared_dict['last_name'],
                                student_no=prepared_dict['student_no'],
                                email=prepared_dict['email'],
                                username=prepared_dict['username'],
                                password=prepared_dict['password'])

                            new_email = EmailAddress(
                                user=obj,
                                email=prepared_dict['email'],
                                verified=True,
                                primary=True)
                            new_email.save()

                        except IntegrityError:
                            user_creation_error += error_message

                        except Error:
                            user_creation_error += error_message

                        else:
                            try:
                                reset_pass_form = ResetPasswordForm({
                                    'email':
                                    prepared_dict['email'],
                                    'name':
                                    'Asghar'
                                })
                                if reset_pass_form.is_valid():
                                    reset_pass_form.save(request)

                                semester_user_obj = UserSemester.objects.create(
                                    user=obj, semester=semester_obj)
                                sem_user_created.append(semester_user_obj)
                            except IntegrityError:
                                user_add_sem_error += error_message

                            except Error:
                                user_add_sem_error += error_message

                create_specific_messages(request, user_creation_error,
                                         user_add_sem_error, sem_user_created,
                                         already_existing_users,
                                         user_list_record, semester_obj,
                                         sem_user_added)
            else:
                messages.error(request, message)

            new_form = AddUsersToSemesterForm()
            semester = Semester.objects.get(pk=pk)
            return render(request, 'management/upload_users.html', {
                'form': new_form,
                'semester': semester,
                'users': sem_users
            })

    else:
        semester = Semester.objects.get(pk=pk)
        form = AddUsersToSemesterForm()
    return render(request, 'management/upload_users.html', {
        'form': form,
        'semester': semester,
        'users': sem_users
    })
Ejemplo n.º 12
0
 def create(self, request, *args, **kwargs):
     formset = ResetPasswordForm(request.data)
     if formset.is_valid():
         formset.save(request)
         return Response({'detail': 'An email has been sent to your email address.'})
     return Response({'detail': 'Email was not provided or error.'}, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 13
0
def reset_password_email(request):
    for user in request.POST.getlist('email_students'):
        user_email = User.objects.get(id=user).email
        reset_pass_form = ResetPasswordForm({'email': user_email})
        if reset_pass_form.is_valid():
            reset_pass_form.save(request)