Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add a token to all URLs that generate and return files
Roland Geiderc2255384873b
diff --git a/wger/manager/pdf.py b/wger/manager/pdf.pyindex aaa2bef2e..5e8712c9f 100644--- a/wger/manager/pdf.py+++ b/wger/manager/pdf.py@@ -18,12 +18,14 @@ import loggingimport datetimefrom django.http import HttpResponse+from django.http import HttpResponseForbiddenfrom django.core.urlresolvers import reversefrom django.shortcuts import get_object_or_404from django.contrib.auth.decorators import login_requiredfrom django.utils.translation import ugettext as _from wger.manager.models import Workout+from wger.utils.helpers import check_tokenfrom wger.utils.pdf import styleSheetfrom reportlab.lib.pagesizes import A4, cm@@ -38,8 +40,7 @@ from wger import get_versionlogger = logging.getLogger('wger.custom')-@login_required-def workout_log(request, id):+def workout_log(request, id, uidb64=None, token=None):'''Generates a PDF with the contents of the given workout@@ -48,12 +49,20 @@ def workout_log(request, id):* http://www.reportlab.com/apis/reportlab/dev/platypus.html'''+ # Load the workout+ if uidb64 is not None and token is not None:+ if check_token(uidb64, token):+ workout = get_object_or_404(Workout, pk=id)+ else:+ return HttpResponseForbidden()+ else:+ if request.user.is_anonymous():+ return HttpResponseForbidden()+ workout = get_object_or_404(Workout, pk=id, user=request.user)+# Create the HttpResponse object with the appropriate PDF headers.response = HttpResponse(content_type='application/pdf')- # Load the workout- workout = get_object_or_404(Workout, pk=id, user=request.user)-# Create the PDF object, using the response object as its "file."doc = SimpleDocTemplate(response,pagesize=A4,@@ -269,7 +278,7 @@ def workout_log(request, id):@login_required-def workout_view(request, id):+def workout_view(request, id, uidb64=None, token=None):'''Generates a PDF with the contents of the workout, without table for logs'''@@ -278,7 +287,13 @@ def workout_view(request, id):response = HttpResponse(content_type='application/pdf')# Load the workout- workout = get_object_or_404(Workout, pk=id, user=request.user)+ if uidb64 is not None and token is not None:+ if check_token(uidb64, token):+ workout = get_object_or_404(Workout, pk=id)+ else:+ if request.user.is_anonymous():+ return HttpResponseForbidden()+ workout = get_object_or_404(Workout, pk=id, user=request.user)# Create the PDF object, using the response object as its "file."doc = SimpleDocTemplate(response,diff --git a/wger/manager/templates/mobile/schedule/view.html b/wger/manager/templates/mobile/schedule/view.htmlindex 211458886..59f274bf2 100644--- a/wger/manager/templates/mobile/schedule/view.html+++ b/wger/manager/templates/mobile/schedule/view.html@@ -132,7 +132,7 @@ than once.{% endblocktrans %}</p>application for example google calendar, outlook or iCal. This will createan appointment for each training day with the appropriate exercises.{% endblocktrans %}</p><p>- <a href="{% url 'schedule-ical' schedule.id %}" {% auto_link_css flavour %}>+ <a href="{% url 'schedule-ical' schedule.id uid token %}" {% auto_link_css flavour %}><img src="{% static 'images/icons/calendar.svg' %}"width="32"height="32"diff --git a/wger/manager/templates/mobile/tags/render_day.html b/wger/manager/templates/mobile/tags/render_day.htmlindex 42c91d384..f63ec123e 100644--- a/wger/manager/templates/mobile/tags/render_day.html+++ b/wger/manager/templates/mobile/tags/render_day.html@@ -151,14 +151,14 @@</a>{% empty %}<a href="{% url 'set-add' day.obj.id %}"- class="list-group-item list-group-item-success">+ class="list-group-item list-group-item-success wger-modal-dialog">{% trans "No exercises selected for this day." %}<br>{% trans "Add one now." %}</a>{% endfor %} <!--for set in day-->{% if day.set_list %}- <a href="{% url 'set-add' day.obj.id %}" class="list-group-item list-group-item-success">+ <a href="{% url 'set-add' day.obj.id %}" class="list-group-item list-group-item-success wger-modal-dialog"><span class="glyphicon glyphicon-plus"></span>{% trans "Add exercises to this workout day" %}</a>diff --git a/wger/manager/templates/mobile/workout/view.html b/wger/manager/templates/mobile/workout/view.htmlindex 3062b395f..403ce3321 100644--- a/wger/manager/templates/mobile/workout/view.html+++ b/wger/manager/templates/mobile/workout/view.html@@ -31,15 +31,6 @@ $(document).ready(function() {{% endif %}toggle_comments();- /*- * At the moment (Oct. 2013), firefox OS has no possibility to download- * authenticated files, like these PDFs: when using web activities, we- * can only pass the PDF's URL to the reader but this will fail, since that- * application is not authenticated.- */- if(typeof MozActivity != 'undefined') {- $(".pdf-button").remove();- }});</script>{% endblock %}@@ -191,7 +182,7 @@ $(document).ready(function() {application for example google calendar, outlook or iCal. This will createan appointment for each training day with the appropriate exercises.{% endblocktrans %}</p><p>- <a href="{% url 'workout-ical' workout.id %}" {% auto_link_css flavour %}>+ <a href="{% url 'workout-ical' workout.id uid token %}" {% auto_link_css flavour %}><img src="{% static 'images/icons/calendar.svg' %}"width="32"height="32"@@ -215,13 +206,13 @@ an appointment for each training day with the appropriate exercises.{% endblockt<h4 class="modal-title">{% trans "Download as PDF" %}</h4></div><div class="modal-body">- <a href="{% url 'workout-pdf-log' workout.id %}" {% auto_link_css flavour "pdf-button" %}>- {% trans "Log" %}- </a>+ <a href="{% url 'workout-pdf-log' workout.id uid token %}" {% auto_link_css flavour %}>+ {% trans "Log" %}+ </a>- <a href="{% url 'workout-pdf-table' workout.id %}" {% auto_link_css flavour "pdf-button" %}>- {% trans "Table" %}- </a>+ <a href="{% url 'workout-pdf-table' workout.id uid token %}" {% auto_link_css flavour %}>+ {% trans "Table" %}+ </a></div></div></div>diff --git a/wger/manager/templates/schedule/view.html b/wger/manager/templates/schedule/view.htmlindex a09cb5b64..d734c5e7e 100644--- a/wger/manager/templates/schedule/view.html+++ b/wger/manager/templates/schedule/view.html@@ -193,7 +193,7 @@ than once.{% endblocktrans %}</p>application for example google calendar, outlook or iCal. This will createan appointment for each training day with the appropriate exercises.{% endblocktrans %}</p><p>- <a href="{% url 'schedule-ical' schedule.id %}" class="btn btn-block btn-default">+ <a href="{% url 'schedule-ical' schedule.id uid token %}" class="btn btn-block btn-default"><img src="{% static 'images/icons/calendar.svg' %}"width="32"height="32"diff --git a/wger/manager/templates/set/add.html b/wger/manager/templates/set/add.htmlindex bc1c9370b..af8efe317 100644--- a/wger/manager/templates/set/add.html+++ b/wger/manager/templates/set/add.html@@ -35,15 +35,21 @@ function custom_page_init(){% csrf_token %}{% render_form_field form.exercises %}- <div class="form-group">- <label for="slider" class="col-md-3 control-label">- {{form.sets.label}}- </label>-+ <div div class="form-group">+ <div class="col-md-3">+ <label for="id_sets" class="control-label">+ {{form.sets.label}}+ - <span id="id_sets_value">{{ form.sets.value }}</span>+ </label>+ </div><div class="col-md-9">- <div id="slider"></div>- <span id="slider-show">{{form.sets.value}}</span>- <input type="hidden" id="id_sets" name="sets" value="{{ form.sets.value }}">+ <input name="sets"+ id="id_sets"+ min="1"+ max="10"+ value="{{ form.sets.value }}"+ type="range"+ class="form-control"></div></div>diff --git a/wger/manager/templates/workout/view.html b/wger/manager/templates/workout/view.htmlindex c492c874c..cd3db7f97 100644--- a/wger/manager/templates/workout/view.html+++ b/wger/manager/templates/workout/view.html@@ -39,8 +39,6 @@ $(document).ready(function() {</p>{% endif %}--{% for day in workout.canonical_representation.day_list %}<div id="div-day-{{ day.obj.id }}">{% render_day day.obj flavour %}@@ -110,9 +108,9 @@ $(document).ready(function() {alt="{% trans 'Download as PDF' %}"title="{% trans 'Download as PDF' %}">{% trans "Download as PDF" %}:- <a href="{% url 'workout-pdf-log' workout.id %}">{% trans "Log" %}</a>+ <a href="{% url 'workout-pdf-log' workout.id uid token %}">{% trans "Log" %}</a>|- <a href="{% url 'workout-pdf-table' workout.id %}">{% trans "Table" %}</a>+ <a href="{% url 'workout-pdf-table' workout.id uid token %}">{% trans "Table" %}</a></p><p>@@ -186,7 +184,7 @@ $(document).ready(function() {application for example google calendar, outlook or iCal. This will createan appointment for each training day with the appropriate exercises.{% endblocktrans %}</p><p>- <a href="{% url 'workout-ical' workout.id %}" class="btn btn-block btn-default">+ <a href="{% url 'workout-ical' workout.id uid token %}" class="btn btn-block btn-default"><img src="{% static 'images/icons/calendar.svg' %}"width="32"height="32"diff --git a/wger/manager/tests/test_ical.py b/wger/manager/tests/test_ical.pyindex 3b14c9fe2..cf5433e2f 100644--- a/wger/manager/tests/test_ical.py+++ b/wger/manager/tests/test_ical.py@@ -13,11 +13,12 @@# You should have received a copy of the GNU Affero General Public Licenseimport datetime+from django.contrib.auth.models import Userfrom django.core.urlresolvers import reversefrom wger.manager.tests.testcase import WorkoutManagerTestCase-from wger.utils.helpers import next_weekday+from wger.utils.helpers import next_weekday, make_token# TODO: parse the generated calendar files with the icalendar library@@ -49,6 +50,26 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):Tests exporting the ical file for a workout'''+ def export_ical_token(self):+ '''+ Helper function that checks exporing an ical file using tokens for access+ '''++ user = User.objects.get(username='test')+ uid, token = make_token(user)+ response = self.client.get(reverse('workout-ical', kwargs={'pk': 3,+ 'uidb64': uid,+ 'token': token}))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response['Content-Type'], 'text/calendar')+ self.assertEqual(response['Content-Disposition'],+ 'attachment; filename=Calendar-workout-3.ics')++ # Approximate size+ self.assertGreater(len(response.content), 540)+ self.assertLess(len(response.content), 560)+def export_ical(self, fail=False):'''Helper function@@ -74,6 +95,7 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):'''self.export_ical(fail=True)+ self.export_ical_token()def test_export_ical_owner(self):'''@@ -82,6 +104,7 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):self.user_login('test')self.export_ical(fail=False)+ self.export_ical_token()def test_export_ical_other(self):'''@@ -90,13 +113,34 @@ class WorkoutICalExportTestCase(WorkoutManagerTestCase):self.user_login('admin')self.export_ical(fail=True)+ self.export_ical_token()class ScheduleICalExportTestCase(WorkoutManagerTestCase):'''- Tests exporting the ical file for a scheduel+ Tests exporting the ical file for a schedule'''+ def export_ical_token(self):+ '''+ Helper function that checks exporing an ical file using tokens for access+ '''++ user = User.objects.get(username='test')+ uid, token = make_token(user)+ response = self.client.get(reverse('schedule-ical', kwargs={'pk': 2,+ 'uidb64': uid,+ 'token': token}))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response['Content-Type'], 'text/calendar')+ self.assertEqual(response['Content-Disposition'],+ 'attachment; filename=Calendar-schedule-2.ics')++ # Approximate size+ self.assertGreater(len(response.content), 1650)+ self.assertLess(len(response.content), 1660)+def export_ical(self, fail=False):'''Helper function@@ -122,6 +166,7 @@ class ScheduleICalExportTestCase(WorkoutManagerTestCase):'''self.export_ical(fail=True)+ self.export_ical_token()def test_export_ical_owner(self):'''@@ -130,6 +175,7 @@ class ScheduleICalExportTestCase(WorkoutManagerTestCase):self.user_login('admin')self.export_ical(fail=False)+ self.export_ical_token()def test_export_ical_other(self):'''@@ -138,3 +184,4 @@ class ScheduleICalExportTestCase(WorkoutManagerTestCase):self.user_login('test')self.export_ical(fail=True)+ self.export_ical_token()diff --git a/wger/manager/tests/test_pdf.py b/wger/manager/tests/test_pdf.pyindex 106e92ee5..1af4320bf 100644--- a/wger/manager/tests/test_pdf.py+++ b/wger/manager/tests/test_pdf.py@@ -11,10 +11,12 @@# GNU General Public License for more details.## You should have received a copy of the GNU Affero General Public License+from django.contrib.auth.models import Userfrom django.core.urlresolvers import reversefrom wger.manager.tests.testcase import WorkoutManagerTestCase+from wger.utils.helpers import make_tokenclass WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):@@ -22,12 +24,31 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):Tests exporting a workout as a pdf'''+ def export_pdf_token(self):+ '''+ Helper function to test exporting a workout as a pdf using tokens+ '''++ user = User.objects.get(username='test')+ uid, token = make_token(user)+ response = self.client.get(reverse('workout-pdf-log', kwargs={'id': 3,+ 'uidb64': uid,+ 'token': token}))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response['Content-Type'], 'application/pdf')+ self.assertEqual(response['Content-Disposition'],+ 'attachment; filename=Workout-3-log.pdf')++ # Approximate size only+ self.assertGreater(int(response['Content-Length']), 31000)+ self.assertLess(int(response['Content-Length']), 35000)+def export_pdf(self, fail=False):'''Helper function to test exporting a workout as a pdf'''- # Create a workoutresponse = self.client.get(reverse('workout-pdf-log', kwargs={'id': 3}))if fail:@@ -48,6 +69,7 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):'''self.export_pdf(fail=True)+ self.export_pdf_token()def test_export_pdf_owner(self):'''@@ -56,6 +78,7 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):self.user_login('test')self.export_pdf(fail=False)+ self.export_pdf_token()def test_export_pdf_other(self):'''@@ -64,6 +87,7 @@ class WorkoutPdfLogExportTestCase(WorkoutManagerTestCase):self.user_login('admin')self.export_pdf(fail=True)+ self.export_pdf_token()class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):@@ -71,6 +95,26 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):Tests exporting a workout as a pdf'''+ def export_pdf_token(self):+ '''+ Helper function to test exporting a workout as a pdf using tokens+ '''++ user = User.objects.get(username='test')+ uid, token = make_token(user)+ response = self.client.get(reverse('workout-pdf-table', kwargs={'id': 3,+ 'uidb64': uid,+ 'token': token}))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response['Content-Type'], 'application/pdf')+ self.assertEqual(response['Content-Disposition'],+ 'attachment; filename=Workout-3-table.pdf')++ # Approximate size only+ self.assertGreater(int(response['Content-Length']), 31000)+ self.assertLess(int(response['Content-Length']), 35000)+def export_pdf(self, fail=False):'''Helper function to test exporting a workout as a pdf@@ -97,6 +141,7 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):'''self.export_pdf(fail=True)+ self.export_pdf_token()def test_export_pdf_owner(self):'''@@ -105,6 +150,7 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):self.user_login('test')self.export_pdf(fail=False)+ self.export_pdf_token()def test_export_pdf_other(self):'''@@ -113,3 +159,4 @@ class WorkoutPdfTableExportTestCase(WorkoutManagerTestCase):self.user_login('admin')self.export_pdf(fail=True)+ self.export_pdf_token()diff --git a/wger/manager/urls.py b/wger/manager/urls.pyindex 8885538ae..1f10076f7 100644--- a/wger/manager/urls.py+++ b/wger/manager/urls.py@@ -68,13 +68,22 @@ urlpatterns = patterns('',url(r'^workout/calendar/(?P<year>\d{4})-(?P<month>\d{1,2})$',log.calendar,name='workout-calendar'),+ url(r'^workout/(?P<pk>\d+)/ical/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',+ ical.export,+ name='workout-ical'),url(r'^workout/(?P<pk>\d+)/ical$',ical.export,name='workout-ical'),+ url(r'^workout/(?P<id>\d+)/pdf/log/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',+ pdf.workout_log,+ name='workout-pdf-log'),url(r'^workout/(?P<id>\d+)/pdf/log$',pdf.workout_log,name='workout-pdf-log'),+ url(r'^workout/(?P<id>\d+)/pdf/table/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',+ pdf.workout_view,+ name='workout-pdf-table'),url(r'^workout/(?P<id>\d+)/pdf/table$',pdf.workout_view,name='workout-pdf-table'),@@ -108,6 +117,9 @@ urlpatterns = patterns('',url(r'^workout/schedule/(?P<pk>\d+)/delete/$',schedule.ScheduleDeleteView.as_view(),name='schedule-delete'),+ url(r'^workout/schedule/(?P<pk>\d+)/ical/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',+ ical.export_schedule,+ name='schedule-ical'),url(r'^workout/schedule/(?P<pk>\d+)/ical$',ical.export_schedule,name='schedule-ical'),diff --git a/wger/manager/views/ical.py b/wger/manager/views/ical.pyindex faa4d39c3..e1df22fce 100644--- a/wger/manager/views/ical.py+++ b/wger/manager/views/ical.py@@ -23,6 +23,7 @@ from icalendar.tools import UIDGeneratorfrom django.shortcuts import get_object_or_404from django.http import HttpResponse+from django.http import HttpResponseForbiddenfrom django.contrib.auth.decorators import login_requiredfrom django.conf import settingsfrom django.contrib.sites.models import Site@@ -30,6 +31,7 @@ from django.contrib.sites.models import Sitefrom wger import get_versionfrom wger.manager.models import Workout, Schedulefrom wger.utils.helpers import next_weekday+from wger.utils.helpers import check_tokenlogger = logging.getLogger('wger.custom')@@ -102,14 +104,21 @@ def get_events_workout(calendar, workout, duration, start_date=None):# Views-@login_required-def export(request, pk):+def export(request, pk, uidb64=None, token=None):'''Export the current workout as an iCal file'''- # Load workout- workout = get_object_or_404(Workout, pk=pk, user=request.user)+ # Load the workout+ if uidb64 is not None and token is not None:+ if check_token(uidb64, token):+ workout = get_object_or_404(Workout, pk=pk)+ else:+ return HttpResponseForbidden()+ else:+ if request.user.is_anonymous():+ return HttpResponseForbidden()+ workout = get_object_or_404(Workout, pk=pk, user=request.user)# Create the calendarcalendar = get_calendar()@@ -127,13 +136,19 @@ def export(request, pk):@login_required-def export_schedule(request, pk):+def export_schedule(request, pk, uidb64=None, token=None):'''Export the current schedule as an iCal file'''- # Load schedule- schedule = get_object_or_404(Schedule, pk=pk, user=request.user)+ # Load the schedule+ if uidb64 is not None and token is not None:+ if check_token(uidb64, token):+ schedule = get_object_or_404(Schedule, pk=pk)+ else:+ return HttpResponseForbidden()+ else:+ schedule = get_object_or_404(Schedule, pk=pk, user=request.user)# Create the calendarcalendar = get_calendar()diff --git a/wger/manager/views/schedule.py b/wger/manager/views/schedule.pyindex 8a1101ebf..9e5072281 100644--- a/wger/manager/views/schedule.py+++ b/wger/manager/views/schedule.py@@ -29,6 +29,7 @@ from wger.manager.models import Schedulefrom wger.utils.generic_views import WgerFormMixinfrom wger.utils.generic_views import WgerDeleteMixinfrom wger.utils.generic_views import WgerPermissionMixin+from wger.utils.helpers import make_tokenlogger = logging.getLogger('wger.custom')@@ -53,8 +54,10 @@ def view(request, pk):Show the workout schedule'''template_data = {}+ user = request.user+ uid, token = make_token(user)- schedule = get_object_or_404(Schedule, pk=pk, user=request.user)+ schedule = get_object_or_404(Schedule, pk=pk, user=user)template_data['schedule'] = scheduleif schedule.is_active:template_data['active_workout'] = schedule.get_current_scheduled_workout()@@ -63,6 +66,9 @@ def view(request, pk):schedule.get_current_scheduled_workout()+ template_data['uid'] = uid+ template_data['token'] = token+return render(request, 'schedule/view.html', template_data)diff --git a/wger/manager/views/workout.py b/wger/manager/views/workout.pyindex 94daf8030..ba8f712c2 100644--- a/wger/manager/views/workout.py+++ b/wger/manager/views/workout.py@@ -41,6 +41,7 @@ from wger.manager.forms import WorkoutCopyFormfrom wger.utils.generic_views import WgerFormMixinfrom wger.utils.generic_views import WgerDeleteMixinfrom wger.utils.generic_views import WgerPermissionMixin+from wger.utils.helpers import make_tokenlogger = logging.getLogger('wger.custom')@@ -71,8 +72,10 @@ def view(request, id):Show the workout with the given ID'''template_data = {}- workout = get_object_or_404(Workout, pk=id, user=request.user)+ user = request.user+ workout = get_object_or_404(Workout, pk=id, user=user)canonical = workout.canonical_representation+ uid, token = make_token(user)# Create the backgrounds that show what muscles the workout will work onmuscles_front = []@@ -92,6 +95,8 @@ def view(request, id):template_data['workout'] = workouttemplate_data['muscle_backgrounds_front'] = muscles_fronttemplate_data['muscle_backgrounds_back'] = muscles_back+ template_data['uid'] = uid+ template_data['token'] = tokenreturn render(request, 'workout/view.html', template_data)diff --git a/wger/nutrition/templates/mobile/plan/view.html b/wger/nutrition/templates/mobile/plan/view.htmlindex 3f5ca0367..95e15856f 100644--- a/wger/nutrition/templates/mobile/plan/view.html+++ b/wger/nutrition/templates/mobile/plan/view.html@@ -16,16 +16,6 @@ $(document).ready(function() {// Check if the user wants to see ingredients in englishinit_english_ingredients();-- /*- * At the moment (Oct. 2013), firefox OS has no possibility to download- * authenticated files, like these PDFs: when using web activities, we- * can only pass the PDF's URL to the reader but this will fail, since that- * application is not authenticated.- */- if(typeof MozActivity != 'undefined') {- $(".pdf-button").remove();- }});</script>{% endblock %}@@ -334,8 +324,8 @@ $(document).ready(function() {<h3>{% trans "Options" %}</h3>-<a href="{% url 'wger.nutrition.views.plan.export_pdf' plan.id %}"- {% auto_link_css flavour "pdf-button" %}>+<a href="{% url 'nutrition-export-pdf' plan.id uid token %}"+ {% auto_link_css flavour %}><img src="{% static 'images/icons/save.svg' %}"width="32"height="32"diff --git a/wger/nutrition/templates/plan/view.html b/wger/nutrition/templates/plan/view.htmlindex 2e77049b5..136e635b5 100644--- a/wger/nutrition/templates/plan/view.html+++ b/wger/nutrition/templates/plan/view.html@@ -258,7 +258,7 @@ function custom_modal_init()<h3>{% trans "Options" %}</h3><p>-<a href="{% url 'wger.nutrition.views.plan.export_pdf' plan.id %}"+<a href="{% url 'nutrition-export-pdf' plan.id uid token %}"target="_blank"><img src="{% static 'images/icons/save.svg' %}"width="32"diff --git a/wger/nutrition/tests/test_pdf.py b/wger/nutrition/tests/test_pdf.pyindex 6824a7a2f..56fd22ba7 100644--- a/wger/nutrition/tests/test_pdf.py+++ b/wger/nutrition/tests/test_pdf.py@@ -18,6 +18,7 @@ from wger.core.models import Languagefrom wger.nutrition.models import NutritionPlanfrom wger.manager.tests.testcase import WorkoutManagerTestCase+from wger.utils.helpers import make_tokenclass NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):@@ -25,17 +26,39 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):Tests exporting a nutritional plan as a pdf'''+ def export_pdf_token(self):+ '''+ Helper function to test exporting a nutritional plan as a pdf using+ a token as access (no fails)+ '''++ user = User.objects.get(pk=2)+ uid, token = make_token(user)+ response = self.client.get(reverse('nutrition-export-pdf',+ kwargs={'id': 4,+ 'uidb64': uid,+ 'token': token}))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response['Content-Type'], 'application/pdf')+ self.assertEqual(response['Content-Disposition'],+ 'attachment; filename=nutritional-plan.pdf')++ # Approximate size+ self.assertGreater(int(response['Content-Length']), 31000)+ self.assertLess(int(response['Content-Length']), 34000)+def export_pdf(self, fail=False):'''Helper function to test exporting a nutritional plan as a pdf'''# Get a plan- response = self.client.get(reverse('wger.nutrition.views.plan.export_pdf',+ response = self.client.get(reverse('nutrition-export-pdf',kwargs={'id': 4}))if fail:- self.assertIn(response.status_code, (404, 302))+ self.assertIn(response.status_code, (404, 403))else:self.assertEqual(response.status_code, 200)self.assertEqual(response['Content-Type'], 'application/pdf')@@ -53,11 +76,11 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):plan.user = userplan.language = languageplan.save()- response = self.client.get(reverse('wger.nutrition.views.plan.export_pdf',+ response = self.client.get(reverse('nutrition-export-pdf',kwargs={'id': plan.id}))if fail:- self.assertIn(response.status_code, (404, 302))+ self.assertIn(response.status_code, (404, 403))else:self.assertEqual(response.status_code, 200)self.assertEqual(response['Content-Type'], 'application/pdf')@@ -74,6 +97,7 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):'''self.export_pdf(fail=True)+ self.export_pdf_token()def test_export_pdf_owner(self):'''@@ -82,6 +106,7 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):self.user_login('test')self.export_pdf(fail=False)+ self.export_pdf_token()def test_export_pdf_other(self):'''@@ -90,3 +115,4 @@ class NutritionalPlanPdfExportTestCase(WorkoutManagerTestCase):self.user_login('admin')self.export_pdf(fail=True)+ self.export_pdf_token()diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.pyindex b05ba084f..734ee797d 100644--- a/wger/nutrition/urls.py+++ b/wger/nutrition/urls.py@@ -47,8 +47,12 @@ urlpatterns = patterns('wger.nutrition.views',url(r'^(?P<pk>\d+)/edit/$',login_required(plan.PlanEditView.as_view()),name='nutrition-edit'),+ url(r'^(?P<id>\d+)/pdf/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$',+ plan.export_pdf,+ name='nutrition-export-pdf'),url(r'^(?P<id>\d+)/pdf/$',- plan.export_pdf),+ plan.export_pdf,+ name='nutrition-export-pdf'),# Mealsurl(r'^(?P<plan_pk>\d+)/meal/add/$',diff --git a/wger/nutrition/views/plan.py b/wger/nutrition/views/plan.pyindex 23b4abbed..77e107454 100644--- a/wger/nutrition/views/plan.py+++ b/wger/nutrition/views/plan.py@@ -19,6 +19,7 @@ import datetimefrom django.shortcuts import renderfrom django.shortcuts import get_object_or_404from django.http import HttpResponse+from django.http import HttpResponseForbiddenfrom django.http import HttpResponseRedirectfrom django.core.context_processors import csrffrom django.core.urlresolvers import reverse@@ -42,6 +43,7 @@ from wger.nutrition.models import MEALITEM_WEIGHT_UNITfrom wger import get_versionfrom wger.utils.generic_views import WgerFormMixinfrom wger.utils.generic_views import WgerDeleteMixin+from wger.utils.helpers import check_token, make_tokenfrom wger.utils.pdf import styleSheetfrom wger.utils.language import load_language@@ -107,8 +109,10 @@ def view(request, id):Show the nutrition plan with the given ID'''template_data = {}+ user = request.user+ uid, token = make_token(user)- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)+ plan = get_object_or_404(NutritionPlan, pk=id, user=user)template_data['plan'] = plan# Load the language and pass it to the template@@ -120,6 +124,10 @@ def view(request, id):# Get the nutritional infotemplate_data['nutritional_data'] = plan.get_nutritional_values()+ # Tokens for the links+ template_data['uid'] = uid+ template_data['token'] = token+return render(request, 'plan/view.html', template_data)@@ -158,8 +166,7 @@ def copy(request, pk):return HttpResponseRedirect(reverse('nutrition-view', kwargs={'id': plan.id}))-@login_required-def export_pdf(request, id):+def export_pdf(request, id, uidb64=None, token=None):'''Generates a PDF with the contents of a nutrition plan@@ -168,8 +175,17 @@ def export_pdf(request, id):* http://www.reportlab.com/apis/reportlab/dev/platypus.html'''- # Load the workout- plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)+ # Load the plan+ if uidb64 is not None and token is not None:+ if check_token(uidb64, token):+ plan = get_object_or_404(NutritionPlan, pk=id)+ else:+ return HttpResponseForbidden()+ else:+ if request.user.is_anonymous():+ return HttpResponseForbidden()+ plan = get_object_or_404(NutritionPlan, pk=id, user=request.user)+plan_data = plan.get_nutritional_values()# Create the HttpResponse object with the appropriate PDF headers.diff --git a/wger/software/templates/functions.html b/wger/software/templates/functions.htmlindex e1c2f82f6..a59fda9ba 100644--- a/wger/software/templates/functions.html+++ b/wger/software/templates/functions.html@@ -148,7 +148,7 @@ do.{% endblocktrans %}</p><a name="pdf-export"></a><h3>{% trans "PDF export" %}</h3>-{% with link='href="/static/pdf/workout-pdf-1.4-en.pdf" data-ajax="false" class="pdf-button"' %}+{% with link='href="/static/pdf/workout-pdf-1.4-en.pdf" data-ajax="false"' %}<p>{% blocktrans %}It can also generate a PDF with your current routine.This is suitable for printing so you can bring it to the gym and keep a logfor 7 weeks. In case you wonder how it looks like, <a {{link}}>here's a sample</a>.{% endblocktrans %}@@ -232,7 +232,7 @@ keep track of what you actually ate during the day and how it compares towhat the plan says. It simply shows you the nutritional values of the planyou create.{% endblocktrans %}</p>-{% with link='href="/static/pdf/nutrition-plan-pdf-1.4-en.pdf" data-ajax="false" class="pdf-button"' %}+{% with link='href="/static/pdf/nutrition-plan-pdf-1.4-en.pdf" data-ajax="false"' %}<p>{% blocktrans %}It can also be downloaded as a PDF you can keep on yourfridge, so you don't forget to follow the plan... And as with the workoutlog, <a {{link}}>here's a sample</a>.{% endblocktrans %}</p>diff --git a/wger/utils/helpers.py b/wger/utils/helpers.pyindex b6e49014c..0e59ccb89 100644--- a/wger/utils/helpers.py+++ b/wger/utils/helpers.py@@ -20,6 +20,10 @@ import jsonimport datetimefrom functools import wraps+from django.contrib.auth.models import User+from django.contrib.auth.tokens import default_token_generator+from django.utils.encoding import force_bytes+from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encodelogger = logging.getLogger('wger.custom')@@ -72,3 +76,34 @@ def next_weekday(date, weekday):if days_ahead <= 0:days_ahead += 7return date + datetime.timedelta(days_ahead)+++def make_token(user):+ '''+ Convenience function that generates the UID and token for a user++ :param user: a user object+ :return: the uid and the token+ '''+ uid = urlsafe_base64_encode(force_bytes(user.pk))+ token = default_token_generator.make_token(user)++ return uid, token+++def check_token(uidb64, token):+ '''+ Checks that the user token is correct.++ :param uidb:+ :param token:+ :return: True on success, False in all other situations+ '''+ if uidb64 is not None and token is not None:+ uid = urlsafe_base64_decode(uidb64)+ user = User.objects.get(pk=uid)++ if user is not None and default_token_generator.check_token(user, token):+ return True++ return False