Exemple #1
0
    def _from_vars(self):
        self._hostname = self._vs_host().from_html_vars("host")
        self._vs_host().validate_value(self._hostname, "host")

        # TODO: validate all fields
        self._item = request.get_unicode_input_mandatory('file', u'')
        self._match_txt = request.get_unicode_input_mandatory('match', u'')

        self._host = watolib.Folder.current().host(self._hostname)

        if self._hostname and not self._host:
            raise MKUserError(None, _("This host does not exist."))

        if self._item and not self._hostname:
            raise MKUserError(None, _("You need to specify a host name to test file matching."))
Exemple #2
0
 def _file_path(self, file_id: Optional[str] = None) -> Path:
     if file_id is None:
         file_id = request.get_unicode_input_mandatory("file_id")
     if not file_id.isalnum():
         raise MKUserError("file_id",
                           _("The file_id has to be alphanumeric."))
     return self._upload_tmp_path / ("%s.csv" % file_id)
Exemple #3
0
def ajax_tree_openclose() -> None:
    tree = request.get_str_input_mandatory("tree")
    name = request.get_unicode_input_mandatory("name")

    config.user.set_tree_state(tree, name, request.get_str_input("state"))
    config.user.save_tree_states()
    response.set_data('OK')  # Write out something to make debugging easier
Exemple #4
0
def ajax_save_treestate():
    path_id = request.get_unicode_input_mandatory("path")
    current_ex_level_str, path = path_id.split(":", 1)
    current_ex_level = int(current_ex_level_str)

    if user.bi_expansion_level != current_ex_level:
        user.set_tree_states("bi", {})
    user.set_tree_state("bi", path, request.var("state") == "open")
    user.save_tree_states()

    user.bi_expansion_level = current_ex_level
Exemple #5
0
def _check_auth_automation() -> UserId:
    secret = request.get_str_input_mandatory("_secret", "").strip()
    user_id = request.get_unicode_input_mandatory("_username", "")

    user_id = UserId(user_id.strip())
    request.del_var_from_env("_username")
    request.del_var_from_env("_secret")

    if verify_automation_secret(user_id, secret):
        # Auth with automation secret succeeded - mark transid as unneeded in this case
        transactions.ignore()
        set_auth_type("automation")
        return user_id
    raise MKAuthException(_("Invalid automation secret for user %s") % user_id)
Exemple #6
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return redirect(mode_url("%s_groups" % self.type_name))

        alias = request.get_unicode_input_mandatory("alias").strip()
        self.group = {"alias": alias}

        self._determine_additional_group_data()

        if self._new:
            self._name = request.get_ascii_input_mandatory("name").strip()
            watolib.add_group(self._name, self.type_name, self.group)
        else:
            watolib.edit_group(self._name, self.type_name, self.group)

        return redirect(mode_url("%s_groups" % self.type_name))
Exemple #7
0
    def _evaluate_user_opts(self) -> Tuple[TableRows, bool, Optional[str]]:
        assert self.id is not None
        table_id = ensure_str(self.id)
        rows = self.rows

        search_term = None
        actions_enabled = (self.options["searchable"]
                           or self.options["sortable"])

        if not actions_enabled:
            return rows, False, None

        table_opts = user.tableoptions.setdefault(table_id, {})

        # Handle the initial visibility of the actions
        actions_visible = table_opts.get('actions_visible', False)
        if request.get_ascii_input('_%s_actions' % table_id):
            actions_visible = request.get_ascii_input('_%s_actions' %
                                                      table_id) == '1'
            table_opts['actions_visible'] = actions_visible

        if self.options["searchable"]:
            search_term = request.get_unicode_input_mandatory('search', '')
            # Search is always lower case -> case insensitive
            search_term = search_term.lower()
            if search_term:
                request.set_var('search', search_term)
                rows = _filter_rows(rows, search_term)

        if request.get_ascii_input('_%s_reset_sorting' % table_id):
            request.del_var('_%s_sort' % table_id)
            if 'sort' in table_opts:
                del table_opts['sort']  # persist

        if self.options["sortable"]:
            # Now apply eventual sorting settings
            sort = self._get_sort_column(table_opts)
            if sort is not None:
                request.set_var('_%s_sort' % table_id, sort)
                table_opts['sort'] = sort  # persist
                sort_col, sort_reverse = map(int, sort.split(',', 1))
                rows = _sort_rows(rows, sort_col, sort_reverse)

        if actions_enabled:
            user.save_tableoptions()

        return rows, actions_visible, search_term
Exemple #8
0
    def _from_vars(self):
        self._start = bool(request.var("_start"))
        # 'all' not set -> only scan checked hosts in current folder, no recursion
        # otherwise: all host in this folder, maybe recursively
        self._all = bool(request.var("all"))
        self._complete_folder = self._all

        # Ignored during initial form display
        self._settings = ParentScanSettings(
            where=request.get_ascii_input_mandatory("where", "subfolder"),
            alias=request.get_unicode_input_mandatory("alias", "").strip(),
            recurse=html.get_checkbox("recurse") or False,
            select=request.get_ascii_input_mandatory("select", "noexplicit"),
            timeout=request.get_integer_input_mandatory("timeout", 8),
            probes=request.get_integer_input_mandatory("probes", 2),
            max_ttl=request.get_integer_input_mandatory("max_ttl", 10),
            force_explicit=html.get_checkbox("force_explicit") or False,
            ping_probes=request.get_integer_input_mandatory("ping_probes", 5),
        )
        self._job = ParentScanBackgroundJob()
Exemple #9
0
    def action(self) -> ActionResult:
        if html.form_submitted("search"):
            return None

        alias = request.get_unicode_input_mandatory("alias")

        unique, info = watolib.is_alias_used("roles", self._role_id, alias)
        if not unique:
            assert info is not None
            raise MKUserError("alias", info)

        new_id = request.get_ascii_input_mandatory("id")
        if not new_id:
            raise MKUserError("id", "You have to provide a ID.")
        if not re.match("^[-a-z0-9A-Z_]*$", new_id):
            raise MKUserError(
                "id",
                _("Invalid role ID. Only the characters a-z, A-Z, 0-9, _ and - are allowed."
                  ))
        if new_id != self._role_id:
            if new_id in self._roles:
                raise MKUserError("id",
                                  _("The ID is already used by another role"))

        self._role["alias"] = alias

        # based on
        if not self._role.get("builtin"):
            basedon = request.get_ascii_input_mandatory("basedon")
            if basedon not in builtin_role_ids:
                raise MKUserError(
                    "basedon",
                    _("Invalid valid for based on. Must be id of builtin rule."
                      ))
            self._role["basedon"] = basedon

        # Permissions
        permissions = self._role["permissions"]
        for var_name, value in request.itervars(prefix="perm_"):
            try:
                perm = permission_registry[var_name[5:]]
            except KeyError:
                continue

            if value == "yes":
                permissions[perm.name] = True
            elif value == "no":
                permissions[perm.name] = False
            elif value == "default":
                try:
                    del permissions[perm.name]
                except KeyError:
                    pass  # Already at defaults

        if self._role_id != new_id:
            self._roles[new_id] = self._role
            del self._roles[self._role_id]
            self._rename_user_role(self._role_id, new_id)

        self._save_roles()
        watolib.add_change("edit-roles",
                           _("Modified user role '%s'") % new_id,
                           sites=get_login_sites())
        return redirect(mode_url("roles"))
Exemple #10
0
    def action(self) -> ActionResult:
        # TODO: remove subclass specific things specifict things (everything with _type == 'user')
        if not transactions.check_transaction():
            return None

        title = request.get_unicode_input_mandatory("title").strip()
        if not title:
            raise MKUserError("title", _("Please specify a title."))

        for this_attr in self._attrs:
            if title == this_attr["title"] and self._name != this_attr["name"]:
                raise MKUserError(
                    "alias",
                    _("This alias is already used by the attribute %s.") %
                    this_attr["name"],
                )

        topic = request.get_unicode_input_mandatory("topic", "").strip()
        help_txt = request.get_unicode_input_mandatory("help", "").strip()
        show_in_table = html.get_checkbox("show_in_table")
        add_custom_macro = html.get_checkbox("add_custom_macro")

        if self._new:
            self._name = request.get_ascii_input_mandatory("name", "").strip()
            if not self._name:
                raise MKUserError(
                    "name", _("Please specify a name for the new attribute."))
            if " " in self._name:
                raise MKUserError(
                    "name",
                    _("Sorry, spaces are not allowed in attribute names."))
            if not re.match("^[-a-z0-9A-Z_]*$", self._name):
                raise MKUserError(
                    "name",
                    _("Invalid attribute name. Only the characters a-z, A-Z, 0-9, _ and - are allowed."
                      ),
                )
            if [a for a in self._attrs if a["name"] == self._name]:
                raise MKUserError(
                    "name",
                    _("Sorry, there is already an attribute with that name."))

            ty = request.get_ascii_input_mandatory("type", "").strip()
            if ty not in [t[0] for t in custom_attr_types()]:
                raise MKUserError("type",
                                  _("The choosen attribute type is invalid."))

            self._attr = {
                "name": self._name,
                "type": ty,
            }
            self._attrs.append(self._attr)

            add_change(
                "edit-%sattr" % self._type,
                _("Create new %s attribute %s") % (self._type, self._name),
            )
        else:
            add_change(
                "edit-%sattr" % self._type,
                _("Modified %s attribute %s") % (self._type, self._name))
        self._attr.update({
            "title": title,
            "topic": topic,
            "help": help_txt,
            "show_in_table": show_in_table,
            "add_custom_macro": add_custom_macro,
        })

        self._add_extra_attrs_from_html_vars()

        save_custom_attrs_to_mk_file(self._all_attrs)
        self._update_config()

        return redirect(mode_url(self._type + "_attrs"))
Exemple #11
0
 def __init__(self):
     super(ABCCrashReportPage, self).__init__()
     self._crash_id = request.get_unicode_input_mandatory("crash_id")
     self._site_id = request.get_unicode_input_mandatory("site")
Exemple #12
0
 def _file_path(self) -> Path:
     file_id = request.get_unicode_input_mandatory(
         "file_id", "%s-%d" % (config.user.id, int(time.time())))
     return self._upload_tmp_path / ("%s.csv" % file_id)