Exemplo n.º 1
0
    def _action(self) -> None:
        assert user.id is not None

        users = userdb.load_users(lock=True)
        user_spec = users[user.id]

        cur_password = request.get_str_input_mandatory("cur_password")
        password = request.get_str_input_mandatory("password")
        password2 = request.get_str_input_mandatory("password2", "")

        # Force change pw mode
        if not cur_password:
            raise MKUserError("cur_password", _("You need to provide your current password."))

        if not password:
            raise MKUserError("password", _("You need to change your password."))

        if cur_password == password:
            raise MKUserError("password", _("The new password must differ from your current one."))

        if userdb.check_credentials(user.id, cur_password) is False:
            raise MKUserError("cur_password", _("Your old password is wrong."))

        if password2 and password != password2:
            raise MKUserError("password2", _("The both new passwords do not match."))

        watolib.verify_password_policy(password)
        user_spec["password"] = hash_password(password)
        user_spec["last_pw_change"] = int(time.time())

        # In case the user was enforced to change it's password, remove the flag
        try:
            del user_spec["enforce_pw_change"]
        except KeyError:
            pass

        # Increase serial to invalidate old authentication cookies
        if "serial" not in user_spec:
            user_spec["serial"] = 1
        else:
            user_spec["serial"] += 1

        userdb.save_users(users)

        flash(_("Successfully changed password."))

        # Set the new cookie to prevent logout for the current user
        login.update_auth_cookie(user.id)

        # In distributed setups with remote sites where the user can login, start the
        # user profile replication now which will redirect the user to the destination
        # page after completion. Otherwise directly open up the destination page.
        origtarget = request.get_str_input_mandatory("_origtarget", "user_change_pw.py")
        if user.authorized_login_sites():
            raise redirect(
                makeuri_contextless(
                    request, [("back", origtarget)], filename="user_profile_replicate.py"
                )
            )
        raise redirect(origtarget)
Exemplo n.º 2
0
    def _action(self) -> None:
        assert user.id is not None
        credentials = load_two_factor_credentials(user.id, lock=True)

        credential_id = request.get_ascii_input_mandatory("_edit")
        credential = credentials["webauthn_credentials"].get(credential_id)
        if credential is None:
            raise MKUserError("_edit", _("The credential does not exist"))

        vs = self._valuespec(credential)
        settings = vs.from_html_vars("profile")
        vs.validate_value(settings, "profile")

        credential["alias"] = settings["alias"]

        save_two_factor_credentials(user.id, credentials)

        flash(_("Successfully changed the credential."))

        # In distributed setups with remote sites where the user can login, start the
        # user profile replication now which will redirect the user to the destination
        # page after completion. Otherwise directly open up the destination page.
        origtarget = "user_two_factor_overview.py"
        if user.authorized_login_sites():
            raise redirect(
                makeuri_contextless(request, [("back", origtarget)],
                                    filename="user_profile_replicate.py"))
        raise redirect(origtarget)
Exemplo n.º 3
0
    def action(self) -> ActionResult:
        folder = watolib.Folder.current()
        if not html.check_transaction():
            return redirect(mode_url("folder", folder=folder.path()))

        if html.request.var("_update_dns_cache") and self._should_use_dns_cache():
            config.user.need_permission("wato.update_dns_cache")
            num_updated, failed_hosts = watolib.check_mk_automation(self._host.site_id(),
                                                                    "update-dns-cache", [])
            infotext = _("Successfully updated IP addresses of %d hosts.") % num_updated
            if failed_hosts:
                infotext += "<br><br><b>Hostnames failed to lookup:</b> " \
                          + ", ".join(["<tt>%s</tt>" % h for h in failed_hosts])
            flash(infotext)
            return None

        if html.request.var("delete"):  # Delete this host
            folder.delete_hosts([self._host.name()])
            return redirect(mode_url("folder", folder=folder.path()))

        attributes = watolib.collect_attributes("host" if not self._is_cluster() else "cluster",
                                                new=False)
        watolib.Host.host(self._host.name()).edit(attributes, self._get_cluster_nodes())
        self._host = folder.host(self._host.name())

        if html.request.var("services"):
            return redirect(mode_url("inventory", folder=folder.path(), host=self._host.name()))
        if html.request.var("diag_host"):
            return redirect(
                mode_url("diag_host",
                         folder=folder.path(),
                         host=self._host.name(),
                         _start_on_load="1"))
        return redirect(mode_url("folder", folder=folder.path()))
Exemplo n.º 4
0
    def action(self) -> ActionResult:
        if not html.transaction_valid():
            return None

        action_var = html.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 html.check_transaction():
            return redirect(mode_url(self._mode_type.list_mode_name()))

        entries = self._store.load_for_modification()

        ident = html.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("delete", entry,
                         _("Removed the %s '%s'") % (self._mode_type.name_singular(), ident))
        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()))
Exemplo n.º 5
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()))
Exemplo n.º 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()))
Exemplo n.º 7
0
    def action(self) -> ActionResult:
        folder = Folder.current()
        if not transactions.check_transaction():
            return redirect(mode_url("folder", folder=folder.path()))

        if request.var("_update_dns_cache") and self._should_use_dns_cache():
            user.need_permission("wato.update_dns_cache")
            update_dns_cache_result = update_dns_cache(self._host.site_id())
            infotext = (_("Successfully updated IP addresses of %d hosts.") %
                        update_dns_cache_result.n_updated)
            if update_dns_cache_result.failed_hosts:
                infotext += "<br><br><b>Hostnames failed to lookup:</b> " + ", ".join(
                    [
                        "<tt>%s</tt>" % h
                        for h in update_dns_cache_result.failed_hosts
                    ])
            flash(infotext)
            return None

        if request.var("delete"):  # Delete this host
            folder.delete_hosts([self._host.name()], automation=delete_hosts)
            return redirect(mode_url("folder", folder=folder.path()))

        if request.var("_remove_tls_registration"):
            remove_tls_registration(
                {self._host.site_id(): [self._host.name()]})
            return None

        attributes = collect_attributes(
            "host" if not self._is_cluster() else "cluster", new=False)
        host = Host.host(self._host.name())
        if host is None:
            flash(f"Host {self._host.name()} could not be found.")
            return None

        host.edit(attributes, self._get_cluster_nodes())
        self._host = folder.load_host(self._host.name())

        if request.var("_save"):
            return redirect(
                mode_url("inventory",
                         folder=folder.path(),
                         host=self._host.name()))
        if request.var("diag_host"):
            return redirect(
                mode_url("diag_host",
                         folder=folder.path(),
                         host=self._host.name(),
                         _start_on_load="1"))
        return redirect(mode_url("folder", folder=folder.path()))
Exemplo n.º 8
0
    def action(self) -> ActionResult:
        varname = request.var("_varname")
        if not varname:
            return None

        action = request.var("_action")

        config_variable = config_variable_registry[varname]()
        def_value = self._default_values[varname]

        if not transactions.check_transaction():
            return None

        if varname in self._current_settings:
            self._current_settings[
                varname] = not self._current_settings[varname]
        else:
            self._current_settings[varname] = not def_value
        msg = _("Changed Configuration variable %s to %s.") % (
            varname,
            "on" if self._current_settings[varname] else "off",
        )
        save_global_settings(self._current_settings)

        _changes.add_change(
            "edit-configvar",
            msg,
            domains=[config_variable.domain()],
            need_restart=config_variable.need_restart(),
        )

        if action == "_reset":
            flash(msg)
        return redirect(mode_url("globalvars"))
Exemplo n.º 9
0
    def action(self) -> ActionResult:
        if html.request.var("_reset"):
            if not html.check_transaction():
                return None

            try:
                del self._current_settings[self._varname]
            except KeyError:
                pass

            msg: Union[
                HTML,
                str] = _("Resetted configuration variable %s to its default."
                         ) % self._varname
        else:
            new_value = self._valuespec.from_html_vars("ve")
            self._valuespec.validate_value(new_value, "ve")
            self._current_settings[self._varname] = new_value
            msg = _("Changed global configuration variable %s to %s.") \
                  % (self._varname, self._valuespec.value_to_text(new_value))
            # FIXME: THIS HTML(...) is needed because we do not know what we get from value_to_text!!
            msg = HTML(msg)

        self._save()
        watolib.add_change("edit-configvar",
                           msg,
                           sites=self._affected_sites(),
                           domains=[self._config_variable.domain()],
                           need_restart=self._config_variable.need_restart())

        return redirect(self._back_url())
Exemplo n.º 10
0
 def action(self) -> ActionResult:
     return redirect(
         makeuri_contextless(
             request,
             self._get_search_vars(),
         )
     )
Exemplo n.º 11
0
    def action(self) -> ActionResult:
        if request.var("_reset"):
            if not transactions.check_transaction():
                return None

            try:
                del self._current_settings[self._varname]
            except KeyError:
                pass

            msg = escape_to_html(
                _("Resetted configuration variable %s to its default.") %
                self._varname)
        else:
            new_value = self._valuespec.from_html_vars("ve")
            self._valuespec.validate_value(new_value, "ve")
            self._current_settings[self._varname] = new_value
            msg = HTML(
                _("Changed global configuration variable %s to %s.") % (
                    escaping.escape_attribute(self._varname),
                    self._valuespec.value_to_html(new_value),
                ))

        self._save()
        _changes.add_change(
            "edit-configvar",
            msg,
            sites=self._affected_sites(),
            domains=[self._config_variable.domain()],
            need_restart=self._config_variable.need_restart(),
        )

        return redirect(self._back_url())
Exemplo n.º 12
0
    def action(self) -> ActionResult:
        if html.request.has_var("backfolder"):
            # Edit icon on subfolder preview should bring user back to parent folder
            folder = watolib.Folder.folder(html.request.var("backfolder"))
        else:
            folder = watolib.Folder.current()

        if not html.check_transaction():
            return redirect(mode_url("folder", folder=folder.path()))

        # Title
        title = TextUnicode().from_html_vars("title")
        TextUnicode(allow_empty=False).validate_value(title, "title")

        attributes = watolib.collect_attributes("folder", new=self._folder.name() is None)
        self._save(title, attributes)

        return redirect(mode_url("folder", folder=folder.path()))
Exemplo n.º 13
0
def delete_host_after_confirm(delname) -> ActionResult:
    c = wato_confirm(_("Confirm host deletion"),
                     _("Do you really want to delete the host <tt>%s</tt>?") % delname)
    if c:
        watolib.Folder.current().delete_hosts([delname])
        # Delete host files
        return redirect(mode_url("folder", folder=watolib.Folder.current().path()))
    if c is False:  # not yet confirmed
        return FinalizeRequest(code=200)
    return None  # browser reload
Exemplo n.º 14
0
    def action(self) -> ActionResult:
        if not html.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")
        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())

        entries[self._ident] = self._entry

        if self._new:
            self._add_change(
                "add", self._entry,
                _("Added the %s '%s'") %
                (self._mode_type.name_singular(), self._ident))
        else:
            self._add_change(
                "edit", self._entry,
                _("Edited the %s '%s'") %
                (self._mode_type.name_singular(), self._ident))

        self._save(entries)

        return redirect(mode_url(self._mode_type.list_mode_name()))
Exemplo n.º 15
0
 def _delete_hosts_after_confirm(self, host_names) -> ActionResult:
     c = wato_confirm(
         _("Confirm deletion of %d hosts") % len(host_names),
         _("Do you really want to delete the %d selected hosts?") % len(host_names))
     if c:
         self._folder.delete_hosts(host_names)
         flash(_("Successfully deleted %d hosts") % len(host_names))
         return redirect(mode_url("folder", folder=self._folder.path()))
     if c is False:  # not yet confirmed
         return FinalizeRequest(code=200)
     return None  # browser reload
Exemplo n.º 16
0
 def action(self) -> ActionResult:
     if transactions.check_transaction():
         value = self._vs_key().from_html_vars("key")
         # Remove the secret key from known URL vars. Otherwise later constructed URLs
         # which use the current page context will contain the passphrase which could
         # leak the secret information
         request.del_var("key_p_passphrase")
         self._vs_key().validate_value(value, "key")
         self._create_key(value)
         return redirect(mode_url(self.back_mode))
     return None
Exemplo n.º 17
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return None

        user.need_permission("wato.edit_hosts")

        changed_attributes = collect_attributes("bulk", new=False)
        host_names = get_hostnames_from_checkboxes()
        for host_name in host_names:
            host = Folder.current().load_host(host_name)
            host.update_attributes(changed_attributes)
            # call_hook_hosts_changed() is called too often.
            # Either offer API in class Host for bulk change or
            # delay saving until end somehow

        flash(_("Edited %d hosts") % len(host_names))
        return redirect(Folder.current().url())
Exemplo n.º 18
0
    def _delete_subfolder_after_confirm(self, subfolder_name) -> ActionResult:
        subfolder = self._folder.subfolder(subfolder_name)
        msg = _("Do you really want to delete the folder %s?") % subfolder.title()
        if not config.wato_hide_filenames:
            msg += _(" Its directory is <tt>%s</tt>.") % subfolder.filesystem_path()
        num_hosts = subfolder.num_hosts_recursively()
        if num_hosts:
            msg += _(
                " The folder contains <b>%d</b> hosts, which will also be deleted!") % num_hosts
        c = wato_confirm(_("Confirm folder deletion"), msg)

        if c:
            self._folder.delete_subfolder(subfolder_name)
            return redirect(mode_url("folder", folder=self._folder.path()))
        if c is False:  # not yet confirmed
            return FinalizeRequest(code=200)
        return None  # browser reload
Exemplo n.º 19
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return None

        user.need_permission("wato.edit_hosts")
        to_clean = self._bulk_collect_cleaned_attributes()
        if "contactgroups" in to_clean:
            self._folder.need_permission("write")

        hosts = get_hosts_from_checkboxes()

        # Check all permissions before doing any edit
        for host in hosts:
            host.need_permission("write")

        for host in hosts:
            host.clean_attributes(to_clean)

        return redirect(self._folder.url())
Exemplo n.º 20
0
    def action(self) -> ActionResult:
        if html.check_transaction():
            value = self._vs_key().from_html_vars("key")
            html.request.del_var("key_p_passphrase")
            self._vs_key().validate_value(value, "key")

            key_file = self._get_uploaded(value, "key_file")
            if not key_file:
                raise MKUserError(None, _("You need to provide a key file."))

            if not key_file.startswith("-----BEGIN ENCRYPTED PRIVATE KEY-----\n") \
               or "-----END ENCRYPTED PRIVATE KEY-----\n" not in key_file \
               or "-----BEGIN CERTIFICATE-----\n" not in key_file \
               or not key_file.endswith("-----END CERTIFICATE-----\n"):
                raise MKUserError(None, _("The file does not look like a valid key file."))

            self._upload_key(key_file, value)
            return redirect(mode_url(self.back_mode))
        return None
Exemplo n.º 21
0
    def action(self) -> ActionResult:
        varname = html.request.var("_varname")
        if not varname:
            return None

        action = html.request.var("_action")

        config_variable = config_variable_registry[varname]()
        def_value = self._default_values[varname]

        if action == "reset" and not is_a_checkbox(config_variable.valuespec()):
            c = wato_confirm(
                _("Resetting configuration variable"),
                _("Do you really want to reset the configuration variable <b>%s</b> "
                  "back to the default value of <b><tt>%s</tt></b>?") %
                (varname, config_variable.valuespec().value_to_text(def_value)))
        else:
            if not html.check_transaction():
                return None
            c = True  # no confirmation for direct toggle

        if c:
            if varname in self._current_settings:
                self._current_settings[varname] = not self._current_settings[varname]
            else:
                self._current_settings[varname] = not def_value
            msg = _("Changed Configuration variable %s to %s.") % (
                varname, "on" if self._current_settings[varname] else "off")
            watolib.save_global_settings(self._current_settings)

            watolib.add_change("edit-configvar",
                               msg,
                               domains=[config_variable.domain()],
                               need_restart=config_variable.need_restart())

            if action == "_reset":
                flash(msg)
            return redirect(mode_url("globalvars"))
        if c is False:
            return FinalizeRequest(code=200)
        return None
Exemplo n.º 22
0
    def action(self) -> ActionResult:
        if html.request.var("_reset"):
            if not is_a_checkbox(self._valuespec):
                c = wato_confirm(
                    _("Resetting configuration variable"),
                    _("Do you really want to reset this configuration variable "
                      "back to its default value?"))
                if c is False:
                    return FinalizeRequest(code=200)
                if c is None:
                    return None
            elif not html.check_transaction():
                return None

            try:
                del self._current_settings[self._varname]
            except KeyError:
                pass

            msg: Union[
                HTML, str] = _("Resetted configuration variable %s to its default.") % self._varname
        else:
            new_value = self._valuespec.from_html_vars("ve")
            self._valuespec.validate_value(new_value, "ve")
            self._current_settings[self._varname] = new_value
            msg = _("Changed global configuration variable %s to %s.") \
                  % (self._varname, self._valuespec.value_to_text(new_value))
            # FIXME: THIS HTML(...) is needed because we do not know what we get from value_to_text!!
            msg = HTML(msg)

        self._save()
        watolib.add_change("edit-configvar",
                           msg,
                           sites=self._affected_sites(),
                           domains=[self._config_variable.domain()],
                           need_restart=self._config_variable.need_restart())

        page_menu = self.parent_mode()
        assert page_menu is not None
        return redirect(mode_url(page_menu.name()))
Exemplo n.º 23
0
    def action(self) -> ActionResult:
        if html.request.var("_search"):  # just commit to search form
            return None

        # Operations on SUBFOLDERS

        if html.request.var("_delete_folder"):
            if html.transaction_valid():
                return self._delete_subfolder_after_confirm(html.request.var("_delete_folder"))
            return None

        if html.request.has_var("_move_folder_to"):
            if html.check_transaction():
                what_folder = watolib.Folder.folder(html.request.var("_ident"))
                target_folder = watolib.Folder.folder(html.request.var("_move_folder_to"))
                watolib.Folder.current().move_subfolder_to(what_folder, target_folder)
            return None

        # Operations on HOSTS

        # Deletion of single hosts
        delname = html.request.var("_delete_host")
        if delname and watolib.Folder.current().has_host(delname):
            return delete_host_after_confirm(delname)

        # Move single hosts to other folders
        if html.request.has_var("_move_host_to"):
            hostname = html.request.var("_ident")
            if hostname:
                target_folder = watolib.Folder.folder(html.request.var("_move_host_to"))
                watolib.Folder.current().move_hosts([hostname], target_folder)
                return None

        # bulk operation on hosts
        if not html.transaction_valid():
            return None

        # Host table: No error message on search filter reset
        if html.request.var("_hosts_reset_sorting") or html.request.var("_hosts_sort"):
            return None

        selected_host_names = get_hostnames_from_checkboxes()
        if not selected_host_names:
            raise MKUserError(None,
                              _("Please select some hosts before doing bulk operations on hosts."))

        if html.request.var("_bulk_inventory"):
            return redirect(mode_url("bulkinventory", folder=watolib.Folder.current().path()))

        if html.request.var("_parentscan"):
            return redirect(mode_url("parentscan", folder=watolib.Folder.current().path()))

        # Deletion
        if html.request.var("_bulk_delete"):
            return self._delete_hosts_after_confirm(selected_host_names)

        # Move
        if html.request.var("_bulk_move"):
            target_folder_path = html.request.var("_bulk_moveto",
                                                  html.request.var("_top_bulk_moveto"))
            if target_folder_path == "@":
                raise MKUserError("_bulk_moveto", _("Please select the destination folder"))
            target_folder = watolib.Folder.folder(target_folder_path)
            watolib.Folder.current().move_hosts(selected_host_names, target_folder)
            flash(_("Moved %d hosts to %s") % (len(selected_host_names), target_folder.title()))
            return None

        # Move to target folder (from import)
        if html.request.var("_bulk_movetotarget"):
            return self._move_to_imported_folders(selected_host_names)

        if html.request.var("_bulk_edit"):
            return redirect(mode_url("bulkedit", folder=watolib.Folder.current().path()))

        if html.request.var("_bulk_cleanup"):
            return redirect(mode_url("bulkcleanup", folder=watolib.Folder.current().path()))

        return None
Exemplo n.º 24
0
 def action(self) -> ActionResult:
     self._remove_unused_search_vars()
     return redirect(mode_url("folder", folder=self._folder.path()))
Exemplo n.º 25
0
    def action(self) -> ActionResult:
        if html.request.var("_search"):  # just commit to search form
            return None

        folder_url = self._folder.url()

        # Operations on SUBFOLDERS

        if html.request.var("_delete_folder"):
            if html.check_transaction():
                self._folder.delete_subfolder(html.request.var("_delete_folder"))
            return redirect(folder_url)

        if html.request.has_var("_move_folder_to"):
            if html.check_transaction():
                what_folder = watolib.Folder.folder(html.request.var("_ident"))
                target_folder = watolib.Folder.folder(html.request.var("_move_folder_to"))
                watolib.Folder.current().move_subfolder_to(what_folder, target_folder)
            return redirect(folder_url)

        # Operations on HOSTS

        # Deletion of single hosts
        delname = html.request.var("_delete_host")
        if delname and watolib.Folder.current().has_host(delname):
            watolib.Folder.current().delete_hosts([delname])
            return redirect(folder_url)

        # Move single hosts to other folders
        if html.request.has_var("_move_host_to"):
            hostname = html.request.var("_ident")
            if hostname and watolib.Folder.current().has_host(hostname):
                target_folder = watolib.Folder.folder(html.request.var("_move_host_to"))
                watolib.Folder.current().move_hosts([hostname], target_folder)
                return redirect(folder_url)

        # bulk operation on hosts
        if not html.transaction_valid():
            return redirect(folder_url)

        # Host table: No error message on search filter reset
        if html.request.var("_hosts_reset_sorting") or html.request.var("_hosts_sort"):
            return None

        selected_host_names = get_hostnames_from_checkboxes()
        if not selected_host_names:
            raise MKUserError(None,
                              _("Please select some hosts before doing bulk operations on hosts."))

        # Move
        if html.request.var("_bulk_move"):
            target_folder_path = html.request.var("_bulk_moveto",
                                                  html.request.var("_top_bulk_moveto"))
            if target_folder_path == "@":
                raise MKUserError("_bulk_moveto", _("Please select the destination folder"))
            target_folder = watolib.Folder.folder(target_folder_path)
            watolib.Folder.current().move_hosts(selected_host_names, target_folder)
            flash(_("Moved %d hosts to %s") % (len(selected_host_names), target_folder.title()))
            return redirect(folder_url)

        # Move to target folder (from import)
        if html.request.var("_bulk_movetotarget"):
            self._move_to_imported_folders(selected_host_names)
            return redirect(folder_url)

        # Deletion
        if html.request.var("_bulk_delete"):
            return self._delete_hosts(selected_host_names)

        search_text = html.request.get_unicode_input_mandatory("search", "")
        for request_var, mode_name in [
            ("_bulk_inventory", "bulkinventory"),
            ("_parentscan", "parentscan"),
            ("_bulk_edit", "bulkedit"),
            ("_bulk_cleanup", "bulkcleanup"),
        ]:
            if html.request.var(request_var):
                return redirect(
                    self._folder.url(add_vars=[
                        ("mode", mode_name),
                        ("search", search_text),
                        ("selection", weblib.selection_id()),
                    ]))

        return None
Exemplo n.º 26
0
 def action(self) -> ActionResult:
     self._remove_unused_search_vars()
     return redirect(self._folder.url())
Exemplo n.º 27
0
 def _delete_hosts(self, host_names) -> ActionResult:
     self._folder.delete_hosts(host_names)
     flash(_("Successfully deleted %d hosts") % len(host_names))
     return redirect(self._folder.url())