コード例 #1
0
    def process_user(self, user):
        if "shoop.front.apps.auth" not in settings.INSTALLED_APPS:
            raise Problem(_(u"The `shoop.front.apps.auth` app needs to be enabled for password reset."))

        r = RecoverPasswordForm()
        r.request = self.request
        if r.process_user(user):
            messages.success(self.request, _(u"Password recovery email sent to %(email)s") % {"email": user.email})
        else:
            raise Problem(_(u"Sending the password recovery email failed."))
コード例 #2
0
    def _get_unauth_response(self, request, reason):
        """
        Get an error response (or raise a Problem) for a given request and reason message.

        :type request: Request
        :param request: HttpRequest
        :type reason: Reason string
        :param reason: str
        """
        if request.is_ajax():
            return HttpResponseForbidden(
                json.dumps({"error": force_text(reason)}))
        resp = redirect_to_login(
            next=request.path,
            login_url="%s?%s" %
            (reverse("shoop_admin:login"), urlencode({"error": reason})))
        if request.user.is_authenticated():
            # Instead of redirecting to the login page, let the user know what's wrong with
            # a helpful link.
            raise (Problem(
                _("Can't view this page. %(reason)s") % {
                    "reason": reason
                }).with_link(url=resp.url,
                             title=_("Log in with different credentials…")))
        return resp
コード例 #3
0
ファイル: views.py プロジェクト: g-rohit-git/shoop
 def handle_post_delete_file(self, data):
     file = File.objects.get(pk=data["id"])
     try:
         file.delete()
     except IntegrityError as ie:
         raise Problem(str(ie))
     return JsonResponse({"success": True, "message": _("File deleted.")})
コード例 #4
0
def check_and_raise_if_only_one_allowed(setting_name, obj):
    if getattr(settings, setting_name, True):
        return
    if not obj.pk and obj.__class__.objects.count() >= 1:
        raise Problem(
            _("Only one %(model)s permitted.") %
            {"model": obj._meta.verbose_name})
コード例 #5
0
    def post(self, request, *args, **kwargs):
        order = self.object = self.get_object()
        new_status = OrderStatus.objects.get(pk=int(request.POST["status"]))
        old_status = order.status
        if new_status.role == OrderStatusRole.COMPLETE and not order.can_set_complete():
            raise Problem(_("Unable to set order as completed at this point"))
        if new_status.role == OrderStatusRole.CANCELED and not order.can_set_canceled():
            raise Problem(_("Paid, shipped, or canceled orders cannot be canceled"))
        order.status = new_status
        order.save(update_fields=("status",))
        message = _("Order status changed: {old_status} to {new_status}").format(
            old_status=old_status, new_status=new_status)
        order.add_log_entry(message, user=request.user, identifier="status_change")
        messages.success(self.request, message)

        return HttpResponseRedirect(get_model_url(self.get_object()))
コード例 #6
0
 def process_payment_return_request(self, order, request):
     checkout = self._get_checkout_object()
     fields = {
         "version": request.REQUEST.get("VERSION"),
         "order_number": request.REQUEST.get("STAMP"),
         "order_reference": request.REQUEST.get("REFERENCE"),
         "payment": request.REQUEST.get("PAYMENT"),
         "status": request.REQUEST.get("STATUS"),
         "algorithm": request.REQUEST.get("ALGORITHM"),
         "mac": request.REQUEST.get("MAC"),
     }
     if not all(fields.values()):
         messages.warning(request, u"Arvoja puuttuu.")
         return
     status = int(fields["status"])
     if status < 0:
         messages.warning(request, u"Peruit maksamisen. Yritä uudestaan.")
         return
     if status in (2, 3, 5, 6, 8, 9, 10):
         if checkout.validate_payment_return(**fields):
             payment_id = fields["payment"]
             order.create_payment(order.taxful_total_price,
                                  payment_identifier="Checkout.fi %s" %
                                  payment_id,
                                  description="Checkout.fi %s (ref %s)" %
                                  (payment_id, fields["order_reference"]))
         else:
             messages.warning(request, u"Maksun validointi epäonnistui.")
         return
     raise Problem("Unknown return code %s" % status)
コード例 #7
0
ファイル: edit_package.py プロジェクト: teserak/shoop
 def dispatch_command(self, request, command):
     product = self.object
     if command == "clear_package":
         clear_existing_package(product)
         messages.success(self.request, _("Package cleared."))
     else:
         raise Problem("Unknown command: %s" % command)
     return HttpResponseRedirect(self.get_success_url())
コード例 #8
0
    def get_object(self, queryset=None):
        obj = super(ShopEditView, self).get_object(queryset)
        if not settings.SHOOP_ENABLE_MULTIPLE_SHOPS:
            if not obj.pk and Shop.objects.count() >= 1:
                # This seems like a new object, but there already is (at least) one shop...
                raise Problem(_(u"Only one shop permitted."))

        return obj
コード例 #9
0
    def _handle_set_is_active(self):
        state = bool(int(self.request.POST["set_is_active"]))
        if not state:
            if (getattr(self.object, 'is_superuser', False)
                    and not getattr(self.request.user, 'is_superuser', False)):
                raise Problem(_("You can not deactivate a superuser."))
            if self.object == self.request.user:
                raise Problem(_("You can not deactivate yourself."))

        self.object.is_active = state
        self.object.save(update_fields=("is_active", ))
        messages.success(
            self.request,
            _("%(user)s is now %(state)s.") % {
                "user": self.object,
                "state": _("active") if state else _("inactive")
            })
        return HttpResponseRedirect(self.request.path)
コード例 #10
0
    def dispatch(self, request, *args, **kwargs):
        user = self.get_target_user()
        token = self.kwargs["token"]

        valid = (user is not None and self.token_generator.check_token(user, token))
        if not valid:
            raise Problem(_(u"This recovery link is invalid."))

        return super(RecoverPasswordConfirmView, self).dispatch(request, *args, **kwargs)
コード例 #11
0
    def __init__(self, changing_user, target_user, *args, **kwargs):
        super(PasswordChangeForm, self).__init__(*args, **kwargs)
        self.changing_user = changing_user
        self.target_user = target_user
        if self.target_user.is_superuser and not self.changing_user.is_superuser:
            raise Problem(_("You can not change the password of a superuser."))

        if not (self.changing_user == self.target_user
                or self.target_user.is_superuser):
            # Only require old password when changing your own or a superuser's password.
            self.fields.pop("old_password")
コード例 #12
0
ファイル: edit_variation.py プロジェクト: itsrashad/shoop
 def dispatch_command(self, request, command):
     product = self.object
     if command == "unvariate":
         product.clear_variation()
         messages.success(self.request, _("Variation cleared."))
     elif command == "simplify":
         product.simplify_variation()
         messages.success(self.request, _("Variation simplified."))
     else:
         raise Problem("Unknown command: %s" % command)
     return HttpResponseRedirect(self.get_success_url())
コード例 #13
0
ファイル: product.py プロジェクト: itsrashad/shoop
    def get(self, request, *args, **kwargs):
        product = self.object = self.get_object()

        if product.mode == ProductMode.VARIATION_CHILD:
            return redirect("shoop:product",
                            pk=product.variation_parent.pk,
                            slug=product.variation_parent.slug)

        shop_product = self.shop_product = product.get_shop_instance(
            request.shop)
        if not shop_product:
            raise Problem(_(u"This product is not available in this shop."))

        errors = list(
            shop_product.get_visibility_errors(customer=request.customer))

        if errors:
            raise Problem("\n".join(extract_messages(errors)))

        return super(ProductDetailView, self).get(request, *args, **kwargs)
コード例 #14
0
ファイル: pseudo_payment.py プロジェクト: itsrashad/shoop
 def process_payment_return_request(self, order, request):
     mac = self.compute_pseudo_mac(order)
     if request.REQUEST.get("mac") != mac:
         raise Problem(u"Invalid MAC.")
     if not order.is_paid():
         order.create_payment(
             order.taxful_total_price,
             payment_identifier="Pseudo-%s" % now().isoformat(),
             description="Shoop Pseudo Payment Service Payment")
         messages.success(
             request, u"Pseudo Payment successfully processed the request.")
コード例 #15
0
 def dispatch(self, request, *args, **kwargs):
     # This view only dispatches further to the method module's own detail view class
     object = self.get_object()
     module = object.module
     if not module.admin_detail_view_class:
         raise Problem("Module %s has no admin detail view" % module.name)
     if isinstance(module.admin_detail_view_class, six.text_type):
         view_class = load(module.admin_detail_view_class)
     else:
         view_class = module.admin_detail_view_class
     kwargs["object"] = object
     return view_class(model=self.model).dispatch(request, *args, **kwargs)
コード例 #16
0
ファイル: upload.py プロジェクト: sidaga/shoop
 def form_valid(self, form):
     file = form.cleaned_data["file"]
     if not file.name.endswith(".zip"):
         raise Problem("Only ZIP files are supported")
     # TODO: Maybe verify the file before saving?
     filename = "shoop-addon-%s-%s" % (uuid.uuid4(),
                                       os.path.basename(file.name))
     with open(os.path.join(tempfile.gettempdir(), filename), "wb") as outf:
         shutil.copyfileobj(file, outf)
     return HttpResponseRedirect(
         manipulate_query_string(
             reverse("shoop_admin:addon.upload_confirm"), file=filename))
コード例 #17
0
 def dispatch(self, request, *args, **kwargs):  # doccov: ignore
     if not could_edit(request):
         raise Problem(_("No access to editing"))
     self._populate_vars()
     if self.default_layout:
         self.view_config.save_default_placeholder_layout(
             self.placeholder_name, self.default_layout)
         # We saved the default layout, so get rid of the humongous GET arg and try again
         get_args = dict(self.request.GET.items())
         get_args.pop("default_config", None)
         return HttpResponseRedirect(
             "%s?%s" % (self.request.path, urlencode(get_args)))
     return super(EditorView, self).dispatch(request, *args, **kwargs)
コード例 #18
0
def render_html_to_pdf(html, stylesheet_paths=[]):
    if not weasyprint:
        raise Problem(
            _("Could not create PDF since Weasyprint is not available. Please contact support."
              ))
    stylesheets = []
    for stylesheet_path in stylesheet_paths:
        stylesheets.append(
            weasyprint.CSS(string=_fetch_static_resource_str(stylesheet_path)))
    pdf = weasyprint.HTML(
        string=html,
        url_fetcher=_custom_url_fetcher).write_pdf(stylesheets=stylesheets)
    return wrap_pdf_in_response(pdf)
コード例 #19
0
    def __init__(self, **kwargs):
        super(ReloadMethodForm, self).__init__(**kwargs)
        self.reload_methods = list(self.get_viable_reload_methods())

        if not self.reload_methods:
            raise Problem(
                "There are no viable reload methods available. Please contact your system administrator."
            )

        self.fields["reload_method"] = forms.ChoiceField(
            choices=[(rm.identifier, rm.title) for rm in self.reload_methods],
            label=_("Reload Method"),
            initial=self.reload_methods[0].identifier,
            widget=forms.RadioSelect)
コード例 #20
0
 def dispatch(self, request, *args, **kwargs):  # doccov: ignore
     if not could_edit(request):
         raise Problem(_("No access to editing"))
     self._populate_vars()
     if self.default_layout:
         self.view_config.save_default_placeholder_layout(self.placeholder_name, self.default_layout)
         # We saved the default layout, so get rid of the humongous GET arg and try again
         get_args = dict(self.request.GET.items())
         get_args.pop("default_config", None)
         global_type = get_args.pop("global_type", None)
         if global_type:
             get_args["view"] = XTHEME_GLOBAL_VIEW_NAME
         # We are overriding the view with XTHEME_GLOBAL_VIEW_NAME if this is a global placeholder
         return HttpResponseRedirect("%s?%s" % (self.request.path, urlencode(get_args)))
     return super(EditorView, self).dispatch(request, *args, **kwargs)
コード例 #21
0
def command_dispatch(request):
    """
    Xtheme command dispatch view.

    :param request: A request
    :type request: django.http.HttpRequest
    :return: A response
    :rtype: django.http.HttpResponse
    """
    command = request.POST.get("command")
    if command:
        response = handle_command(request, command)
        if response:
            return response
    raise Problem("Unknown command: %r" % command)
コード例 #22
0
 def get_form_defs(self):
     bind_user_id = self.request.REQUEST.get("user_id")
     if bind_user_id:
         bind_user = get_user_model().objects.get(pk=bind_user_id)
         if PersonContact.objects.filter(user=bind_user).exists():
             raise Problem(_("User %(bind_user)s already has a contact", bind_user=bind_user))
     else:
         bind_user = None
     yield TemplatedFormDef(
         "base",
         ContactBaseForm,
         template_name="shoop/admin/contacts/_edit_base_form.jinja",
         required=True,
         kwargs={"instance": self.object, "bind_user": bind_user}
     )
コード例 #23
0
 def _populate_vars(self):
     theme = get_theme_by_identifier(self.request.GET["theme"])
     if not theme:
         raise Problem(_("Unable to determine current theme."))
     self.view_config = ViewConfig(theme=theme,
                                   view_name=self.request.GET["view"],
                                   draft=True)
     self.placeholder_name = self.request.GET["ph"]
     self.default_layout = self._get_default_layout()
     self.layout = self.view_config.get_placeholder_layout(
         placeholder_name=self.placeholder_name,
         default_layout=self.default_layout)
     (x, y) = self.current_cell_coords = (
         int(self.request.GET.get("x", -1)),
         int(self.request.GET.get("y", -1)),
     )
     self.current_cell = self.layout.get_cell(x=x, y=y)
     self.build_form()
コード例 #24
0
    def post(self, request, *args, **kwargs):  # doccov: ignore
        command = request.POST.get("command")
        if command:
            dispatcher = getattr(self, "dispatch_%s" % command, None)
            if not callable(dispatcher):
                raise Problem(_("Unknown command %s") % command)
            dispatch_kwargs = dict(request.POST.items())
            rv = dispatcher(**dispatch_kwargs)
            if rv:
                return rv
            self.request.method = "GET"  # At this point, we won't want to cause form validation
            self.build_form()  # and it's not a bad idea to rebuild the form
            return super(EditorView, self).get(request, *args, **kwargs)

        if request.POST.get("save") and self.form and self.form.is_valid():
            self.form.save()
            self.save_layout()

        return super(EditorView, self).get(request, *args, **kwargs)
コード例 #25
0
    def handle(self, command, kwargs=None):
        """
        Dispatch and handle processing of the given command.

        :param command: Name of command to run
        :type command: unicode
        :param kwargs: Arguments to pass to the command handler. If empty, `request.POST` is used.
        :type kwargs: dict
        :return: response
        :rtype: HttpResponse
        """

        kwargs = kwargs or dict(six.iteritems(self.request.POST))
        try:
            handler = self.get_command_handler(command)
            if not handler or not callable(handler):
                raise Problem(_(u"Invalid command %s") % command)
            kwargs.pop(
                "csrfmiddlewaretoken",
                None)  # The CSRF token should never be passed as a kwarg
            kwargs.pop("command", None)  # Nor the command
            kwargs.update(request=self.request, basket=self.basket)
            kwargs = self.preprocess_kwargs(command, kwargs)
            response = handler(**kwargs) or {}
        except (Problem, ValidationError) as exc:
            if not self.ajax:
                raise
            response = {
                "error":
                force_text(exc, errors="ignore"),
                "code":
                force_text(getattr(exc, "code", None) or "", errors="ignore")
            }
        response = self.postprocess_response(command, kwargs, response)

        if self.ajax:
            return JsonResponse(response)

        return_url = (response.get("return") or kwargs.get("return"))
        if return_url and return_url.startswith("/"):
            return HttpResponseRedirect(return_url)
        return redirect("shoop:basket")
コード例 #26
0
 def get_object(self, queryset=None):
     contact = self.get_contact()
     user = getattr(contact, "user", None)
     if not user:
         raise Problem(_(u"The contact does not have an associated user."))
     return user