import __main__ from secrets import token_urlsafe as _token_urlsafe, token_hex as _token_hex from string import ascii_letters as _ascii_letters from random import choice as _choice from os.path import join as _join, isfile as _isfile, isdir as _isdir from os import makedirs as _makedirs, environ as _environ _HERE = _environ['PWD'] _PASSWORD_DIR = _join(_HERE, 'password') def get_password(username: str, description: str, type: str, hide: bool, server_name: str='none', length: int=20, temporary: bool=True, ) -> str: if hide: return "XXXXX" def gen_password(): return _token_urlsafe(length)[:length] return _set_password(server_name, username, description, gen_password, temporary, type, ) def get_password_alpha_num(server_name, username: str, description: str, length, hide: bool, starts_with_char=False, ): if hide: return "XXXXX" def gen_password(): password = _token_hex() if starts_with_char: password = _choice(_ascii_letters) + password return password[:length] return _set_password(server_name, username, description, gen_password, True, 'cleartext', ) def _set_password(server_name: str, username: str, description: str, gen_password, temporary, type, ) -> str: if type != 'cleartext': raise Exception('only cleartext is supported') if not server_name or not username: return dir_name = _join(_PASSWORD_DIR, server_name, description) if not _isdir(dir_name): _makedirs(dir_name) file_name = _join(dir_name, username) if not _isfile(file_name): password = gen_password() with open(file_name, 'w') as fh: fh.write(password) with open(file_name, 'r') as fh: file_content = fh.read().strip() return file_content def get_zone_name(zones: list, index: str, ): if zones is not None: return zones[int(index)] def get_last_server_name(server_names): if server_names: return server_names[-1]