Self hosted FLOSS fitness/workout, nutrition and weight tracker
Allow user to delete own account
Roland Geideref161311b1c2
diff --git a/wger/core/forms.py b/wger/core/forms.pyindex 39b8c90fa..b3b7489be 100644--- a/wger/core/forms.py+++ b/wger/core/forms.py@@ -18,7 +18,7 @@ from captcha.fields import ReCaptchaFieldfrom django.contrib.auth.forms import UserCreationFormfrom django.contrib.auth.models import User as Django_Userfrom django.core.exceptions import ValidationError-from django.forms import ModelForm, EmailField, Form, CharField, widgets+from django.forms import ModelForm, EmailField, Form, CharField, widgets, PasswordInputfrom django.utils.translation import ugettext as _from wger.core.models import UserProfile@@ -57,6 +57,31 @@ class UserEmailForm(ModelForm):raise ValidationError(_("This email is already used."))+class PasswordConfirmationForm(Form):+ '''+ A simple password confirmation form.++ This can be used to make sure the user really wants to perform a dangerous+ action. The form must be initialised with a user object.+ '''+ password = CharField(label=_("Password"),+ widget=PasswordInput,+ help_text=_('Please enter your current password.'))++ def __init__(self, user, data=None):+ self.user = user+ super(PasswordConfirmationForm, self).__init__(data=data)++ def clean_password(self):+ '''+ Check that the password supplied matches the one for the user+ '''+ password = self.cleaned_data.get('password', None)+ if not self.user.check_password(password):+ raise ValidationError(_('Invalid password'))+ return self.cleaned_data.get("password")++class RegistrationForm(UserCreationForm, UserEmailForm):'''Registration formdiff --git a/wger/core/templates/user/delete_account.html b/wger/core/templates/user/delete_account.htmlnew file mode 100644index 000000000..73440c8df--- /dev/null+++ b/wger/core/templates/user/delete_account.html@@ -0,0 +1,38 @@+{% extends "base.html" %}+{% load browserid %}+{% load i18n %}+{% load staticfiles %}+{% load wger_extras %}++{% block title %} {% trans "Delete account" %}{% endblock %}+++{% block header %}+{% browserid_css %}+{% endblock %}++{% block content %}++<form action="{% url 'core:user-delete' %}"+ method="post"+ class="form-horizontal"+ role="form">+ <div class="panel panel-danger">+ <div class="panel-heading">+ <h3 class="panel-title">{% trans "Are you sure?" %}</h3>+ </div>+ <div class="panel-body">+ <p>{% blocktrans %}This action will delete your user account.+It will also irrevocably remove all your data and can't be undone. {% endblocktrans %}</p>++ {% render_form_fields form 'tmp' False %}+ {% render_form_submit 'Delete' 'danger' %}+ </div>+ </div>+</form>++{% endblock %}+++{% block sidebar %}+{% endblock %}diff --git a/wger/core/templates/user/preferences.html b/wger/core/templates/user/preferences.htmlindex dc6a13228..00b66a2d7 100644--- a/wger/core/templates/user/preferences.html+++ b/wger/core/templates/user/preferences.html@@ -133,4 +133,14 @@ $(function() {title="{% trans 'API key' %}">{% trans "API key" %}</a></p>++<p style="margin-top: 2em;">+ <a href="{% url 'core:user-delete' %}" {% auto_link_css flavour %}>+ <img src="{% static 'images/icons/trash.svg' %}"+ width="32"+ height="32"+ alt="{% trans 'Delete account' %}"+ title="{% trans 'Delete account' %}">+ {% trans "Delete account" %}</a>+ </p>{% endblock %}diff --git a/wger/core/tests/test_delete_user.py b/wger/core/tests/test_delete_user.pynew file mode 100644index 000000000..657f1f99d--- /dev/null+++ b/wger/core/tests/test_delete_user.py@@ -0,0 +1,71 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++import logging+import datetime+import decimal++from django.core.urlresolvers import reverse+from django.contrib.auth.models import User+from wger.core.models import UserProfile+from wger.core.tests import api_base_test++from wger.utils.constants import TWOPLACES+from wger.weight.models import WeightEntry+from wger.manager.tests.testcase import WorkoutManagerTestCase++logger = logging.getLogger('wger.custom')+++class DeleteUserTestCase(WorkoutManagerTestCase):+ '''+ Tests deleting the user account and all his data+ '''++ def delete_user(self, fail=False):+ '''+ Helper function+ '''+ response = self.client.get(reverse('core:user-delete'))+ self.assertEqual(User.objects.filter(username='test').count(), 1)+ if fail:+ self.assertEqual(response.status_code, 302)+ else:+ self.assertEqual(response.status_code, 200)++ # Wrong user password+ if not fail:+ response = self.client.post(reverse('core:user-delete'),+ {'password': 'not the user password'})+ self.assertEqual(response.status_code, 200)+ self.assertEqual(User.objects.filter(username='test').count(), 1)++ # Correct user password+ response = self.client.post(reverse('core:user-delete'), {'password': 'testtest'})+ self.assertEqual(response.status_code, 302)+ if not fail:+ self.assertEqual(User.objects.filter(username='test').count(), 0)++ def test_delete_user_logged_in(self):+ '''+ Tests deleting the own account as a logged in user+ '''+ self.user_login('test')+ self.delete_user(fail=False)++ def test_delete_user_anonymous(self):+ '''+ Tests deleting the own account as an anonymous user+ '''+ self.delete_user(fail=True)diff --git a/wger/core/urls.py b/wger/core/urls.pyindex ca96f556f..188bf9dc7 100644--- a/wger/core/urls.py+++ b/wger/core/urls.py@@ -38,6 +38,9 @@ urlpatterns = patterns('',name='dashboard'),# User+ url(r'^user/delete$',+ user.delete,+ name='user-delete'),url(r'^user/logout$',user.logout,name='logout'),diff --git a/wger/core/views/user.py b/wger/core/views/user.pyindex e5a637d0e..b20102ce1 100644--- a/wger/core/views/user.py+++ b/wger/core/views/user.py@@ -35,6 +35,7 @@ from wger.core.models import Languagefrom wger.utils.constants import USER_TABfrom wger.utils.user_agents import check_request_amazon, check_request_androidfrom wger.core.forms import UserPreferencesForm+from wger.core.forms import PasswordConfirmationFormfrom wger.core.forms import UserEmailFormfrom wger.core.forms import RegistrationFormfrom wger.core.forms import RegistrationFormNoCaptcha@@ -57,6 +58,24 @@ def login(request):extra_context=context)+@login_required()+def delete(request):+ '''+ Delete the user account and all his data. Requires password confirmation first+ '''+ form = PasswordConfirmationForm(user=request.user)+ if request.method == 'POST':+ form = PasswordConfirmationForm(data=request.POST, user=request.user)+ if form.is_valid():+ request.user.delete()+ django_logout(request)+ messages.success(request, _('Your account was successfully deleted'))+ return HttpResponseRedirect(reverse('software:features'))+ context = {'form': form}++ return render(request, 'user/delete_account.html', context)++def logout(request):'''Logout the user. For temporary users, delete them.diff --git a/wger/software/templates/changelog.html b/wger/software/templates/changelog.htmlindex ef3d77890..5dbb1762b 100644--- a/wger/software/templates/changelog.html+++ b/wger/software/templates/changelog.html@@ -22,6 +22,7 @@</ul></li><li>Show exercise pictures in workout as well</li>+ <li>Allow the user to delete his account and data</li></ul>