Coverage for pyquickhelper/loghelper/pwd_helper.py: 72%
32 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1"""
2@file
3@brief Helpers to store and retrieve password.
4"""
5from getpass import getpass
6from os import getenv
9def set_password(system, username, password, lib='keyrings.cryptfile',
10 env='KEYRING_CRYPTFILE_PASSWORD', ask=True):
11 """
12 Stores a password.
13 By default, uses :epkg:`keyring` or
14 :epkg:`keyrings.cryptfile`.
16 :param system: system
17 :param username: username
18 :param password: password
19 :param lib: which lib to use to store the password
20 :param env: see below
21 :param ask: ask for password if missing
23 If `lib == 'keyrings.cryptfile'`, the function used the environment
24 variable *env*, if present, no password is asked.
25 """
26 if lib == 'keyring':
27 from keyring import (
28 set_password as lib_set_password,
29 get_password as lib_get_password)
30 lib_set_password(system, username, password)
31 pwd = lib_get_password(system, username)
32 if pwd != password:
33 raise RuntimeError( # pragma: no cover
34 "Unable to store a password with keyring for '{}', '{}'.".format(
35 system, username))
36 return
37 if lib == 'keyrings.cryptfile':
38 from keyrings.cryptfile.cryptfile import CryptFileKeyring # pylint: disable=E0401
39 kr = CryptFileKeyring()
40 kr.keyring_key = getenv("KEYRING_CRYPTFILE_PASSWORD")
41 if kr.keyring_key is None and ask:
42 kr.keyring_key = getpass()
43 kr.set_password(system, username, password)
44 return
45 raise RuntimeError(
46 f"Unknown library '{lib}'.")
49def get_password(system, username, lib='keyrings.cryptfile',
50 env='KEYRING_CRYPTFILE_PASSWORD', ask=True):
51 """
52 Restores a password.
53 By default, uses :epkg:`keyring`.
55 :param system: system
56 :param username: username
57 :param lib: which lib to use to store the password
58 :param env: see below
59 :param ask: ask for password if missing
60 :return: password
62 If `lib == 'keyrings.cryptfile'`, the function used the environment
63 variable *env*, if present, no password is asked.
64 """
65 if lib == 'keyring':
66 from keyring import get_password as lib_get_password
67 pwd = lib_get_password(system, username)
68 if pwd in (None, '', b''):
69 raise RuntimeError( # pragma: no cover
70 "Unable to restore a password with keyring for '{}', '{}'.".format(
71 system, username))
72 return pwd
73 if lib == 'keyrings.cryptfile':
74 from keyrings.cryptfile.cryptfile import CryptFileKeyring # pylint: disable=E0401
75 kr = CryptFileKeyring()
76 kr.keyring_key = getenv("KEYRING_CRYPTFILE_PASSWORD")
77 if kr.keyring_key is None and ask:
78 kr.keyring_key = getpass()
79 return kr.get_password(system, username)
80 raise RuntimeError(
81 f"Unknown library '{lib}'.")