<commit_before>"""
Management of Zabbix users.

:codeauthor: <NAME> <<EMAIL>>


"""


from copy import deepcopy

import salt.utils.json
from salt.exceptions import SaltException


def __virtual__():
    """
    Only make these states available if Zabbix module is available.
    """
    if "zabbix.user_create" in __salt__:
        return True
    return (False, "zabbix module could not be loaded")


def admin_password_present(name, password=None, **kwargs):
    """
    Initial change of Zabbix Admin password to password taken from one of the sources (only the most prioritized one):
        1. 'password' parameter
        2. '_connection_password' parameter
        3. pillar 'zabbix.password' setting

    1) Tries to log in as Admin with password found in state password parameter or _connection_password
       or pillar or default zabbix password in this precise order, if any of them is present.
    2) If one of above passwords matches, it tries to change the password to the most prioritized one.
    3) If not able to connect with any password then it fails.

    :param name: Just a name of state
    :param password: Optional - desired password for Admin to be set
    :param _connection_user: Optional - Ignored in this state (always assumed 'Admin')
    :param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
    :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)

    .. code-block:: yaml

        # password taken from pillar or _connection_password
        zabbix-admin-password:
            zabbix_user.admin_password_present

        # directly set password
        zabbix-admin-password:
            zabbix_user.admin_password_present:
                - password: <PASSWORD>
    """
    dry_run = __opts__["test"]
    default_zabbix_user = "Admin"
    default_zabbix_password = "<PASSWORD>"
    ret = {"name": name, "changes": {}, "result": False, "comment": ""}

    passwords = []
    connection_args = {}
    connection_args["_connection_user"] = default_zabbix_user
    if "_connection_url" in kwargs:
        connection_args["_connection_url"] = kwargs["_connection_url"]

    config_password = __salt__["config.option"]("zabbix.password", None)
    if config_password:
        passwords.append(config_password)
    if "_connection_password" in kwargs:
        passwords.append(kwargs["_connection_password"])
    if password:
        passwords.append(password)

    # get unique list in preserved order and reverse it
    seen = set()
    unique_passwords = [str(x) for x in passwords if x not in seen and not seen.add(x)]
    unique_passwords.reverse()

    if not unique_passwords:
        ret[
            "comment"
        ] = "Could not find any Zabbix Admin password setting! See documentation."
        return ret
    else:
        desired_password = unique_passwords[0]

    unique_passwords.append(default_zabbix_password)

    for pwd in unique_passwords:
        connection_args["_connection_password"] = pwd
        try:
            user_get = __salt__["zabbix.user_get"](
                default_zabbix_user, **connection_args
            )
        except SaltException as err:
            if "Login name or password is incorrect" in str(err):
                user_get = False
            else:
                raise
        if user_get:
            if pwd == desired_password:
                ret["result"] = True
                ret["comment"] = "Admin password is correct."
                return ret
            else:
                break<commit_msg>Zabbix 6.0 changed login error message<commit_after>"""
Management of Zabbix users.

:codeauthor: <NAME> <<EMAIL>>


"""


from copy import deepcopy

import salt.utils.json
from salt.exceptions import SaltException


def __virtual__():
    """
    Only make these states available if Zabbix module is available.
    """
    if "zabbix.user_create" in __salt__:
        return True
    return (False, "zabbix module could not be loaded")


def admin_password_present(name, password=None, **kwargs):
    """
    Initial change of Zabbix Admin password to password taken from one of the sources (only the most prioritized one):
        1. 'password' parameter
        2. '_connection_password' parameter
        3. pillar 'zabbix.password' setting

    1) Tries to log in as Admin with password found in state password parameter or _connection_password
       or pillar or default zabbix password in this precise order, if any of them is present.
    2) If one of above passwords matches, it tries to change the password to the most prioritized one.
    3) If not able to connect with any password then it fails.

    :param name: Just a name of state
    :param password: Optional - desired password for Admin to be set
    :param _connection_user: Optional - Ignored in this state (always assumed 'Admin')
    :param _connection_password: Optional - <PASSWORD> (can also be set in opts or pillar, see module's docstring)
    :param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)

    .. code-block:: yaml

        # password taken from pillar or _connection_password
        zabbix-admin-password:
            <PASSWORD>

        # directly set password
        zabbix-admin-password:
            <PASSWORD>_password_<PASSWORD>:
                - password: <PASSWORD>
    """
    login_error_messages = [
        "Login name or password is incorrect",
        "Incorrect user name or password",
    ]
    dry_run = __opts__["test"]
    default_zabbix_user = "Admin"
    default_zabbix_password = "<PASSWORD>"
    ret = {"name": name, "changes": {}, "result": False, "comment": ""}

    passwords = []
    connection_args = {}
    connection_args["_connection_user"] = default_zabbix_user
    if "_connection_url" in kwargs:
        connection_args["_connection_url"] = kwargs["_connection_url"]

    config_password = __salt__["config.option"]("zabbix.password", None)
    if config_password:
        passwords.append(config_password)
    if "_connection_password" in kwargs:
        passwords.append(kwargs["_connection_password"])
    if password:
        passwords.append(password)

    # get unique list in preserved order and reverse it
    seen = set()
    unique_passwords = [str(x) for x in passwords if x not in seen and not seen.add(x)]
    unique_passwords.reverse()

    if not unique_passwords:
        ret[
            "comment"
        ] = "Could not find any Zabbix Admin password setting! See documentation."
        return ret
    else:
        desired_password = unique_passwords[0]

    unique_passwords.append(default_zabbix_password)

    for pwd in unique_passwords:
        connection_args["_connection_password"] = pwd
        try:
            user_get = __salt__["zabbix.user_get"](
                default_zabbix_user, **connection_args
            )
        except SaltException as err:
            if all([x not in str(err) for x in login_error_messages]):
                raise
            user_get = False
        if user_get:
            if pwd == desired_password:
                ret["result"] = True
                ret["comment"] = "Admin password is correct."
                return ret
            else:
                break
{'fraction_non_alphanumeric': 0.0801578660860098, 'fraction_numerical': 0.002177463255307567, 'mean_word_length': 2.656218905472637, 'pattern_counts': {'":': 8, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '90650', 'n_tokens_mistral': 2046, 'n_tokens_neox': 1984, 'n_words': 702}