Use password validation in change password flow

This also moves the form validation into a form instead of doing it in
the view.
This commit is contained in:
Mouse Reeve 2022-07-15 10:45:08 -07:00
parent 4a65ee326a
commit 659ee96002
4 changed files with 70 additions and 45 deletions

View file

@ -1,5 +1,8 @@
""" using django model forms """ """ using django model forms """
from django import forms from django import forms
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from bookwyrm import models from bookwyrm import models
from bookwyrm.models.fields import ClearableFileInputWithWarning from bookwyrm.models.fields import ClearableFileInputWithWarning
@ -66,3 +69,33 @@ class DeleteUserForm(CustomForm):
class Meta: class Meta:
model = models.User model = models.User
fields = ["password"] fields = ["password"]
class ChangePasswordForm(CustomForm):
current_password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = models.User
fields = ["password"]
widgets = {
"password": forms.PasswordInput(),
}
def clean(self):
"""Make sure passwords match and are valid"""
current_password = self.data.get("current_password")
if not self.instance.check_password(current_password):
self.add_error("current_password", _("Incorrect password"))
cleaned_data = super().clean()
new_password = cleaned_data.get("password")
confirm_password = self.data.get("confirm_password")
if new_password != confirm_password:
self.add_error("confirm_password", _("Password does not match"))
try:
validate_password(new_password)
except ValidationError as err:
self.add_error("password", err)

View file

@ -20,34 +20,19 @@
{% csrf_token %} {% csrf_token %}
<div class="field"> <div class="field">
<label class="label" for="id_password">{% trans "Current password:" %}</label> <label class="label" for="id_password">{% trans "Current password:" %}</label>
<input {{ form.current_password }}
type="password" {% include 'snippets/form_errors.html' with errors_list=form.current_password.errors id="desc_current_password" %}
name="current_password"
maxlength="128"
class="input"
required=""
id="id_current_password"
aria-describedby="desc_current_password"
>
{% include 'snippets/form_errors.html' with errors_list=errors.current_password id="desc_current_password" %}
</div> </div>
<hr aria-hidden="true" /> <hr aria-hidden="true" />
<div class="field"> <div class="field">
<label class="label" for="id_password">{% trans "New password:" %}</label> <label class="label" for="id_password">{% trans "New password:" %}</label>
<input type="password" name="password" maxlength="128" class="input" required="" id="id_password"> {{ form.password }}
{% include 'snippets/form_errors.html' with errors_list=form.password.errors id="desc_current_password" %}
</div> </div>
<div class="field"> <div class="field">
<label class="label" for="id_confirm_password">{% trans "Confirm password:" %}</label> <label class="label" for="id_confirm_password">{% trans "Confirm password:" %}</label>
<input {{ form.confirm_password }}
type="password" {% include 'snippets/form_errors.html' with errors_list=form.confirm_password.errors id="desc_confirm_password" %}
name="confirm-password"
maxlength="128"
class="input"
required=""
id="id_confirm_password"
aria-describedby="desc_confirm_password"
>
{% include 'snippets/form_errors.html' with errors_list=errors.confirm_password id="desc_confirm_password" %}
</div> </div>
<button class="button is-primary" type="submit">{% trans "Change Password" %}</button> <button class="button is-primary" type="submit">{% trans "Change Password" %}</button>
</form> </form>

View file

@ -46,8 +46,8 @@ class ChangePasswordViews(TestCase):
"", "",
{ {
"current_password": "password", "current_password": "password",
"password": "hi", "password": "longwordsecure",
"confirm-password": "hi", "confirm_password": "longwordsecure",
}, },
) )
request.user = self.local_user request.user = self.local_user
@ -64,8 +64,8 @@ class ChangePasswordViews(TestCase):
"", "",
{ {
"current_password": "not my password", "current_password": "not my password",
"password": "hi", "password": "longwordsecure",
"confirm-password": "hihi", "confirm_password": "hihi",
}, },
) )
request.user = self.local_user request.user = self.local_user
@ -81,8 +81,25 @@ class ChangePasswordViews(TestCase):
"", "",
{ {
"current_password": "password", "current_password": "password",
"password": "hi", "password": "longwordsecure",
"confirm-password": "hihi", "confirm_password": "hihi",
},
)
request.user = self.local_user
result = view(request)
validate_html(result.render())
self.assertEqual(self.local_user.password, password_hash)
def test_password_change_invalid(self):
"""change password"""
view = views.ChangePassword.as_view()
password_hash = self.local_user.password
request = self.factory.post(
"",
{
"current_password": "password",
"password": "hi",
"confirm_password": "hi",
}, },
) )
request.user = self.local_user request.user = self.local_user

View file

@ -3,11 +3,10 @@ from django.contrib.auth import login
from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required
from django.template.response import TemplateResponse from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator from django.utils.decorators import method_decorator
from django.utils.translation import gettext_lazy as _
from django.views import View from django.views import View
from django.views.decorators.debug import sensitive_variables, sensitive_post_parameters from django.views.decorators.debug import sensitive_variables, sensitive_post_parameters
from bookwyrm import models from bookwyrm import forms
# pylint: disable= no-self-use # pylint: disable= no-self-use
@ -17,33 +16,24 @@ class ChangePassword(View):
def get(self, request): def get(self, request):
"""change password page""" """change password page"""
data = {"user": request.user} data = {"form": forms.ChangePasswordForm()}
return TemplateResponse(request, "preferences/change_password.html", data) return TemplateResponse(request, "preferences/change_password.html", data)
@sensitive_variables("new_password") @sensitive_variables("new_password")
@sensitive_variables("confirm_password")
@method_decorator(sensitive_post_parameters("current_password")) @method_decorator(sensitive_post_parameters("current_password"))
@method_decorator(sensitive_post_parameters("password")) @method_decorator(sensitive_post_parameters("password"))
@method_decorator(sensitive_post_parameters("confirm__password")) @method_decorator(sensitive_post_parameters("confirm__password"))
def post(self, request): def post(self, request):
"""allow a user to change their password""" """allow a user to change their password"""
data = {"user": request.user} form = forms.ChangePasswordForm(request.POST, instance=request.user)
if not form.is_valid():
# check current password data = {"form": form}
user = models.User.objects.get(id=request.user.id)
if not user.check_password(request.POST.get("current_password")):
data["errors"] = {"current_password": [_("Incorrect password")]}
return TemplateResponse(request, "preferences/change_password.html", data)
new_password = request.POST.get("password")
confirm_password = request.POST.get("confirm-password")
if new_password != confirm_password:
data["errors"] = {"confirm_password": [_("Password does not match")]}
return TemplateResponse(request, "preferences/change_password.html", data) return TemplateResponse(request, "preferences/change_password.html", data)
new_password = form.cleaned_data["password"]
request.user.set_password(new_password) request.user.set_password(new_password)
request.user.save(broadcast=False, update_fields=["password"]) request.user.save(broadcast=False, update_fields=["password"])
login(request, request.user) login(request, request.user)
data["success"] = True data = {"success": True, "form": forms.ChangePasswordForm()}
return TemplateResponse(request, "preferences/change_password.html", data) return TemplateResponse(request, "preferences/change_password.html", data)