codekingpro/portable-devtools
114k
1# ------------------------------------2# Copyright (c) Microsoft Corporation.3# Licensed under the MIT License.4# ------------------------------------5import os6import json7import logging8import ctypes as ct9from .._constants import VSCODE_CREDENTIALS_SECTION10 11try:12 import ctypes.wintypes as wt13except (IOError, ValueError):14 pass15 16_LOGGER = logging.getLogger(__name__)17 18SUPPORTED_CREDKEYS = set(("Type", "TargetName", "Persist", "UserName", "Comment", "CredentialBlob"))19 20_PBYTE = ct.POINTER(ct.c_byte)21 22 23class _CREDENTIAL(ct.Structure):24 _fields_ = [25 ("Flags", wt.DWORD),26 ("Type", wt.DWORD),27 ("TargetName", ct.c_wchar_p),28 ("Comment", ct.c_wchar_p),29 ("LastWritten", wt.FILETIME),30 ("CredentialBlobSize", wt.DWORD),31 ("CredentialBlob", _PBYTE),32 ("Persist", wt.DWORD),33 ("AttributeCount", wt.DWORD),34 ("Attributes", ct.c_void_p),35 ("TargetAlias", ct.c_wchar_p),36 ("UserName", ct.c_wchar_p),37 ]38 39 40_PCREDENTIAL = ct.POINTER(_CREDENTIAL)41 42_advapi = ct.WinDLL("advapi32") # type: ignore43_advapi.CredReadW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.POINTER(_PCREDENTIAL)]44_advapi.CredReadW.restype = wt.BOOL45_advapi.CredFree.argtypes = [_PCREDENTIAL]46 47 48def _read_credential(service_name, account_name):49 target = "{}/{}".format(service_name, account_name)50 cred_ptr = _PCREDENTIAL()51 if _advapi.CredReadW(target, 1, 0, ct.byref(cred_ptr)):52 cred_blob = cred_ptr.contents.CredentialBlob53 cred_blob_size = cred_ptr.contents.CredentialBlobSize54 cred = "".join(map(chr, cred_blob[:cred_blob_size]))55 _advapi.CredFree(cred_ptr)56 return cred57 return None58 59 60def get_user_settings():61 try:62 path = os.path.join(os.environ["APPDATA"], "Code", "User", "settings.json")63 with open(path, encoding="utf-8") as file:64 return json.load(file)65 except Exception as ex: # pylint:disable=broad-except66 _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG))67 return {}68 69 70def get_refresh_token(cloud_name):71 try:72 return _read_credential(VSCODE_CREDENTIALS_SECTION, cloud_name)73 except Exception as ex: # pylint: disable=broad-except74 _LOGGER.debug(75 'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)76 )77 return None78 