Commit fea6a2a9 authored by Pierre-Elliott Bécue's avatar Pierre-Elliott Bécue

Refactors SubscribeUserToPackageView.post

Forces the post request to check if a package exists before attempting
the subscription, and also enhances the way incorrect requests are
handled.
parent 870d6dda
......@@ -14,10 +14,16 @@ from django.db.models import Prefetch
from django.http import Http404, HttpResponseBadRequest, HttpResponseForbidden
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse_lazy
from django.utils.html import format_html
from django.views.generic.base import View
from distro_tracker.accounts.models import UserEmail
from distro_tracker.core.models import EmailSettings, Keyword, Subscription
from distro_tracker.core.models import (
EmailSettings,
Keyword,
Subscription,
get_web_package
)
from distro_tracker.core.utils import (
distro_tracker_render_to_string,
render_to_json_response
......@@ -192,26 +198,39 @@ class SubscribeUserToPackageView(LoginRequiredMixin, View):
if email not in users_emails:
return HttpResponseForbidden()
# Create the subscriptions
json_result = {'status': 'ok'}
try:
for email in emails:
Subscription.objects.create_for(
package_name=package,
email=email)
except ValidationError as e:
json_result['status'] = 'failed'
json_result['error'] = e.message
_pkg = get_web_package(package)
_err = None
if _pkg:
try:
for email in emails:
Subscription.objects.create_for(
package_name=package,
email=email)
except ValidationError as e:
_err = e.message
else:
_err = format_html(
"Package {pkg} does not exist.",
pkg=package,
)
if request.is_ajax():
json_result = {'status': 'ok'}
if _err is not None:
json_result = {
'status': 'failed',
'error': _err,
}
return render_to_json_response(json_result)
else:
if 'error' in json_result:
return HttpResponseBadRequest(json_result['error'])
next = request.POST.get('next', None)
if not next:
return redirect('dtracker-package-page', package_name=package)
return redirect(next)
if _err:
return HttpResponseBadRequest(_err)
_next = request.POST.get('next', None)
return safe_redirect(
_next,
resolve_url('dtracker-package-page', package_name=package),
)
class UnsubscribeUserView(LoginRequiredMixin, View):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment