Exemple #1
0
 def _ajax_add_bookmark(self) -> None:
     title = request.var("title")
     url = request.var("url")
     if title and url and transactions.transaction_valid():
         BookmarkList.validate_url(url, "url")
         self._add_bookmark(title, url)
     self.show()
Exemple #2
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return redirect(self.mode_url())

        if request.var("_delete"):
            delid = request.get_ascii_input_mandatory("_delete")

            if delid not in self._roles:
                raise MKUserError(None, _("This role does not exist."))

            if transactions.transaction_valid() and self._roles[delid].get("builtin"):
                raise MKUserError(None, _("You cannot delete the builtin roles!"))

            users = userdb.load_users()
            for user in users.values():
                if delid in user["roles"]:
                    raise MKUserError(
                        None,
                        _("You cannot delete roles, that are still in use (%s)!") % delid,
                    )

            self._rename_user_role(delid, None)  # Remove from existing users
            del self._roles[delid]
            self._save_roles()
            _changes.add_change(
                "edit-roles", _("Deleted role '%s'") % delid, sites=get_login_sites()
            )

        elif request.var("_clone"):
            cloneid = request.get_ascii_input_mandatory("_clone")

            try:
                cloned_role = self._roles[cloneid]
            except KeyError:
                raise MKUserError(None, _("This role does not exist."))

            newid = cloneid
            while newid in self._roles:
                newid += "x"

            new_role = {}
            new_role.update(cloned_role)

            new_alias = new_role["alias"]
            while not groups.is_alias_used("roles", newid, new_alias)[0]:
                new_alias += _(" (copy)")
            new_role["alias"] = new_alias

            if cloned_role.get("builtin"):
                new_role["builtin"] = False
                new_role["basedon"] = cloneid

            self._roles[newid] = new_role
            self._save_roles()
            _changes.add_change(
                "edit-roles", _("Created new role '%s'") % newid, sites=get_login_sites()
            )

        return redirect(self.mode_url())
Exemple #3
0
    def action(self) -> ActionResult:
        if not transactions.transaction_valid():
            return redirect(mode_url(self._mode_type.list_mode_name()))

        vs = self.valuespec()

        config = vs.from_html_vars("_edit")
        vs.validate_value(config, "_edit")

        if "ident" in config:
            self._ident = config.pop("ident")
        assert self._ident is not None
        self._entry = config

        entries = self._store.load_for_modification()

        if self._new and self._ident in entries:
            raise MKUserError(
                "ident",
                _("This ID is already in use. Please choose another one."))

        if not self._new and self._ident not in self._store.filter_editable_entries(
                entries):
            raise MKUserError(
                "ident",
                _("You are not allowed to edit this %s.") %
                self._mode_type.name_singular())

        if self._new:
            entries[self._ident] = self._entry
            self._add_change(
                action="add",
                text=_("Added the %s '%s'") %
                (self._mode_type.name_singular(), self._ident),
                affected_sites=self._mode_type.affected_sites(self._entry),
            )
        else:
            current_sites = self._mode_type.affected_sites(self._entry)
            previous_sites = self._mode_type.affected_sites(
                entries[self._ident])

            affected_sites = (None if current_sites is None
                              or previous_sites is None else sorted(
                                  {*previous_sites, *current_sites}))

            entries[self._ident] = self._entry

            self._add_change(
                action="edit",
                text=_("Edited the %s '%s'") %
                (self._mode_type.name_singular(), self._ident),
                affected_sites=affected_sites,
            )

        self._save(entries)

        return redirect(mode_url(self._mode_type.list_mode_name()))
Exemple #4
0
    def action(self) -> ActionResult:
        if transactions.transaction_valid():
            if request.has_var("_do_upload"):
                self._upload_csv_file()

            csv_reader = self._open_csv_file()

            if request.var("_do_import"):
                return self._import(csv_reader)
        return None
Exemple #5
0
    def _action(self) -> None:
        if not transactions.transaction_valid():
            return

        action_handler = gui_background_job.ActionHandler(
            self._breadcrumb(self._title()))

        if action_handler.handle_actions() and action_handler.did_delete_job():
            raise HTTPRedirect(
                makeuri_contextless(
                    request,
                    [
                        ("host", self._request.host.name()),
                        ("type", self._request.agent_type),
                        ("back_url", self._back_url),
                    ],
                ))
Exemple #6
0
    def action(self) -> ActionResult:
        if not transactions.transaction_valid():
            return redirect(mode_url("folder"))

        attributes = watolib.collect_attributes(self._host_type_name(),
                                                new=True)
        cluster_nodes = self._get_cluster_nodes()

        hostname = request.get_ascii_input_mandatory("host")
        Hostname().validate_value(hostname, "host")

        folder = watolib.Folder.current()

        if transactions.check_transaction():
            folder.create_hosts([(hostname, attributes, cluster_nodes)])

        self._host = folder.load_host(hostname)

        inventory_url = watolib.folder_preserving_link([
            ("mode", "inventory"),
            ("host", self._host.name()),
            ("_scan", "1"),
        ])

        create_msg = (None if self._host.is_ping_host() else (
            _("Successfully created the host. Now you should do a "
              '<a href="%s">service discovery</a> in order to auto-configure '
              "all services to be checked on this host.") % inventory_url))

        if request.var("_save"):
            return redirect(inventory_url)

        if create_msg:
            flash(create_msg)

        if request.var("diag_host"):
            return redirect(
                mode_url("diag_host",
                         folder=folder.path(),
                         host=self._host.name(),
                         _try="1"))

        return redirect(mode_url("folder", folder=folder.path()))
Exemple #7
0
    def action(self) -> ActionResult:
        if not transactions.transaction_valid():
            return None

        action_var = request.get_str_input("_action")
        if action_var is None:
            return None

        if action_var != "delete":
            return self._handle_custom_action(action_var)

        if not transactions.check_transaction():
            return redirect(mode_url(self._mode_type.list_mode_name()))

        entries = self._store.load_for_modification()

        ident = request.get_ascii_input("_delete")
        if ident not in entries:
            raise MKUserError(
                "_delete",
                _("This %s does not exist.") % self._mode_type.name_singular())

        if ident not in self._store.filter_editable_entries(entries):
            raise MKUserError(
                "_delete",
                _("You are not allowed to delete this %s.") %
                self._mode_type.name_singular(),
            )

        self._validate_deletion(ident, entries[ident])

        entry = entries.pop(ident)
        self._add_change(
            action="delete",
            text=_("Removed the %s '%s'") %
            (self._mode_type.name_singular(), ident),
            affected_sites=self._mode_type.affected_sites(entry),
        )
        self._store.save(entries)

        flash(_("The %s has been deleted.") % self._mode_type.name_singular())
        return redirect(mode_url(self._mode_type.list_mode_name()))
Exemple #8
0
def edit_dictionaries(
    dictionaries: "Sequence[Tuple[str, Union[Transform, Dictionary]]]",
    value: Dict[str, Any],
    focus: Optional[str] = None,
    hover_help: bool = True,
    validate: Optional[Callable[[Any], None]] = None,
    title: Optional[str] = None,
    method: str = "GET",
    preview: bool = False,
    varprefix: str = "",
    formname: str = "form",
    consume_transid: bool = True,
):

    if request.get_ascii_input("filled_in") == formname and transactions.transaction_valid():
        if not preview and consume_transid:
            transactions.check_transaction()

        messages: List[str] = []
        new_value: Dict[str, Dict[str, Any]] = {}
        for keyname, vs_dict in dictionaries:
            dict_varprefix = varprefix + keyname
            new_value[keyname] = {}
            try:
                edited_value = vs_dict.from_html_vars(dict_varprefix)
                vs_dict.validate_value(edited_value, dict_varprefix)
                new_value[keyname].update(edited_value)
            except MKUserError as e:
                messages.append("%s: %s" % (vs_dict.title() or _("Properties"), e))
                user_errors.add(e)
            except Exception as e:
                messages.append("%s: %s" % (vs_dict.title() or _("Properties"), e))
                user_errors.add(MKUserError(None, str(e)))

            if validate and not user_errors:
                try:
                    validate(new_value[keyname])
                except MKUserError as e:
                    messages.append(str(e))
                    user_errors.add(e)

        if messages:
            messages_joined = "".join(["%s<br>\n" % m for m in messages])
            if not preview:
                html.show_error(messages_joined)
            else:
                raise MKUserError(None, messages_joined)
        else:
            return new_value

    html.begin_form(formname, method=method)
    for keyname, vs_dict in dictionaries:
        dict_varprefix = varprefix + keyname
        subvalue = value.get(keyname, {})
        vs_dict.render_input_as_form(dict_varprefix, subvalue)

    end()
    # Should be ignored be hidden_fields, but I do not dare to change it there
    request.del_var("filled_in")
    html.hidden_fields()
    html.end_form()