1"""
2Authentication runner for creating, deleting, and managing eauth tokens.
3
4.. versionadded:: 2016.11.0
5
6"""
7
8
9import os
10
11import salt.auth
12import salt.exceptions
13import salt.netapi
14
15
16def mk_token(**load):
17    r"""
18    Create an eauth token using provided credentials
19
20    Non-root users may specify an expiration date -- if allowed via the
21    :conf_master:`token_expire_user_override` setting -- by passing an
22    additional ``token_expire`` param. This overrides the
23    :conf_master:`token_expire` setting of the same name in the Master config
24    and is how long a token should live in seconds.
25
26    CLI Example:
27
28    .. code-block:: shell
29
30        salt-run auth.mk_token username=saltdev password=saltdev eauth=auto
31
32        # Create a token valid for three years.
33        salt-run auth.mk_token username=saltdev password=saltdev eauth=auto \
34            token_expire=94670856
35
36        # Calculate the number of seconds using expr.
37        salt-run auth.mk_token username=saltdev password=saltdev eauth=auto \
38            token_expire=$(expr \( 365 \* 24 \* 60 \* 60 \) \* 3)
39    """
40    # This will hang if the master daemon is not running.
41    netapi = salt.netapi.NetapiClient(__opts__)
42    if not netapi._is_master_running():
43        raise salt.exceptions.SaltDaemonNotRunning("Salt Master must be running.")
44
45    auth = salt.auth.Resolver(__opts__)
46    return auth.mk_token(load)
47
48
49def del_token(token):
50    """
51    Delete an eauth token by name
52
53    CLI Example:
54
55    .. code-block:: shell
56
57        salt-run auth.del_token 6556760736e4077daa601baec2b67c24
58    """
59    token_path = os.path.join(__opts__["token_dir"], token)
60    if os.path.exists(token_path):
61        return os.remove(token_path) is None
62    return False
63