示例#1
0
def password_reset(username, code):
    require_current = None
    message = None

    form = PasswordResetForm()
    user = User.getByName(username)
    if not user and user.change_configuration.get('password_reset_code') != code:
        abort(404)

    if request.method == 'POST':
        del form.current_password
        if form.validate_on_submit():
            if form.password.data == form.confirm.data:
                salt = bcrypt.gensalt()
                hashed_password = bcrypt.hashpw(form.password.data, salt)
                user.password = hashed_password
                user.change_configuration = {}
                user.update_record()

                if session.get('username'):
                    session['username'] = ''
                return redirect(url_for('.password_reset_complete'))

    return render_template('user/password_reset.html',
                           form=form,
                           message=message,
                           require_current=require_current,
                           username=username,
                           code=code
                           )
示例#2
0
def change_password():
    require_current = True
    error = None
    form = PasswordResetForm()

    user = User.objects.filter(username=session.get('username')).first()

    if not user:
        abort(404)

    if request.method == 'POST':
        if form.validate_on_submit():
            if form.current_password.data == user.password:
                # salt = bcrypt.gensalt()
                # hashed_password = bcrypt.hashpw(form.password.data.encode('UTF_8'), salt)
                hashed_password = form.password.data
                user.password = hashed_password
                user.save()
                # if user is logged in, log him out
                if session.get('username'):
                    session.pop('username')
                return redirect(url_for('user_app.password_reset_complete'))
            else:
                error = "Incorrect password"
    return render_template('user/password_reset.html',
                           form=form,
                           require_current=require_current,
                           error=error)
示例#3
0
def change_password():
    require_current = True
    error = None
    
    form = PasswordResetForm()
    
    user = User.objects.filter(username=session.get("username")).first()
    
    if not user:
        abort(404)

    if request.method == "POST":
        if form.validate_on_submit():
            if bcrypt.hashpw(form.current_password.data, user.password) == user.password:
                salt = bcrypt.gensalt()
                hashed_password = bcrypt.hashpw(form.password.data, salt)
                user.password = hashed_password
                user.save()
                
                body_html = render_template("mail/user/password_change.html", user=user)
                body_text = render_template("mail/user/password_change.txt", user=user)
                email(user.email, "Password change request", body_html, body_text)
                
                # If user is logged in, log him/her out
                if session.get("username"):
                    session.pop("username")
                return redirect(url_for("user_app.password_reset_complete"))
            else:
                error = "Incorrect password"
    return render_template("user/password_reset.html",
        form=form,
        require_current=require_current,
        error=error)
示例#4
0
def change_password():
    require_current = True
    error = None
    form = PasswordResetForm()

    user = User.getByName(username=session.get('username'))
    if not user:
        abort(404)

    if request.method == 'POST':
        if form.validate_on_submit():
            if bcrypt.hashpw(form.current_password.data, user.password) == user.password:
                salt = bcrypt.gensalt()
                hashed_password = bcrypt.hashpw(form.password.data, salt)
                user.password = hashed_password
                user.update_record()
                # if user is logged in, log him out
                if session.get('username'):
                    session.pop('username')
                return redirect(url_for('.password_reset_complete')), 302
            else:
                error = "Incorrect password"

    return render_template('user/password_reset.html',
                           form=form,
                           require_current=require_current,
                           error=error
                           )
示例#5
0
def password_reset(username, code):
    message = None
    require_current = None
    
    form = PasswordResetForm()
    
    user = User.objects.filter(username=username).first()
    if not user or code != user.change_configuration.get('password_reset_code'):
        abort(404)
        
    if request.method == 'POST':
        del form.current_password
        if form.validate_on_submit():
            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(form.password.data, salt)
            user.password = hashed_password
            user.change_configuration = {}
            user.save()
            
            if session.get('username'):
                session.pop('username')
            return redirect(url_for('user_app.password_reset_complete'))
            
    return render_template('user/password_reset.html',
        form=form,
        message=message,
        require_current=require_current,
        username=username,
        code=code
    )
示例#6
0
文件: views.py 项目: pemm8/flaskbook
def change_password():
    require_current = True
    error = None
    form = PasswordResetForm()
    
    user = User.objects.filter(username=session.get('username')).first()
    if not user:
        abort(404)
    
    if request.method == 'POST':
        if form.validate_on_submit():
            if bcrypt.hashpw(form.current_password.data, user.password) == user.password:
                salt = bcrypt.gensalt()
                hashed_password = bcrypt.hashpw(form.password.data, salt)
                user.password = hashed_password
                user.save()
                
                # email the user the confirmation of password change
                body_html = render_template('mail/user/change_password_confirmation.html')
                body_text = render_template('mail/user/change_password_confirmation.txt')
                email(user.email, "Recent Password Change", body_html, body_text)
                
                # if user is logged in, log out
                if session.get('username'):
                    session.pop('username')
                return redirect(url_for('user_app.password_reset_complete'))
            else:
                error = "Incorrect password"
    return render_template('user/password_reset.html',
        form=form,
        require_current=require_current,
        error=error
    )
                
示例#7
0
def change_password():
    require_current = True
    error = None
    form = PasswordResetForm()
    
    user = User.objects.filter(username=session.get('username')).first()
    
    if not user:
        abort(404)
        
    if request.method == 'POST':
        if form.validate_on_submit():
            if bcrypt.hashpw(form.current_password.data, user.password) == user.password:
                salt = bcrypt.gensalt()
                hashed_password = bcrypt.hashpw(form.password.data, salt)
                user.password = hashed_password
                user.save()
                # if user is logged in, log him out
                if session.get('username'):
                    session.pop('username')
                return redirect(url_for('user_app.password_reset_complete'))
            else:
                error = "Incorrect password"
    return render_template('user/password_reset.html',
        form=form,
        require_current=require_current,
        error=error
    )
示例#8
0
def password_reset(username, code):
    message = None
    require_current = None
    
    form = PasswordResetForm()
    
    user = User.objects.filter(username=username).first()
    if not user or code != user.change_configuration.get('password_reset_code'):
        abort(404)
        
    if request.method == 'POST':
        del form.current_password
        if form.validate_on_submit():
            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(form.password.data, salt)
            user.password = hashed_password
            user.change_configuration = {}
            user.save()
            
            if session.get('username'):
                session.pop('username')
            return redirect(url_for('user_app.password_reset_complete'))
            
    return render_template('user/password_reset.html',
        form=form,
        message=message,
        require_current=require_current,
        username=username,
        code=code
    )
示例#9
0
def password_reset(request):
    form = PasswordResetForm(data=request.POST)
    if form.is_valid():
        email = form.cleaned_data.get('email')
        form.save(
            use_https=request.is_secure(),
            from_email=None,
            subject_template_name='registration/password_reset_subject.txt',
            email_template_name='registration/password_reset_email.html',
            token_generator=account_activation_token,
            request=request)
        return render(request, 'registration/password_reset_done.html',
                      {'email': email})
    return render(request, 'registration/password_reset_form.html',
                  {'form': form})
示例#10
0
def password_reset(request):
    if request.method == "POST":
        form = PasswordResetForm(request.POST, )
        if form.is_valid():
            email = form.cleaned_data.get('email')
            user = User.objects.get(email=email)
            msg = tokens.generate_pw_reset_email(user, request)
            msg.send()
            return HttpResponseRedirect(reverse('password_reset_done'))
        else:
            return TemplateResponse(request, 'password_reset_form.html', {'form': form})
    else:
        form = PasswordResetForm()
    context = {
        'form': form,
    }

    return TemplateResponse(request, 'password_reset_form.html', context)
def password_reset(request):
    if request.method == "POST":
        form = PasswordResetForm(request.POST, )
        if form.is_valid():
            email = form.cleaned_data.get('email')
            user = User.objects.get(email=email)
            msg = tokens.generate_pw_reset_email(user, request)
            msg.send()
            return HttpResponseRedirect(reverse('password_reset_done'))
        else:
            return TemplateResponse(request, 'password_reset_form.html', {'form': form})
    else:
        form = PasswordResetForm()
    context = {
        'form': form,
    }

    return TemplateResponse(request, 'password_reset_form.html', context)
class TestServices(TestCase):
    """ Test suite for testing the UserCreationForms """
    def setUp(self):
        self.averageForm = AvgRegisterForm(data={'email' : '*****@*****.**',
                                          'username' : 'AverageTester',
                                          'role' : 'AVERAGE',
                                          'first_name' : 'TesterName',
                                          'last_name' : 'TesterSurname',
                                          'password1' : 'TestPassword',
                                          'password2' : 'TestPassword'})

        self.academicForm = AcademicRegisterForm(data={'email' : '*****@*****.**',
                                          'username' : 'AcademicTester',
                                          'role' : 'TEACHER',
                                          'first_name' : 'TesterName',
                                          'last_name' : 'TesterSurname',
                                          'password1' : 'TestPassword',
                                          'password2' : 'TestPassword'})

        self.passwordResetFormValid = PasswordResetForm(data={'old_password' : 'oldpassword',
                                                              'new_password' : 'newpassword',
                                                              'confirm_password' : 'newpassword' })

        self.passwordResetFormInvalid = PasswordResetForm(data={'old_password' : 'oldpassword',
                                                              'new_password' : 'newpassword',
                                                              'confirm_password' : 'differentpassword' })

    def test_AvgRegisterForm(self):
        """ Method for testing that AvgRegisterForm is valid """
        self.assertTrue(self.averageForm.is_valid())

    def test_AcademicRegisterForm(self):
        """ Method for testing that AcademicRegisterForm is valid """
        self.assertTrue(self.academicForm.is_valid())

    def test_PasswordResetForm_valid(self):
        """ Method for testing the PasswordResetForm with matching new passwords """
        self.assertTrue(self.passwordResetFormValid.is_valid())

    def test_PasswordResetForm_invalid(self):
        """ Method for testing the PasswordResetForm with non-matching new passwords """
        self.assertFalse(self.passwordResetFormInvalid.is_valid())
示例#13
0
def password_reset_handler_view(request):
    if request.POST:
        password_reset_form = PasswordResetForm(request.POST)
        if password_reset_form.is_valid():
            email = password_reset_form.cleaned_data['email']
            password_reset_form.save(request)
            return JsonResponse({
                'message':
                message(
                    "На ваш почтовый адрес отправлена инструкция о восстановлении пароля!",
                    request),
                'result':
                'success',
                'url':
                '',
            })
        else:
            response = render_template(
                'PasswordReset/password_reset_form.html',
                {'password_reset_form': password_reset_form}, request)
            return JsonResponse({'response': response, 'result': 'error'})
def my_account(request):
    """ View for My Account page """
    context = {}
    if (request.method == "POST"):
        form = PasswordResetForm(request.POST)
        if form.is_valid():
            newPassword = form.cleaned_data['new_password']
            oldPassword = form.cleaned_data['old_password']
            email = request.user.email

            user = authenticate(username=email, password=oldPassword)
            if user is None:
                context = {}
                context['form'] = form
                context['error'] = "You have entered the wrong password"
                return render(request, 'classroom_main/my_account.html',
                              context)
            else:
                context = {}
                user.set_password(newPassword)
                user.save()
                context['success'] = "Password changed successfully"
                context['form'] = PasswordResetForm()
                return render(request, 'classroom_main/my_account.html',
                              context)
    else:
        form = PasswordResetForm()

    context['form'] = form

    return render(request, 'classroom_main/my_account.html', context)
示例#15
0
def reset_password(code):
    serial = Serializer(app.config['SECRET_KEY'])
    user_obj = None
    form = PasswordResetForm()
    require_current = None
    error = None
    if request.method == 'POST':
        del form.current_password
        if form.validate_on_submit():
            try:
                user_obj = serial.loads(code)
            except Exception as e:
                error = 'Invalid or expired password reset link. Please reset your password again.'
                flash(error, 'error')
                return redirect(url_for('login'))
                # return render_template('error.html')

            user = User.query.filter_by(id=user_obj['id'], ).first()

            if not user:
                error = 'User does not exist. Please try again with a valid email.'
                flash(error, 'error')
                return redirect(url_for('login'))

            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(form.password.data, salt)
            user.password = hashed_password
            # user.save()
            db.session.add(user)
            db.session.commit()
            if session.get('username'):
                session.pop('username')
            return render_template('user/reset_password_confirm.html')

    return render_template('user/reset_password.html',
                           form=form,
                           error=error,
                           require_current=require_current,
                           code=code)
示例#16
0
def password_reset(username, code):
    form = PasswordResetForm()
    message = None
    require_current = None

    user = User.objects.filter(username=username).first()
    # if the user dont exist or the reset code is wrong
    if not user or code != user.change_configuration.get(
            'password_reset_code'):
        abort(404)
    # Bipass the form validation to be able to delete the current password
    # without throwing the form validation.datarequired wich would throw an error
    if request.method == 'POST':
        del form.current_password
        # Now we can validate
        if form.validate_on_submit():
            # create a salt
            salt = bcrypt.gensalt()
            # create hashed password passing the new password and the salt
            hashed_password = bcrypt.hashpw(form.password.data, salt)
            # Change the users password to the hashed password
            user.password = hashed_password
            # Change the change_configuration to a empty dict
            user.change_configuration = {}
            user.save()
            # Check to see if the user session exists and delete
            if session.get('username'):
                session.pop('username')
            return redirect(url_for('user_app.password_reset_complete'))

    # If not POST
    return render_template('user/password_reset.html',
                           form=form,
                           message=message,
                           require_current=require_current,
                           username=username,
                           code=code)
    def setUp(self):
        self.averageForm = AvgRegisterForm(data={'email' : '*****@*****.**',
                                          'username' : 'AverageTester',
                                          'role' : 'AVERAGE',
                                          'first_name' : 'TesterName',
                                          'last_name' : 'TesterSurname',
                                          'password1' : 'TestPassword',
                                          'password2' : 'TestPassword'})

        self.academicForm = AcademicRegisterForm(data={'email' : '*****@*****.**',
                                          'username' : 'AcademicTester',
                                          'role' : 'TEACHER',
                                          'first_name' : 'TesterName',
                                          'last_name' : 'TesterSurname',
                                          'password1' : 'TestPassword',
                                          'password2' : 'TestPassword'})

        self.passwordResetFormValid = PasswordResetForm(data={'old_password' : 'oldpassword',
                                                              'new_password' : 'newpassword',
                                                              'confirm_password' : 'newpassword' })

        self.passwordResetFormInvalid = PasswordResetForm(data={'old_password' : 'oldpassword',
                                                              'new_password' : 'newpassword',
                                                              'confirm_password' : 'differentpassword' })
示例#18
0
文件: utils.py 项目: wooshe/Shop
def getDataForNavBaR(ctx, request):
    cart_count = getUserCartCount(request)

    login_form = LoginForm()
    registration_form = RegistrationForm()
    password_reset_form = PasswordResetForm()

    notification_form = NotificationForm()
    category_menu = Category.objects.all()

    ctx.update({
        'cart_count': cart_count,
        'login_form': login_form,
        'registration_form': registration_form,
        'password_reset_form': password_reset_form,
        'notification_form': notification_form,
        'category_menu': category_menu,
    })
示例#19
0
 def test_form_renders_email_input(self):
     form = PasswordResetForm()
     self.assertIn('placeholder="*****@*****.**"', form.as_p())
示例#20
0
 def test_form_validation_for_blank_email(self):
     form = PasswordResetForm(data={'email': ''})
     self.assertFalse(form.is_valid())
     self.assertEqual(form.errors['email'], [EMPTY_EMAIL_ERROR])