def test_load_group_information_empty(tmp_path): environ = dict(create_environ(), REQUEST_URI='') with AppContext(DummyApplication(environ, None)), \ RequestContext(htmllib.html(Request(environ))): assert groups.load_contact_group_information() == {} assert gui_groups.load_host_group_information() == {} assert gui_groups.load_service_group_information() == {}
def _show_subfolder_infos(self, subfolder): html.open_div(class_="infos") html.open_div(class_="infos_content") groups = load_contact_group_information() permitted_groups, _folder_contact_groups, _use_for_services = subfolder.groups( ) for num, pg in enumerate(permitted_groups): cgalias = groups.get(pg, {'alias': pg})['alias'] html.icon(_("Contactgroups that have permission on this folder"), "contactgroups") html.write_text(' %s' % cgalias) html.br() if num > 1 and len(permitted_groups) > 4: html.write_text( _('<i>%d more contact groups</i><br>') % (len(permitted_groups) - num - 1)) break num_hosts = subfolder.num_hosts_recursively() if num_hosts == 1: html.write_text(_("1 Host")) elif num_hosts > 0: html.write_text("%d %s" % (num_hosts, _("Hosts"))) else: html.i(_("(no hosts)")) html.close_div() html.close_div()
def list_group(params): """Show all contact groups""" collection = [{ "id": k, "alias": v["alias"] } for k, v in load_contact_group_information().items()] return constructors.serve_json( serialize_group_list('contact_group_config', collection), )
def list_group(params): """Show all contact groups""" user.need_permission("wato.users") collection = [{ "id": k, "alias": v["alias"] } for k, v in load_contact_group_information().items()] return constructors.serve_json( serialize_group_list("contact_group_config", collection), )
def _show_hosts(self): if not self._folder.has_hosts(): return hostnames = sorted(self._folder.hosts().keys(), key=utils.key_num_split) search_text = html.request.var("search") html.div("", id_="row_info") # Show table of hosts in this folder html.begin_form("hosts", method="POST") with table_element("hosts", title=_("Hosts"), searchable=False, omit_empty_columns=True) as table: # Compute colspan for bulk actions colspan = 6 for attr in host_attribute_registry.attributes(): if attr.show_in_table(): colspan += 1 if not self._folder.locked_hosts() and config.user.may( "wato.edit_hosts") and config.user.may("wato.move_hosts"): colspan += 1 if self._folder.is_search_folder(): colspan += 1 contact_group_names = load_contact_group_information() host_errors = self._folder.host_validation_errors() rendered_hosts: List[HostName] = [] # Now loop again over all hosts and display them max_hosts = len(hostnames) for hostname in hostnames: if table.limit_reached: table.limit_hint = max_hosts continue self._show_host_row(rendered_hosts, table, hostname, search_text, colspan, host_errors, contact_group_names) html.hidden_field("selection_id", weblib.selection_id()) html.hidden_fields() html.end_form() selected = config.user.get_rowselection(weblib.selection_id(), 'wato-folder-/' + self._folder.path()) row_count = len(hostnames) row_info = "%d %s" % (row_count, _("host") if row_count == 1 else _("hosts")) html.javascript("cmk.utils.update_row_info(%s);" % json.dumps(row_info)) selection_properties = { "page_id": "wato-folder-%s" % ('/' + self._folder.path()), "selection_id": weblib.selection_id(), "selected_rows": selected, } html.javascript('cmk.selection.init_rowselect(%s);' % (json.dumps(selection_properties)))
def list_group(params): return constructors.serve_json({ 'id': 'folders', 'value': [ constructors.collection_object('contact_group', 'contact_group', group) for group in load_contact_group_information().values() ], 'links': [constructors.link_rel('self', '/collections/contact_group')] })
def _contact_group_choices(self, only_own=False): contact_groups = load_contact_group_information() if only_own: user_groups = userdb.contactgroups_of_user(config.user.id) else: user_groups = [] entries = [(c, g['alias']) for c, g in contact_groups.items() if not only_own or c in user_groups] return sorted(entries, key=lambda x: x[1])
def _create_auth_file(callee, users=None): if users is None: users = userdb.load_users() contactgroups = load_contact_group_information() groups = {} for gid, group in contactgroups.items(): if 'nagvis_maps' in group and group['nagvis_maps']: groups[gid] = group['nagvis_maps'] _create_php_file(callee, users, config.get_role_permissions(), groups)
def __init__(self): super(ModeEditUser, self).__init__() # Load data that is referenced - in order to display dropdown # boxes and to check for validity. self._contact_groups = load_contact_group_information() self._timeperiods = watolib.timeperiods.load_timeperiods() self._roles = userdb.load_roles() if cmk.is_managed_edition(): self._vs_customer = managed.vs_customer()
def contact_group_choices(only_own=False): contact_groups = load_contact_group_information() if only_own: assert user.id is not None user_groups = userdb.contactgroups_of_user(user.id) else: user_groups = [] entries = [(c, g['alias']) for c, g in contact_groups.items() if not only_own or c in user_groups] return entries
def contact_group_choices(only_own: bool = False) -> list[tuple[str, str]]: contact_groups = load_contact_group_information() if only_own: assert user.id is not None user_groups = userdb.contactgroups_of_user(user.id) else: user_groups = [] entries = [(c, g["alias"]) for c, g in contact_groups.items() if not only_own or c in user_groups] return entries
def create_auth_file(callee, users=None): from cmk.gui.watolib.groups import load_contact_group_information import cmk.gui.userdb as userdb # TODO: Cleanup if users is None: users = userdb.load_users() store.mkdir(g_auth_base_dir) contactgroups = load_contact_group_information() groups = {} for gid, group in contactgroups.items(): if 'nagvis_maps' in group and group['nagvis_maps']: groups[gid] = group['nagvis_maps'] create_php_file(callee, users, config.get_role_permissions(), groups)
def __init__(self): super(ModePasswords, self).__init__( mode_type=PasswordStoreModeType(), store=PasswordStore(), ) self._contact_groups = load_contact_group_information()
def test_load_group_information(tmp_path): with open(cmk.utils.paths.check_mk_config_dir + "/wato/groups.mk", "w") as f: f.write("""# encoding: utf-8 if type(define_contactgroups) != dict: define_contactgroups = {} define_contactgroups.update({'all': u'Everything'}) if type(define_hostgroups) != dict: define_hostgroups = {} define_hostgroups.update({'all_hosts': u'All hosts :-)'}) if type(define_servicegroups) != dict: define_servicegroups = {} define_servicegroups.update({'all_services': u'All särvices'}) """) with open(cmk.utils.paths.default_config_dir + "/multisite.d/wato/groups.mk", "w") as f: f.write("""# encoding: utf-8 multisite_hostgroups = { "all_hosts": { "ding": "dong", }, } multisite_servicegroups = { "all_services": { "d1ng": "dong", }, } multisite_contactgroups = { "all": { "d!ng": "dong", }, } """) with application_and_request_context(): assert groups.load_group_information() == { 'contact': { 'all': { 'alias': u'Everything', "d!ng": "dong", } }, 'host': { 'all_hosts': { 'alias': u'All hosts :-)', "ding": "dong", } }, 'service': { 'all_services': { 'alias': u'All s\xe4rvices', "d1ng": "dong", } }, } assert groups.load_contact_group_information() == { 'all': { 'alias': u'Everything', "d!ng": "dong", } } assert gui_groups.load_host_group_information() == { 'all_hosts': { 'alias': u'All hosts :-)', "ding": "dong", } } assert gui_groups.load_service_group_information() == { 'all_services': { 'alias': u'All s\xe4rvices', "d1ng": "dong", } }
def __init__(self): super(ModePredefinedConditions, self).__init__( mode_type=PredefinedConditionModeType(), store=PredefinedConditionStore(), ) self._contact_groups = load_contact_group_information()
def _get_all_contactgroups(self, request): return load_contact_group_information()
def _show_hosts(self): if not self._folder.has_hosts(): return show_checkboxes = html.request.var('show_checkboxes', '0') == '1' hostnames = sorted(self._folder.hosts().keys(), key=utils.key_num_split) search_text = html.request.var("search") # Helper function for showing bulk actions. This is needed at the bottom # of the table of hosts and - if there are more than just a few - also # at the top of the table. search_shown = False # Show table of hosts in this folder html.begin_form("hosts", method="POST") with table_element("hosts", title=_("Hosts"), searchable=False, omit_empty_columns=True) as table: # Remember if that host has a target folder (i.e. was imported with # a folder information but not yet moved to that folder). If at least # one host has a target folder, then we show an additional bulk action. at_least_one_imported = False more_than_ten_items = False for num, hostname in enumerate(hostnames): if search_text and (search_text.lower() not in hostname.lower()): continue host = self._folder.host(hostname) effective = host.effective_attributes() if effective.get("imported_folder"): at_least_one_imported = True if num == 11: more_than_ten_items = True # Compute colspan for bulk actions colspan = 6 for attr in host_attribute_registry.attributes(): if attr.show_in_table(): colspan += 1 if not self._folder.locked_hosts() and config.user.may( "wato.edit_hosts") and config.user.may("wato.move_hosts"): colspan += 1 if show_checkboxes: colspan += 1 if self._folder.is_search_folder(): colspan += 1 # Add the bulk action buttons also to the top of the table when this # list shows more than 10 rows if more_than_ten_items and \ (config.user.may("wato.edit_hosts") or config.user.may("wato.manage_hosts")): self._bulk_actions(table, at_least_one_imported, True, True, colspan, show_checkboxes) search_shown = True contact_group_names = load_contact_group_information() host_errors = self._folder.host_validation_errors() rendered_hosts = [] # Now loop again over all hosts and display them for hostname in hostnames: self._show_host_row(rendered_hosts, table, hostname, search_text, show_checkboxes, colspan, host_errors, contact_group_names) if config.user.may("wato.edit_hosts") or config.user.may( "wato.manage_hosts"): self._bulk_actions(table, at_least_one_imported, False, not search_shown, colspan, show_checkboxes) html.hidden_fields() html.end_form() selected = config.user.get_rowselection( weblib.selection_id(), 'wato-folder-/' + self._folder.path()) row_count = len(rendered_hosts) headinfo = "%d %s" % (row_count, _("host") if row_count == 1 else _("hosts")) html.javascript("cmk.utils.update_header_info(%s);" % json.dumps(headinfo)) if show_checkboxes: selection_properties = { "page_id": "wato-folder-%s" % ('/' + self._folder.path()), "selection_id": weblib.selection_id(), "selected_rows": selected, } html.javascript('cmk.selection.init_rowselect(%s);' % (json.dumps(selection_properties)))
def test_load_group_information_empty(tmp_path, run_as_superuser): with application_and_request_context(), run_as_superuser(): assert groups.load_contact_group_information() == {} assert gui_groups.load_host_group_information() == {} assert gui_groups.load_service_group_information() == {}
def test_load_group_information(tmp_path): with open(cmk.utils.paths.check_mk_config_dir + "/wato/groups.mk", "w") as f: f.write("""# encoding: utf-8 if type(define_contactgroups) != dict: define_contactgroups = {} define_contactgroups.update({'all': u'Everything'}) if type(define_hostgroups) != dict: define_hostgroups = {} define_hostgroups.update({'all_hosts': u'All hosts :-)'}) if type(define_servicegroups) != dict: define_servicegroups = {} define_servicegroups.update({'all_services': u'All särvices'}) """) with open(cmk.utils.paths.default_config_dir + "/multisite.d/wato/groups.mk", "w") as f: f.write("""# encoding: utf-8 multisite_hostgroups = { "all_hosts": { "ding": "dong", }, } multisite_servicegroups = { "all_services": { "d1ng": "dong", }, } multisite_contactgroups = { "all": { "d!ng": "dong", }, } """) environ = dict(create_environ(), REQUEST_URI='') with AppContext(DummyApplication(environ, None)), \ RequestContext(htmllib.html(Request(environ))): assert groups.load_group_information() == { 'contact': { 'all': { 'alias': u'Everything', "d!ng": "dong", } }, 'host': { 'all_hosts': { 'alias': u'All hosts :-)', "ding": "dong", } }, 'service': { 'all_services': { 'alias': u'All s\xe4rvices', "d1ng": "dong", } }, } assert groups.load_contact_group_information() == { 'all': { 'alias': u'Everything', "d!ng": "dong", } } assert gui_groups.load_host_group_information() == { 'all_hosts': { 'alias': u'All hosts :-)', "ding": "dong", } } assert gui_groups.load_service_group_information() == { 'all_services': { 'alias': u'All s\xe4rvices', "d1ng": "dong", } }
def test_load_group_information(tmp_path, run_as_superuser): with open(cmk.utils.paths.check_mk_config_dir + "/wato/groups.mk", "w") as f: f.write("""# encoding: utf-8 define_contactgroups.update({'all': u'Everything'}) define_hostgroups.update({'all_hosts': u'All hosts :-)'}) define_servicegroups.update({'all_services': u'All särvices'}) """) with open( cmk.utils.paths.default_config_dir + "/multisite.d/wato/groups.mk", "w") as f: f.write("""# encoding: utf-8 multisite_hostgroups = { "all_hosts": { "ding": "dong", }, } multisite_servicegroups = { "all_services": { "d1ng": "dong", }, } multisite_contactgroups = { "all": { "d!ng": "dong", }, } """) with application_and_request_context(), run_as_superuser(): assert groups.load_group_information() == { "contact": { "all": { "alias": "Everything", "d!ng": "dong", } }, "host": { "all_hosts": { "alias": "All hosts :-)", "ding": "dong", } }, "service": { "all_services": { "alias": "All s\xe4rvices", "d1ng": "dong", } }, } assert groups.load_contact_group_information() == { "all": { "alias": "Everything", "d!ng": "dong", } } assert gui_groups.load_host_group_information() == { "all_hosts": { "alias": "All hosts :-)", "ding": "dong", } } assert gui_groups.load_service_group_information() == { "all_services": { "alias": "All s\xe4rvices", "d1ng": "dong", } }
def _fetch_contact_group(ident): groups = load_contact_group_information() group = groups[ident].copy() group['id'] = ident return group
def _load_groups(self): return load_contact_group_information()
def _show_user_list(self): visible_custom_attrs = [ (name, attr) for name, attr in userdb.get_user_attributes() if attr.show_in_table() ] users = userdb.load_users() entries = users.items() html.begin_form("bulk_delete_form", method="POST") roles = userdb.load_roles() timeperiods = watolib.timeperiods.load_timeperiods() contact_groups = load_contact_group_information() with table_element("users", None, empty_text=_("No users are defined yet.")) as table: online_threshold = time.time() - config.user_online_maxage for uid, user in sorted(entries, key=lambda x: x[1].get("alias", x[0]).lower()): table.row() # Checkboxes table.cell(html.render_input("_toggle_group", type_="button", class_="checkgroup", onclick="cmk.selection.toggle_all_rows();", value='X'), sortable=False, css="checkbox") if uid != config.user.id: html.checkbox("_c_user_%s" % base64.b64encode(uid.encode("utf-8"))) user_connection_id = userdb.cleanup_connection_id(user.get('connector')) connection = userdb.get_connection(user_connection_id) # Buttons table.cell(_("Actions"), css="buttons") if connection: # only show edit buttons when the connector is available and enabled edit_url = watolib.folder_preserving_link([("mode", "edit_user"), ("edit", uid)]) html.icon_button(edit_url, _("Properties"), "edit") clone_url = watolib.folder_preserving_link([("mode", "edit_user"), ("clone", uid)]) html.icon_button(clone_url, _("Create a copy of this user"), "clone") delete_url = make_action_link([("mode", "users"), ("_delete", uid)]) html.icon_button(delete_url, _("Delete"), "delete") notifications_url = watolib.folder_preserving_link([("mode", "user_notifications"), ("user", uid)]) if watolib.load_configuration_settings().get("enable_rulebased_notifications"): html.icon_button(notifications_url, _("Custom notification table of this user"), "notifications") # ID table.cell(_("ID"), uid) # Online/Offline if config.save_user_access_times: last_seen = user.get('last_seen', 0) if last_seen >= online_threshold: title = _('Online') img_txt = 'online' elif last_seen != 0: title = _('Offline') img_txt = 'offline' elif last_seen == 0: title = _('Never logged in') img_txt = 'inactive' title += ' (%s %s)' % (render.date(last_seen), render.time_of_day(last_seen)) table.cell(_("Act.")) html.icon(title, img_txt) table.cell(_("Last seen")) if last_seen != 0: html.write_text("%s %s" % (render.date(last_seen), render.time_of_day(last_seen))) else: html.write_text(_("Never logged in")) if cmk.is_managed_edition(): table.cell(_("Customer"), managed.get_customer_name(user)) # Connection if connection: table.cell(_("Connection"), '%s (%s)' % (connection.short_title(), user_connection_id)) locked_attributes = userdb.locked_attributes(user_connection_id) else: table.cell(_("Connection"), "%s (%s) (%s)" % (_("UNKNOWN"), user_connection_id, _("disabled")), css="error") locked_attributes = [] # Authentication if "automation_secret" in user: auth_method = _("Automation") elif user.get("password") or 'password' in locked_attributes: auth_method = _("Password") else: auth_method = "<i>%s</i>" % _("none") table.cell(_("Authentication"), auth_method) table.cell(_("State")) if user.get("locked", False): html.icon(_('The login is currently locked'), 'user_locked') if "disable_notifications" in user and isinstance(user["disable_notifications"], bool): disable_notifications_opts = {"disable": user["disable_notifications"]} else: disable_notifications_opts = user.get("disable_notifications", {}) if disable_notifications_opts.get("disable", False): html.icon(_('Notifications are disabled'), 'notif_disabled') # Full name / Alias table.text_cell(_("Alias"), user.get("alias", "")) # Email table.text_cell(_("Email"), user.get("email", "")) # Roles table.cell(_("Roles")) if user.get("roles", []): role_links = [(watolib.folder_preserving_link([("mode", "edit_role"), ("edit", role)]), roles[role].get("alias")) for role in user["roles"]] html.write_html( HTML(", ").join( html.render_a(alias, href=link) for (link, alias) in role_links)) # contact groups table.cell(_("Contact groups")) cgs = user.get("contactgroups", []) if cgs: cg_aliases = [ contact_groups[c]['alias'] if c in contact_groups else c for c in cgs ] cg_urls = [ watolib.folder_preserving_link([("mode", "edit_contact_group"), ("edit", c)]) for c in cgs ] html.write_html( HTML(", ").join( html.render_a(content, href=url) for (content, url) in zip(cg_aliases, cg_urls))) else: html.i(_("none")) #table.cell(_("Sites")) #html.write(vs_authorized_sites().value_to_text(user.get("authorized_sites", # vs_authorized_sites().default_value()))) # notifications if not watolib.load_configuration_settings().get("enable_rulebased_notifications"): table.cell(_("Notifications")) if not cgs: html.i(_("not a contact")) elif not user.get("notifications_enabled", True): html.write_text(_("disabled")) elif user.get("host_notification_options", "") == "" and \ user.get("service_notification_options", "") == "": html.write_text(_("all events disabled")) else: tp = user.get("notification_period", "24X7") if tp not in timeperiods: tp = tp + _(" (invalid)") elif tp not in watolib.timeperiods.builtin_timeperiods(): url = watolib.folder_preserving_link([("mode", "edit_timeperiod"), ("edit", tp)]) tp = html.render_a(timeperiods[tp].get("alias", tp), href=url) else: tp = timeperiods[tp].get("alias", tp) html.write(tp) # the visible custom attributes for name, attr in visible_custom_attrs: vs = attr.valuespec() table.cell(html.attrencode(_u(vs.title()))) html.write(vs.value_to_text(user.get(name, vs.default_value()))) html.button("_bulk_delete_users", _("Bulk Delete"), "submit", style="margin-top:10px") html.hidden_fields() html.end_form() if not load_contact_group_information(): url = "wato.py?mode=contact_groups" html.open_div(class_="info") html.write( _("Note: you haven't defined any contact groups yet. If you <a href='%s'>" "create some contact groups</a> you can assign users to them und thus " "make them monitoring contacts. Only monitoring contacts can receive " "notifications.") % url) html.write(" you can assign users to them und thus " "make them monitoring contacts. Only monitoring contacts can receive " "notifications.") html.close_div()
def list_group(params): """Show all contact groups""" return constructors.serve_json( serialize_group_list('contact_group_config', list(load_contact_group_information().values())),)
def _load_groups(self) -> Dict[GroupName, GroupSpec]: return load_contact_group_information()
def test_load_group_information_empty(tmp_path): assert groups.load_contact_group_information() == {} assert groups.load_host_group_information() == {} assert groups.load_service_group_information() == {}