Esempio n. 1
0
def reverse(
    viewname, urlconf=None, args=None, kwargs=None, current_app=None, locale=None
):
    """Wraps Django's reverse to prepend the requested locale.
    Keyword Arguments:
    * locale - Use this locale prefix rather than the current active locale.
    Keyword Arguments passed to Django's reverse:
    * viewname
    * urlconf
    * args
    * kwargs
    * current_app
    """
    if locale:
        with translation.override(locale):
            return django_reverse(
                viewname,
                urlconf=urlconf,
                args=args,
                kwargs=kwargs,
                current_app=current_app,
            )
    else:
        return django_reverse(
            viewname, urlconf=urlconf, args=args, kwargs=kwargs, current_app=current_app
        )
Esempio n. 2
0
def reverse(*args, query: dict = None, **kwargs):
    """Extended version of the django function ``reverse`` by just adding support
    for an additional parameter ``query`` which can contain query parameters and
    will be encoded automatically.
    """
    if query is not None:
        return format_lazy(
            "{}?{}",
            django_reverse(*args, **kwargs),
            urlencode(
                {k: str(v) if isinstance(v, Promise) else v for k, v in query.items()},
                doseq=True,
            ),
        )
    return django_reverse(*args, **kwargs)
Esempio n. 3
0
def reverse(viewname,
            query_params=None,
            urlconf=None,
            args=None,
            kwargs=None,
            current_app=None,
            absolute=None):
    """
    Custom wrapper for django reverse accepting query_params and adding it to the link.
    """
    if absolute:
        url = sites_reverse(viewname,
                            args=args,
                            kwargs=kwargs,
                            site_id=SITE_ID)
    else:
        url = django_reverse(viewname,
                             args=args,
                             kwargs=kwargs,
                             urlconf=urlconf,
                             current_app=current_app)
    if query_params:
        return "{}?{}".format(url, urlencode(query_params))

    return url
Esempio n. 4
0
    def test_get_detail_404(self):
        ZaakTypeFactory.create(catalogus=self.catalogus)

        url = get_operation_url('zaaktype_read', uuid=uuid.uuid4())

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        resp_data = response.json()
        del resp_data['instance']
        self.assertEqual(
            resp_data, {
                'code':
                'not_found',
                'title':
                "Niet gevonden.",
                'status':
                404,
                'detail':
                "Niet gevonden.",
                'type':
                "http://testserver{}".format(
                    django_reverse('vng_api_common:error-detail',
                                   kwargs={'exception_class': 'NotFound'}))
            })
Esempio n. 5
0
def reverse(
    viewname, urlconf=None, args=None, kwargs=None, prefix=None, force_locale=False, locale=None
):
    """Wraps Django's reverse to prepend the correct locale.

    force_locale -- Ordinarily, if get_url_prefixer() returns None, we return
        an unlocalized URL, which will be localized via redirect when visited.
        Set force_locale to True to force the insertion of a default locale
        when there is no set prefixer. If you are writing a test and simply
        wish to avoid LocaleURLMiddleware's initial 301 when passing in an
        unprefixed URL, it is probably easier to substitute LocalizingClient
        for any uses of django.test.client.Client and forgo this kwarg.

    locale -- By default, reverse prepends the current locale (if set) or
        the default locale if force_locale == True. To override this behavior
        and have it prepend a different locale, pass in the locale parameter
        with the desired locale. When passing a locale, the force_locale is
        not used and is implicitly True.

    """
    if locale:
        prefixer = Prefixer(locale=locale)
    else:
        prefixer = get_url_prefixer()
        if not prefixer and force_locale:
            prefixer = Prefixer()

    if prefixer:
        prefix = prefix or "/"
    url = django_reverse(viewname, urlconf, args, kwargs, prefix)
    if prefixer:
        return prefixer.fix(url)
    else:
        return url
Esempio n. 6
0
    def test_get_detail_404(self):
        ZaakTypeFactory.create(catalogus=self.catalogus)

        url = get_operation_url("zaaktype_read", uuid=uuid.uuid4())

        response = self.client.get(url)

        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

        resp_data = response.json()
        del resp_data["instance"]
        self.assertEqual(
            resp_data,
            {
                "code":
                "not_found",
                "title":
                "Niet gevonden.",
                "status":
                404,
                "detail":
                "Niet gevonden.",
                "type":
                "http://testserver{}".format(
                    django_reverse(
                        "vng_api_common:error-detail",
                        kwargs={"exception_class": "NotFound"},
                    )),
            },
        )
Esempio n. 7
0
    def test_no_auth(self, client):
        url = reverse("retina:home")
        response = client.get(url, follow=True)

        assert response.redirect_chain[0][1] == status.HTTP_302_FOUND
        assert (settings.LOGIN_URL + "?next=" +
                django_reverse("retina:home") == response.redirect_chain[0][0])
        assert status.HTTP_200_OK == response.status_code
Esempio n. 8
0
def reverse(*args, **kwargs):
    # from django_hosts.resolvers import reverse as hosts_reverse
    # kwargs["host"] = "clubhouse"
    # if "host" in kwargs:
    #     return "/%s" % hosts_reverse(*args, **kwargs).replace("://", "")
    # return hosts_reverse(*args, **kwargs).replace("://", "")
    if "host" in kwargs:
        del kwargs["host"]
    return django_reverse(*args, **kwargs)
Esempio n. 9
0
File: auth.py Progetto: zu83/kitsune
    def authenticate(self, request, **kwargs):
        """Authenticate a user based on the OIDC/oauth2 code flow."""

        # If the request has the /oidc/callback/ path then probably there is a login
        # attempt in the admin interface. In this case just return None and let
        # the OIDC backend handle this request.
        if request and request.path == django_reverse("oidc_authentication_callback"):
            return None

        return super(FXAAuthBackend, self).authenticate(request, **kwargs)
Esempio n. 10
0
File: auth.py Progetto: zu83/kitsune
    def authenticate(self, request, **kwargs):
        """Authenticate a user based on the OIDC code flow."""

        # If the request has the /fxa/callback/ path then probably there is a login
        # with Firefox Accounts. In this case just return None and let
        # the FxA backend handle this request.
        if request and not request.path == django_reverse("oidc_authentication_callback"):
            return None

        return super(SumoOIDCAuthBackend, self).authenticate(request, **kwargs)
Esempio n. 11
0
def reverse(viewname, urlconf=None, args=None, kwargs=None,
            current_app=None, locale=None):
    """Wraps Django's reverse to prepend the requested locale.
    Keyword Arguments:
    * locale - Use this locale prefix rather than the current active locale.
    Keyword Arguments passed to Django's reverse:
    * viewname
    * urlconf
    * args
    * kwargs
    * current_app
    """
    if locale:
        with translation.override(locale):
            return django_reverse(viewname, urlconf=urlconf, args=args,
                                  kwargs=kwargs, current_app=current_app)
    else:
        return django_reverse(viewname, urlconf=urlconf, args=args,
                              kwargs=kwargs, current_app=current_app)
Esempio n. 12
0
    def test_no_auth(self, client):
        url = reverse("retina:home")
        response = client.get(url, follow=True)

        assert response.redirect_chain[0][1] == status.HTTP_302_FOUND
        assert (
            settings.LOGIN_URL + "?next=" + django_reverse("retina:home")
            == response.redirect_chain[0][0]
        )
        assert status.HTTP_200_OK == response.status_code
Esempio n. 13
0
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
    """
    Same as `django.urls.reverse`, but optionally takes a request
    and returns a fully qualified URL, using the request to get the base URL.
    """
    if format is not None:
        kwargs = kwargs or {}
        kwargs['format'] = format
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
    if request:
        return request.build_absolute_uri(url)
    return url
def _reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
    """
    Same as `django.urls.reverse`, but optionally takes a request
    and returns a fully qualified URL, using the request to get the base URL.
    """
    if format is not None:
        kwargs = kwargs or {}
        kwargs['format'] = format
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
    if request:
        return request.build_absolute_uri(url)
    return url
Esempio n. 15
0
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None):
    """Wraps Django's reverse to prepend the correct locale."""
    prefixer = get_url_prefix()

    if prefixer:
        prefix = prefix or '/'
    url = django_reverse(viewname, urlconf, args, kwargs, prefix)
    if prefixer:
        url = prefixer.fix(url)

    # Ensure any unicode characters in the URL are escaped.
    return iri_to_uri(url)
Esempio n. 16
0
def add_short_links(doc_ids):
    """Create short_url's for a list of docs."""
    base_url = "https://{0}%s".format(Site.objects.get_current().domain)
    docs = Document.objects.filter(id__in=doc_ids)
    try:
        for doc in docs:
            # Use django's reverse so the locale isn't included.
            endpoint = django_reverse("wiki.document", args=[doc.slug])
            doc.update(share_link=generate_short_url(base_url % endpoint))
    except BitlyRateLimitException:
        # The next run of the `generate_missing_share_links` cron job will
        # catch all documents that were unable to be processed.
        pass
Esempio n. 17
0
def reverse(value, *args, **kwargs):
    """
    Shortcut filter for reverse url on templates. Is a alternative to
    django {% url %} tag, but more simple.

    Usage example:
        {{ 'web:timeline'|reverse(userid=2) }}

    This is a equivalent to django:
        {% url 'web:timeline' userid=2 %}

    """
    return django_reverse(value, args=args, kwargs=kwargs)
Esempio n. 18
0
def reverse(value, *args, **kwargs):
    """
    Shortcut filter for reverse url on templates. Is a alternative to
    django {% url %} tag, but more simple.

    Usage example:
        {{ 'web:timeline'|reverse(userid=2) }}

    This is a equivalent to django:
        {% url 'web:timeline' userid=2 %}

    """
    return django_reverse(value, args=args, kwargs=kwargs)
Esempio n. 19
0
    def get_absolute_url(self, api: bool = False) -> str:
        """Resolve the url for the user detail template or api view.

        Args:
            api: If true the url for the detail resource on the user api will
                 will be returned.
        """

        if api:
            return drf_reverse("accounts-api:user-detail",
                               kwargs={"pk": self.pk})
        else:
            return django_reverse("accounts:user-detail",
                                  kwargs={"username": self.username})
Esempio n. 20
0
    def get(self, request, *args, **kwargs):
        error_message = _("This QR code has no associated Seat!")
        # request.auth is set only on Token authentication
        # When logged in through the api browser, only request.user will be set
        token_authenticated = request.auth is not None

        # Nothing to see here. A non-admin user should not be able to do anything with this!
        if not token_authenticated and not request.user.is_authenticated:
            return redirect(settings.FRONTEND_URL)

        qr = self.get_object()

        # the ?format=api or ?format=json URL query parameter will be set
        # when using the top right dropdown button next "GET"
        api_browser_format_param = "format" in request.GET

        if token_authenticated or api_browser_format_param:
            if qr.seat is None:
                raise NotFound(error_message)

            seat_staff_api_url = reverse("staff-seat-detail",
                                         args=[qr.seat.pk])
            if request.query_params:
                seat_staff_api_url += "?" + urlencode(request.query_params)
            return redirect(seat_staff_api_url)

        if qr.seat is None:
            messages.error(request, error_message)
            return redirect(
                django_reverse("admin:appointments_qrcode_change",
                               kwargs={"object_id": qr.pk}))

        # Redirect the logged-in user to the Seat admin page
        return redirect(
            django_reverse("admin:appointments_seat_change",
                           kwargs={"object_id": qr.seat.pk}))
Esempio n. 21
0
def reverse(viewname: str, *args, **kwargs):
    """
    Retrieve the absolute URL from a provided viewname.

    Parameters
    ----------
    viewname
        The URL pattern name or a callable view object to reverse.

    Returns
    -------
    str
        The absolute URL.
    """
    return get_absolute_url(django_reverse(viewname, *args, **kwargs))
Esempio n. 22
0
def reverse(viewname, urlconf=None, args=None, kwargs=None):
    """
    Wraps Django's reverse to prepend the correct locale.

    Note: This currently doesn't support passing `current_app`, but we're not
    using that in bedrock. If we need it in the future this is the place to add
    it.

    """
    prefixer = get_url_prefix()

    url = django_reverse(viewname, urlconf, args, kwargs)
    if prefixer:
        url = prefixer.fix(url)

    # Ensure any unicode characters in the URL are escaped.
    return iri_to_uri(url)
Esempio n. 23
0
 def reverse(
     cls,
     viewname,
     urlconf=None,
     args=None,
     kwargs=None,
     current_app=None,
     params=None,
 ):
     url = django_reverse(viewname, urlconf, args, kwargs, current_app)
     if params:
         extra_params = []
         for key, value in params.items():
             extra_params.append(f"{key}={value}")
         param = "&".join(extra_params)
         url = f"{url}?{param}"
     return url
Esempio n. 24
0
def reverse(
    viewname: str,
    url_args: Optional[Dict[str, Any]] = None,
    query_params: Optional[QueryParameters] = None,
    current_app: Optional[str] = None,
    urlconf: Optional[str] = None,
    request: Optional[HttpRequest] = None,
) -> str:
    """An override of django reverse function supporting query parameters.

    Args:
        viewname: the name of the django view from which to compute a url
        url_args: dictionary of url arguments indexed by their names
        query_params: dictionary of query parameters to append to the
            reversed url
        current_app: the name of the django app tighten to the view
        urlconf: url configuration module
        request: build an absolute URI if provided

    Returns:
        str: the url of the requested view with processed arguments and
        query parameters
    """

    if url_args:
        url_args = {k: v for k, v in url_args.items() if v is not None}

    url = django_reverse(viewname,
                         urlconf=urlconf,
                         kwargs=url_args,
                         current_app=current_app)

    if query_params:
        query_params = {k: v for k, v in query_params.items() if v is not None}

    if query_params and len(query_params) > 0:
        query_dict = QueryDict("", mutable=True)
        for k in sorted(query_params.keys()):
            query_dict[k] = query_params[k]
        url += "?" + query_dict.urlencode(safe="/;:")

    if request is not None:
        url = request.build_absolute_uri(url)

    return url
Esempio n. 25
0
def reverse(viewname,
            site_id=None,
            add_domain=False,
            urlconf=None,
            args=None,
            kwargs=None,
            current_app=None,
            qs_kwargs=None):
    from .domain import get_domain

    urlconf = (get_domain(site_id).urlconf
               if site_id is not None and urlconf is None
               and settings.SITE_ID != site_id else urlconf)
    site_id = settings.SITE_ID if site_id is None else site_id
    domain = get_domain(site_id).url if add_domain else ''
    qs = '?{}'.format(urlencode(qs_kwargs)) if qs_kwargs else ''
    return ''.join(
        (domain, django_reverse(viewname, urlconf, args, kwargs,
                                current_app), qs))
Esempio n. 26
0
def reverse(viewname,
            *,
            args=None,
            kwargs=None,
            request=None,
            format=None,
            data=None,
            **extra):
    if format is not None:
        kwargs = kwargs or {}
        kwargs["format"] = format
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)

    if data is not None:
        url += "?" + urlencode(data)

    if request:
        url = request.build_absolute_uri(url)

    return url
Esempio n. 27
0
def translation_reverse(viewname,
                        urlconf=None,
                        args=None,
                        kwargs=None,
                        current_app=None,
                        lang=None):
    """
    Replacement for django's reverse that determines the
    correct URL for a given URL.
    """
    path = django_reverse(viewname,
                          urlconf=urlconf,
                          args=args,
                          kwargs=kwargs,
                          current_app=current_app)
    if settings.USE_I18N:
        return get_path_for_language(
            settings.LANGUAGE_CODE if not lang else lang, path)
    else:
        return path
Esempio n. 28
0
def _reverse(viewname,
             args=None,
             kwargs=None,
             request=None,
             format=None,
             **extra):
    """
    Same as `django.urls.reverse`, but optionally takes request and is_absolute_uri;
    returns a fully qualified URL if is_absolute_uri is True, using the gate_way_domain
    or request to get the base URL.
    """
    if format is not None:
        kwargs = kwargs or {}
        kwargs['format'] = format
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
    if request and is_absolute_uri:
        if gate_way_domain:
            url = gate_way_domain + url
        else:
            url = request.build_absolute_uri(url)
    return url
Esempio n. 29
0
    def test_redirect_no_perm(self, client):
        ds = create_some_datastructure_data()
        url = reverse(
            "retina:api:image-api-view",
            args=[
                image_type,
                ds["patient"].name,
                ds["study"].name,
                ds["image_cf"].name,
                "default",
            ],
        )

        user, _ = get_retina_user_with_token()
        client.force_login(user=user)
        response = client.get(url, follow=True)
        expected_redirect_url = django_reverse(reverse_name,
                                               args=[ds["image_cf"].id])
        assert status.HTTP_302_FOUND == response.redirect_chain[0][1]
        assert expected_redirect_url == response.redirect_chain[0][0]
        assert status.HTTP_403_FORBIDDEN == response.status_code
Esempio n. 30
0
    def test_redirect_no_perm(self, client):
        ds = create_some_datastructure_data()
        url = reverse(
            "retina:api:image-api-view",
            args=[
                image_type,
                ds["patient"].name,
                ds["study"].name,
                ds["image_cf"].name,
                "default",
            ],
        )

        user, _ = get_retina_user_with_token()
        client.force_login(user=user)
        response = client.get(url, follow=True)
        expected_redirect_url = django_reverse(
            reverse_name, args=[ds["image_cf"].id]
        )
        assert status.HTTP_302_FOUND == response.redirect_chain[0][1]
        assert expected_redirect_url == response.redirect_chain[0][0]
        assert status.HTTP_403_FORBIDDEN == response.status_code
Esempio n. 31
0
    def test_redirect_kappa(self, client):
        ds = create_some_datastructure_data(archive_pars={"name": "kappadata"})
        url = reverse(
            "retina:api:image-api-view",
            args=[
                image_type,
                "Archives",
                ds["archive"].name,
                ds["image_cf"].name,
                "default",
            ],
        )
        user, _ = get_retina_user_with_token()
        client.force_login(user=user)
        ds["image_cf"].permit_viewing_by_retina_users()

        response = client.get(url, follow=True)
        expected_redirect_url = django_reverse(reverse_name,
                                               args=[ds["image_cf"].id])
        assert response.redirect_chain[0][1] == status.HTTP_302_FOUND
        assert expected_redirect_url == response.redirect_chain[0][0]
        assert status.HTTP_200_OK == response.status_code
Esempio n. 32
0
    def _mails(self, users_and_watches):
        """Send readiness mails."""
        revision = self.revision
        document = revision.document
        log.debug("Sending ready notifications for revision (id=%s)" % revision.id)

        subject = _lazy("{title} has a revision ready for localization")

        url = django_reverse("wiki.translate", args=[document.slug])

        context = context_dict(revision, ready_for_l10n=True)
        context["l10n_url"] = add_utm(url, "wiki-ready-l10n")
        context["title"] = document.title

        return email_utils.emails_with_users_and_watches(
            subject=subject,
            text_template="wiki/email/ready_for_l10n.ltxt",
            html_template="wiki/email/ready_for_l10n.html",
            context_vars=context,
            users_and_watches=users_and_watches,
            default_locale=document.locale,
        )
Esempio n. 33
0
def reverse(viewname,
            url_args=None,
            query_params=None,
            current_app=None,
            urlconf=None):
    """An override of django reverse function supporting query parameters.

    Args:
        viewname (str): the name of the django view from which to compute a url
        url_args (dict): dictionary of url arguments indexed by their names
        query_params (dict): dictionary of query parameters to append to the
            reversed url
        current_app (str): the name of the django app tighten to the view
        urlconf (str): url configuration module

    Returns:
        str: the url of the requested view with processed arguments and
        query parameters
    """

    if url_args:
        url_args = {k: v for k, v in url_args.items() if v is not None}

    url = django_reverse(viewname,
                         urlconf=urlconf,
                         kwargs=url_args,
                         current_app=current_app)

    if query_params:
        query_params = {k: v for k, v in query_params.items() if v}

    if query_params and len(query_params) > 0:
        query_dict = QueryDict('', mutable=True)
        for k in sorted(query_params.keys()):
            query_dict[k] = query_params[k]
        url += ('?' + query_dict.urlencode(safe='/;:'))

    return url
Esempio n. 34
0
    def test_redirect_kappa(self, client):
        ds = create_some_datastructure_data(archive_pars={"name": "kappadata"})
        url = reverse(
            "retina:api:image-api-view",
            args=[
                image_type,
                "Archives",
                ds["archive"].name,
                ds["image_cf"].name,
                "default",
            ],
        )
        user, _ = get_retina_user_with_token()
        client.force_login(user=user)
        ds["image_cf"].permit_viewing_by_retina_users()

        response = client.get(url, follow=True)
        expected_redirect_url = django_reverse(
            reverse_name, args=[ds["image_cf"].id]
        )
        assert response.redirect_chain[0][1] == status.HTTP_302_FOUND
        assert expected_redirect_url == response.redirect_chain[0][0]
        assert status.HTTP_200_OK == response.status_code
Esempio n. 35
0
def reverse(viewname, *args, **kwargs):
    """Same behavior as django's reverse but uses django_sites to compute absolute url.
    """
    return get_absolute_url(django_reverse(viewname, *args, **kwargs))
Esempio n. 36
0
def test_redirect():
    assert django_reverse("accounts:user-redirect") == "/accounts/redirect/"
    assert resolve("/accounts/redirect/").view_name == "accounts:user-redirect"
Esempio n. 37
0
def test_update():
    assert django_reverse("accounts:user-update") == "/accounts/update/"
    assert resolve("/accounts/update/").view_name == "accounts:user-update"