コード例 #1
0
ファイル: shortener.py プロジェクト: yjacolin/c2cgeoportal
    def create(self):

        if "url" not in self.request.params:
            raise HTTPBadRequest("The parameter url is required")

        url = self.request.params["url"]

        # see: http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestline
        if len(url) > 8190:  # pragma: no cover
            raise HTTPBadRequest("The parameter url is too long ({} > {})".format(len(url), 8190))

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        hostname = uri_parts.hostname
        if "allowed_hosts" in self.settings:
            if hostname not in self.settings["allowed_hosts"]:  # pragma: no cover
                raise HTTPBadRequest("The requested host is not allowed.")
        else:
            if hostname != self.request.server_name:
                raise HTTPBadRequest("The requested host '{0!s}' should be '{1!s}'".format(
                    hostname, self.request.server_name
                ))

        shortened = False

        for base in self.short_bases:
            base_parts = urlparse(base)
            if uri_parts.path.startswith(base_parts.path):
                shortened = True
                ref = uri_parts.path.split("/")[-1]

        tries = 0
        while not shortened:
            ref = "".join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get("length", 4))
            )
            test_url = DBSession.query(Shorturl).filter(Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            tries += 1  # pragma: no cover
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to increase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get("email")
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        if "base_url" in self.settings:
            s_url = self.settings["base_url"] + ref
        else:
            s_url = self.request.route_url("shortener_get", ref=ref)

        email = email or user_email

        smtp_config = self.request.registry.settings.get("smtp", {})
        if \
                email is not None and \
                "email_from" in self.settings and \
                "email_subject" in self.settings and \
                "email_body" in self.settings:  # pragma: no cover
            text = self.settings["email_body"] % {
                "full_url": url,
                "short_url": s_url,
                "message": self.request.params.get("message", ""),
            }
            send_email(
                self.settings["email_from"],
                [email],
                text.encode("utf-8"),
                self.settings["email_subject"],
                smtp_config
            )

        set_common_headers(
            self.request, "shortener", NO_CACHE
        )
        return {"short_url": s_url}
コード例 #2
0
    def create(self):

        if "url" not in self.request.params:
            raise HTTPBadRequest("The parameter url is required")

        url = self.request.params["url"]

        # see: http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestline
        if len(url) > 8190:  # pragma: no cover
            raise HTTPBadRequest(
                "The parameter url is too long ({} > {})".format(
                    len(url), 8190))

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        hostname = uri_parts.hostname
        if "allowed_hosts" in self.settings:
            if hostname not in self.settings[
                    "allowed_hosts"]:  # pragma: no cover
                raise HTTPBadRequest("The requested host is not allowed.")
        else:
            if hostname != self.request.server_name:
                raise HTTPBadRequest(
                    "The requested host '{0!s}' should be '{1!s}'".format(
                        hostname, self.request.server_name))

        shortened = False

        for base in self.short_bases:
            base_parts = urlparse(base)
            if uri_parts.path.startswith(base_parts.path):
                shortened = True
                ref = uri_parts.path.split("/")[-1]

        tries = 0
        while not shortened:
            ref = "".join(
                random.choice(string.ascii_letters + string.digits)
                for i in range(self.settings.get("length", 4)))
            test_url = DBSession.query(Shorturl).filter(
                Shorturl.ref == ref).all()
            if len(test_url) == 0:
                break
            tries += 1  # pragma: no cover
            if tries > 20:  # pragma: no cover
                message = "No free ref found, considere to increase the length"
                logging.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email \
            if self.request.user is not None else None
        email = self.request.params.get("email")
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        if "base_url" in self.settings:
            s_url = self.settings["base_url"] + ref
        else:
            s_url = self.request.route_url("shortener_get", ref=ref)

        email = email or user_email

        if email is not None:  # pragma: no cover
            send_email_config(
                self.request.registry.settings,
                "shortener",
                email,
                full_url=url,
                short_url=s_url,
                message=self.request.params.get("message", ""),
            )

        set_common_headers(self.request, "shortener", NO_CACHE)
        return {"short_url": s_url}
コード例 #3
0
ファイル: shortener.py プロジェクト: camptocamp/c2cgeoportal
    def create(self) -> Dict[str, str]:

        if "url" not in self.request.params:
            raise HTTPBadRequest("The parameter url is required")

        url = self.request.params["url"]

        # see: https://httpd.apache.org/docs/2.2/mod/core.html#limitrequestline
        if len(url) > 8190:
            raise HTTPBadRequest(
                f"The parameter url is too long ({len(url)} > {8190})")

        # Check that it is an internal URL...
        uri_parts = urlparse(url)
        if "allowed_hosts" in self.settings:
            if uri_parts.netloc not in self.settings["allowed_hosts"]:
                raise HTTPBadRequest(
                    f"The requested host '{uri_parts.netloc}' is not part of allowed hosts: "
                    f"{', '.join(self.settings['allowed_hosts'])}")
        else:
            hostname = uri_parts.hostname
            if hostname != self.request.server_name:
                raise HTTPBadRequest(
                    f"The requested host '{hostname!s}' should be '{self.request.server_name!s}'"
                )

        shortened = False

        for base in self.short_bases:
            base_parts = urlparse(base)
            if uri_parts.path.startswith(base_parts.path):
                shortened = True
                ref = uri_parts.path.split("/")[-1]

        tries = 0
        while not shortened:
            ref = "".join(
                random.choice(string.ascii_letters + string.digits)  # nosec
                for i in range(self.settings.get("length", 4)))
            test_url = DBSession.query(Shorturl).filter(
                Shorturl.ref == ref).all()
            if not test_url:
                break
            tries += 1
            if tries > 20:
                message = "No free ref found, considered to increase the length"
                logger.error(message)
                raise HTTPInternalServerError(message)

        user_email = self.request.user.email if self.request.user is not None else None
        email = self.request.params.get("email")
        if not shortened:
            short_url = Shorturl()
            short_url.url = url
            short_url.ref = ref
            short_url.creator_email = user_email
            short_url.creation = datetime.now()
            short_url.nb_hits = 0

            DBSession.add(short_url)

        if "base_url" in self.settings:
            s_url = self.settings["base_url"] + ref
        else:
            s_url = self.request.route_url("shortener_get", ref=ref)

        if email is not None:
            send_email_config(
                self.request.registry.settings,
                "shortener",
                email,
                full_url=url,
                short_url=s_url,
                message=self.request.params.get("message", ""),
                application_url=self.request.route_url("base"),
                current_url=self.request.current_route_url(),
            )

        set_common_headers(self.request, "shortener", Cache.PRIVATE_NO)
        return {"short_url": s_url}