Пример #1
0
def test_breadcrumb_add():
    i1 = BreadcrumbItem("Title1", "index.py")
    b1 = Breadcrumb([i1])

    i2 = BreadcrumbItem("Title2", "index.py")
    b2 = Breadcrumb([i2])

    b3 = b1 + b2
    assert len(b1) == 1
    assert len(b2) == 1
    assert len(b3) == 2
Пример #2
0
    def page_menu(self, breadcrumb: Breadcrumb) -> PageMenu:
        new = self._folder.name() is None
        is_enabled = new or not watolib.Folder.current().locked()

        # When backfolder is set, we have the special situation that we want to redirect the user
        # two breadcrumb layers up. This is a very specific case, so we realize this locally instead
        # of using a generic approach. Just like it done locally by the action method.
        if html.request.has_var("backfolder"):
            breadcrumb = make_folder_breadcrumb(
                watolib.Folder.folder(html.request.var("backfolder")))
            breadcrumb.append(self._breadcrumb_item())

        return make_simple_form_page_menu(breadcrumb,
                                          form_name="edit_host",
                                          button_name="save",
                                          save_is_enabled=is_enabled)
Пример #3
0
def make_header(
    writer: HTMLGenerator,
    title: str,
    breadcrumb: Breadcrumb,
    page_menu: Optional[PageMenu] = None,
    page_state: Optional[PageState] = None,
    javascripts: Optional[Sequence[str]] = None,
    force: bool = False,
    show_body_start: bool = True,
    show_top_heading: bool = True,
) -> None:
    if writer.output_format != "html":
        return

    if not writer._header_sent:
        if show_body_start:
            writer.body_start(title, javascripts=javascripts, force=force)

        writer._header_sent = True

        breadcrumb = breadcrumb or Breadcrumb()

        if writer.render_headfoot and show_top_heading:
            top_heading(
                writer,
                writer.request,
                title,
                breadcrumb=breadcrumb,
                page_menu=page_menu or PageMenu(breadcrumb=breadcrumb),
                page_state=page_state,
                browser_reload=writer.browser_reload,
            )
    writer.begin_page_content()
Пример #4
0
    def page(self) -> None:
        assert user.id is not None

        html.set_render_headfoot(False)
        html.add_body_css_class("login")
        html.add_body_css_class("two_factor")
        html.header(_("Two-factor authentication"), Breadcrumb(), javascripts=[])

        html.open_div(id_="login")

        html.open_div(id_="login_window")

        html.open_a(href="https://checkmk.com")
        html.img(
            src=theme.detect_icon_path(icon_name="logo", prefix="mk-"),
            id_="logo",
            class_="custom" if theme.has_custom_logo() else None,
        )
        html.close_a()

        if not is_two_factor_login_enabled(user.id):
            raise MKGeneralException(_("Two-factor authentication not enabled"))

        html.begin_form(
            "two_factor_login", method="POST", add_transid=False, action="user_login_two_factor.py"
        )
        html.prevent_password_auto_completion()
        html.hidden_field(
            "_origtarget", origtarget := request.get_url_input("_origtarget", "index.py")
        )

        if backup_code := request.get_ascii_input("_backup_code"):
            if is_two_factor_backup_code_valid(user.id, backup_code):
                set_two_factor_completed()
                raise HTTPRedirect(origtarget)
Пример #5
0
    def show_with_timeseries(self):
        html.header("", Breadcrumb())
        div_id = "%s_dashlet_%d" % (self.type_name(), self._dashlet_id)
        html.div("", id_=div_id)

        fetch_url = "ajax_single_graph_metric_data.py"
        args: HTTPVariables = []
        args.append(("context", json.dumps(self._dashlet_spec["context"])))
        args.append(
            ("properties", json.dumps(self.vs_parameters().value_to_json(self._dashlet_spec))))
        body = html.urlencode_vars(args)

        html.javascript(
            """
            let single_metric_class_%(dashlet_id)d = cmk.figures.figure_registry.get_figure("single_metric");
            let %(instance_name)s = new single_metric_class_%(dashlet_id)d(%(div_selector)s);
            %(instance_name)s.initialize();
            %(instance_name)s.set_post_url_and_body(%(url)s, %(body)s);
            %(instance_name)s.scheduler.set_update_interval(%(update)d);
            %(instance_name)s.scheduler.enable();
            """ % {
                "dashlet_id": self._dashlet_id,
                "instance_name": self.instance_name,
                "div_selector": json.dumps("#%s" % div_id),
                "url": json.dumps(fetch_url),
                "body": json.dumps(body),
                "update": 60,
            })
Пример #6
0
def _confirm(html_title, message):
    if not html.request.has_var("_do_confirm") and not html.request.has_var(
            "_do_actions"):
        # TODO: get the breadcrumb from all call sites
        wato_html_head(title=html_title, breadcrumb=Breadcrumb())
    confirm_options = [(_("Confirm"), "_do_confirm")]
    return confirm_with_preview(message, confirm_options)
Пример #7
0
 def breadcrumb(self):
     return Breadcrumb([
         BreadcrumbItem(
             title="Hosts",
             url=watolib.Folder.root_folder().url(),
         ),
     ]) + self._folder.breadcrumb()
Пример #8
0
def make_folder_breadcrumb(folder: watolib.CREFolder) -> Breadcrumb:
    return Breadcrumb([
        BreadcrumbItem(
            title=_("Hosts"),
            url=None,
        ),
    ]) + folder.breadcrumb()
Пример #9
0
def _page_not_found() -> Response:
    # TODO: This is a page handler. It should not be located in generic application
    # object. Move it to another place
    if request.has_var("_plain_error"):
        html.write_text(_("Page not found"))
    else:
        title = _("Page not found")
        make_header(
            html,
            title,
            Breadcrumb([
                BreadcrumbItem(
                    title="Nowhere",
                    url=None,
                ),
                BreadcrumbItem(
                    title=title,
                    url="javascript:document.location.reload(false)",
                ),
            ]),
        )
        html.show_error(_("This page was not found. Sorry."))
    html.footer()

    return response
Пример #10
0
def test_breadcrumb_creation():
    i1 = BreadcrumbItem("Title1", "index.py")

    b = Breadcrumb([i1])
    assert len(b) == 1
    assert b[0].title == "Title1"

    b.append(BreadcrumbItem("Title2", "index.py"))
    assert len(b) == 2
    assert b[1].title == "Title2"

    b += [  # type: ignore[misc]
        BreadcrumbItem("Title3", "index.py"),
        BreadcrumbItem("Title4", "index.py"),
    ]
    assert isinstance(b, Breadcrumb)
    assert len(b) == 4
    assert b[2].title == "Title3"
    assert b[3].title == "Title4"
Пример #11
0
def _render_exception(e: Exception, title: str) -> Response:
    if plain_error():
        html.set_output_format("text")
        if title:
            title = "%s: " % title
        html.write("%s%s\n" % (title, e))

    elif not fail_silently():
        html.header(title, Breadcrumb())
        html.show_error(str(e))
        html.footer()

    return html.response
Пример #12
0
def _show_crash_dump_message(
    crash: "GUICrashReport", plain_text: bool, fail_silently: bool, show_crash_link: Optional[bool]
) -> None:
    """Create a crash dump from a GUI exception and display a message to the user"""

    if show_crash_link is None:
        show_crash_link = user.may("general.see_crash_reports")

    title = _("Internal error")
    message = "%s: %s<br>\n<br>\n" % (title, crash.crash_info["exc_value"])
    # Do not reveal crash context information to unauthenticated users or not permitted
    # users to prevent disclosure of internal information
    if not show_crash_link:
        message += _(
            "An internal error occurred while processing your request. "
            "You can report this issue to your Checkmk administrator. "
            "Detailed information can be found on the crash report page "
            "or in <tt>var/log/web.log</tt>."
        )
    else:
        crash_url = makeuri(
            request,
            [
                ("site", omd_site()),
                ("crash_id", crash.ident_to_text()),
            ],
            filename="crash.py",
        )
        message += (
            _(
                "An internal error occured while processing your request. "
                "You can report this issue to the Checkmk team to help "
                'fixing this issue. Please open the <a href="%s">crash report page</a> '
                "and use the form for reporting the problem."
            )
            % crash_url
        )

    if plain_text:
        response.set_content_type("text/plain")
        response.set_data("%s\n" % escaping.strip_tags(message))
        return

    if fail_silently:
        return

    html.header(title, Breadcrumb())
    html.show_error(message)
    html.footer()
Пример #13
0
def _render_exception(e: Exception, title: str) -> Response:
    if plain_error():
        return Response(
            response=[
                "%s%s\n" % (("%s: " % title) if title else "", e),
            ],
            mimetype="text/plain",
        )

    if not fail_silently():
        html.header(title, Breadcrumb())
        html.show_error(str(e))
        html.footer()

    return response
Пример #14
0
    def main_menu(self) -> MegaMenu:
        """Specify the top-level breadcrumb item of this mode"""
        return MegaMenuSetup

    def breadcrumb(self) -> Breadcrumb:
        """Render the breadcrumb to the current mode

        This methods job is to a) gather the breadcrumb from the
        parent modes, b) append it's own part and then return it
        """

        if parent_cls := self.parent_mode():
            # For some reason pylint does not understand that this is a class type
            breadcrumb = parent_cls().breadcrumb()  # pylint: disable=not-callable
        else:
            breadcrumb = Breadcrumb()

        # For the currently active mode use the same link as the "page title click"
        if html.request.get_ascii_input("mode") == self.name():
            breadcrumb_url = "javascript:window.location.reload(false)"
        else:
            breadcrumb_url = self._breadcrumb_url()

        breadcrumb.append(
            BreadcrumbItem(
                title=self.title(),
                url=breadcrumb_url,
            ))

        return breadcrumb
Пример #15
0
    def main_menu(self) -> MegaMenu:
        """Specify the top-level breadcrumb item of this mode"""
        return mega_menu_registry.menu_setup()

    def breadcrumb(self) -> Breadcrumb:
        """Render the breadcrumb to the current mode

        This methods job is to a) gather the breadcrumb from the
        parent modes, b) append it's own part and then return it
        """

        if parent_cls := self.parent_mode():
            # For some reason pylint does not understand that this is a class type
            breadcrumb = parent_cls().breadcrumb()  # pylint: disable=not-callable
        else:
            breadcrumb = Breadcrumb()

        breadcrumb.extend(self._topic_breadcrumb_item())
        breadcrumb.append(self._breadcrumb_item())

        return breadcrumb

    def _breadcrumb_item(self) -> BreadcrumbItem:
        """Return the breadcrumb item for the current mode"""
        # For the currently active mode use the same link as the "page title click"
        if request.get_ascii_input("mode") == self.name():
            breadcrumb_url = "javascript:window.location.reload(false)"
        else:
            breadcrumb_url = self._breadcrumb_url()

        return BreadcrumbItem(
Пример #16
0
    def _show_login_page(self) -> None:
        html.set_render_headfoot(False)
        html.add_body_css_class("login")
        html.header(config.get_page_heading(), Breadcrumb(), javascripts=[])

        default_origtarget = ("index.py" if html.myfile in ["login", "logout"]
                              else makeuri(global_request, []))
        origtarget = html.get_url_input("_origtarget", default_origtarget)

        # Never allow the login page to be opened in the iframe. Redirect top page to login page.
        # This will result in a full screen login page.
        html.javascript('''if(top != self) {
    window.top.location.href = location;
}''')

        # When someone calls the login page directly and is already authed redirect to main page
        if html.myfile == 'login' and _check_auth(html.request):
            raise HTTPRedirect(origtarget)

        html.open_div(id_="login")

        html.open_div(id_="login_window")

        html.div("" if "hide_version" in config.login_screen else
                 cmk_version.__version__,
                 id_="version")

        html.begin_form("login",
                        method='POST',
                        add_transid=False,
                        action='login.py')
        html.hidden_field('_login', '1')
        html.hidden_field('_origtarget', origtarget)
        html.label("%s:" % _('Username'),
                   id_="label_user",
                   class_=["legend"],
                   for_="_username")
        html.br()
        html.text_input("_username", id_="input_user")
        html.label("%s:" % _('Password'),
                   id_="label_pass",
                   class_=["legend"],
                   for_="_password")
        html.br()
        html.password_input("_password", id_="input_pass", size=None)

        if html.has_user_errors():
            html.open_div(id_="login_error")
            html.show_user_errors()
            html.close_div()

        html.open_div(id_="button_text")
        html.button("_login", _('Login'))
        html.close_div()
        html.close_div()

        html.open_div(id_="foot")

        if config.login_screen.get("login_message"):
            html.open_div(id_="login_message")
            html.show_message(config.login_screen["login_message"])
            html.close_div()

        footer: List[Union[HTML, str]] = []
        for title, url, target in config.login_screen.get("footer_links", []):
            footer.append(html.render_a(title, href=url, target=target))

        if "hide_version" not in config.login_screen:
            footer.append("Version: %s" % cmk_version.__version__)

        footer.append("&copy; %s" % html.render_a(
            "tribe29 GmbH", href="https://checkmk.com", target="_blank"))

        html.write(HTML(" - ").join(footer))

        if cmk_version.is_raw_edition():
            html.br()
            html.br()
            html.write(
                _('You can use, modify and distribute Check_MK under the terms of the <a href="%s" target="_blank">'
                  'GNU GPL Version 2</a>.') % "https://checkmk.com/gpl.html")

        html.close_div()

        html.set_focus('_username')
        html.hidden_fields()
        html.end_form()
        html.close_div()

        html.footer()
Пример #17
0
    def main_menu(self) -> MegaMenu:
        """Specify the top-level breadcrumb item of this mode"""
        return mega_menu_registry.menu_setup()

    def breadcrumb(self) -> Breadcrumb:
        """Render the breadcrumb to the current mode

        This methods job is to a) gather the breadcrumb from the
        parent modes, b) append it's own part and then return it
        """

        if parent_cls := self.parent_mode():
            # For some reason pylint does not understand that this is a class type
            breadcrumb = parent_cls().breadcrumb()  # pylint: disable=not-callable
        else:
            breadcrumb = Breadcrumb()

            topic_item = self._topic_breadcrumb_item()
            if topic_item:
                breadcrumb.append(topic_item)

        breadcrumb.append(self._breadcrumb_item())

        return breadcrumb

    def _breadcrumb_item(self) -> BreadcrumbItem:
        """Return the breadcrumb item for the current mode"""
        # For the currently active mode use the same link as the "page title click"
        if html.request.get_ascii_input("mode") == self.name():
            breadcrumb_url = "javascript:window.location.reload(false)"
        else:
Пример #18
0
def _edit_annotation_breadcrumb(breadcrumb: Breadcrumb, title: str) -> Breadcrumb:
    breadcrumb.append(BreadcrumbItem(
        title=title,
        url=html.makeuri([]),
    ))
    return breadcrumb
Пример #19
0
def wato_confirm(html_title, message):
    if not html.request.has_var("_do_confirm") and not html.request.has_var("_do_actions"):
        # TODO: get the breadcrumb from all call sites
        wato_html_head(html_title, Breadcrumb())
    return html.confirm(message)
Пример #20
0
def make_main_menu_breadcrumb(menu: MegaMenu) -> Breadcrumb:
    """Create a breadcrumb for the main menu level"""
    return Breadcrumb([BreadcrumbItem(
        title=menu.title,
        url=None,
    )])
Пример #21
0
    def _show_login_page(self) -> None:
        html.set_render_headfoot(False)
        html.add_body_css_class("login")
        html.header(get_page_heading(), Breadcrumb(), javascripts=[])

        default_origtarget = ("index.py" if requested_file_name(request)
                              in ["login", "logout"] else makeuri(request, []))
        origtarget = request.get_url_input("_origtarget", default_origtarget)

        # Never allow the login page to be opened in the iframe. Redirect top page to login page.
        # This will result in a full screen login page.
        html.javascript("""if(top != self) {
    window.top.location.href = location;
}""")

        # When someone calls the login page directly and is already authed redirect to main page
        if requested_file_name(request) == "login" and _check_auth(request):
            raise HTTPRedirect(origtarget)

        html.open_div(id_="login")

        html.open_div(id_="login_window")

        html.open_a(href="https://checkmk.com")
        html.img(
            src=theme.detect_icon_path(icon_name="logo", prefix="mk-"),
            id_="logo",
            class_="custom" if theme.has_custom_logo() else None,
        )
        html.close_a()

        html.begin_form("login",
                        method="POST",
                        add_transid=False,
                        action="login.py")
        html.hidden_field("_login", "1")
        html.hidden_field("_origtarget", origtarget)
        html.label("%s:" % _("Username"),
                   id_="label_user",
                   class_=["legend"],
                   for_="_username")
        html.br()
        html.text_input("_username", id_="input_user")
        html.label("%s:" % _("Password"),
                   id_="label_pass",
                   class_=["legend"],
                   for_="_password")
        html.br()
        html.password_input("_password", id_="input_pass", size=None)

        if user_errors:
            html.open_div(id_="login_error")
            html.show_user_errors()
            html.close_div()

        html.open_div(id_="button_text")
        html.button("_login", _("Login"), cssclass="hot")
        html.close_div()
        html.close_div()

        html.open_div(id_="foot")

        if config.login_screen.get("login_message"):
            html.open_div(id_="login_message")
            html.show_message(config.login_screen["login_message"])
            html.close_div()

        footer: List[HTML] = []
        for title, url, target in config.login_screen.get("footer_links", []):
            footer.append(html.render_a(title, href=url, target=target))

        if "hide_version" not in config.login_screen:
            footer.append(escape_html("Version: %s" % cmk_version.__version__))

        footer.append(
            HTML("&copy; %s" % html.render_a(
                "tribe29 GmbH", href="https://tribe29.com", target="_blank")))

        html.write_html(HTML(" - ").join(footer))

        if cmk_version.is_raw_edition():
            html.br()
            html.br()
            html.write_text(
                _('You can use, modify and distribute Check_MK under the terms of the <a href="%s" target="_blank">'
                  "GNU GPL Version 2</a>.") % "https://checkmk.com/gpl.html")

        html.close_div()

        html.set_focus("_username")
        html.hidden_fields()
        html.end_form()
        html.close_div()

        html.footer()