Hub | Fallback to .env + don't upload keys + update support link (#4756)

* fallback to .env

* dont send keys to hub

* remove keys from upload_config

* display keys hierarchy

* pylint

* fix unittest

* Update session_model.py

* point terminal support to .dev

* rewrite tests
This commit is contained in:
montezdesousa
2023-04-13 13:40:02 +01:00
committed by GitHub
parent 9eb44f45d2
commit f0b5cc0aaa
10 changed files with 49 additions and 47 deletions

View File

@@ -155,7 +155,7 @@ class AccountController(BaseController):
if ns_parser:
i = console.input(
"[bold red]This action is irreversible![/bold red]\n"
"Are you sure you want to permanently delete your keys? (y/n): "
"Are you sure you want to permanently delete your keys from OpenBB hub? (y/n): "
)
console.print("")
if i.lower() in ["y", "yes"]:

View File

@@ -3,6 +3,7 @@ BASE_URL = "https://payments.openbb.dev/"
HUB_URL = "https://my.openbb.dev/"
REGISTER_URL = HUB_URL + "register"
SUPPORT_URL = HUB_URL + "app/terminal/support"
SOURCES_URL = HUB_URL + "app/terminal/data-sources"
KEYS_URL = HUB_URL + "app/terminal/api-keys"
COLORS_URL = HUB_URL + "app/terminal/theme"

View File

@@ -19,14 +19,25 @@ DEFAULT_ORDER = [
]
def read_env() -> Dict[str, Any]:
__env_dict: Dict[str, Optional[str]] = {}
local_order = DEFAULT_ORDER.copy()
def get_reading_order() -> list:
"""Get order of .env files. If we are on frozen app, we reverse the order to
read the SETTINGS_ENV_FILE last.
Returns
-------
list
List of .env files.
"""
local_order = DEFAULT_ORDER.copy()
if getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS"):
local_order.reverse()
return local_order
for env_file in local_order:
def read_env() -> Dict[str, Any]:
__env_dict: Dict[str, Optional[str]] = {}
for env_file in get_reading_order():
if env_file.exists():
__env_dict.update(**dotenv_values(env_file))

View File

@@ -338,7 +338,7 @@ def upload_user_field(
def upload_config(
key: str,
value: str,
type_: Literal["keys", "settings", "terminal_style"],
type_: Literal["settings", "terminal_style"],
auth_header: str,
base_url: str = BASE_URL,
timeout: int = TIMEOUT,
@@ -351,7 +351,7 @@ def upload_config(
The key to patch.
value : str
The value to patch.
type_ : Literal["keys", "settings", "terminal_style"]
type_ : Literal["settings", "terminal_style"]
The type of the patch.
auth_header : str
The authorization header, e.g. "Bearer <token>".
@@ -365,7 +365,7 @@ def upload_config(
Optional[requests.Response]
The response from the patch request.
"""
if type_ not in ["keys", "settings", "terminal_style"]:
if type_ not in ["settings", "terminal_style"]:
console.print("[red]\nInvalid patch type.[/red]")
return None

View File

@@ -4,7 +4,7 @@ from prompt_toolkit import PromptSession
import openbb_terminal.core.session.local_model as Local
from openbb_terminal.core.config.paths import PACKAGE_DIRECTORY
from openbb_terminal.core.session.constants import REGISTER_URL
from openbb_terminal.core.session.constants import REGISTER_URL, SUPPORT_URL
from openbb_terminal.core.session.session_model import (
LoginStatus,
create_session,
@@ -19,7 +19,7 @@ def display_welcome_message():
with open(PACKAGE_DIRECTORY / "core" / "session" / "banner.txt") as f:
console.print(f"[menu]{f.read()}[/menu]\n")
console.print(f"Register : [cmds]{REGISTER_URL}[/cmds]")
console.print("Ask support : [cmds]https://openbb.co/support[/cmds]")
console.print(f"Ask support : [cmds]{SUPPORT_URL}[/cmds]")
console.print(
"[yellow]\nWARNING: This is a pre-release version published for testing.[/yellow]"
"[yellow]\nBeware that your account will be deleted without notice.[/yellow]"

View File

@@ -11,7 +11,6 @@ from openbb_terminal.base_helpers import (
)
from openbb_terminal.core.config.paths import HIST_FILE_PATH, SESSION_FILE_PATH
from openbb_terminal.core.models.user_model import (
CredentialsModel,
ProfileModel,
SourcesModel,
UserModel,
@@ -82,13 +81,13 @@ def login(session: dict) -> LoginStatus:
The session info.
"""
# Create a new user:
# credentials: stored in hub, so we set default here
# credentials: stored in hub, but we fallback to local (.env)
# profile: stored in hub, so we set default here
# preferences: stored locally, so we use the current user preferences
# sources: stored in hub, so we set default here
hub_user = UserModel( # type: ignore
credentials=CredentialsModel(),
credentials=get_current_user().credentials,
profile=ProfileModel(),
preferences=get_current_user().preferences,
sources=SourcesModel(),

View File

@@ -11,13 +11,9 @@ from openbb_terminal import (
keys_model,
keys_view,
)
from openbb_terminal.core.config.paths import (
PACKAGE_ENV_FILE,
REPOSITORY_ENV_FILE,
SETTINGS_ENV_FILE,
)
from openbb_terminal.core.session.constants import KEYS_URL
from openbb_terminal.core.session.current_user import get_current_user, is_local
from openbb_terminal.core.session.env_handler import get_reading_order
from openbb_terminal.custom_prompt_toolkit import NestedCompleter
from openbb_terminal.decorators import log_start_end
from openbb_terminal.helper_funcs import EXPORT_ONLY_RAW_DATA_ALLOWED
@@ -72,15 +68,25 @@ class KeysController(BaseController): # pylint: disable=too-many-public-methods
keys_model.KeyStatus.DEFINED_TEST_INCONCLUSIVE
)
def get_source_hierarchy(self) -> str:
"""Hierarchy is equivalent to reverse order of reading .env files.
Returns
-------
str
Source priority string.
"""
reading_order = get_reading_order()
hierarchy = "\n ".join(list(map(str, reversed(reading_order))))
return hierarchy if is_local() else f"{KEYS_URL}\n {hierarchy}"
def print_help(self, update_status: bool = False, reevaluate: bool = False):
"""Print help"""
self.check_keys_status(reevaluate=reevaluate)
mt = MenuText("keys/")
mt.add_param(
"_source",
f"{SETTINGS_ENV_FILE}\n {PACKAGE_ENV_FILE}\n {REPOSITORY_ENV_FILE}"
if is_local()
else KEYS_URL,
self.get_source_hierarchy(),
)
mt.add_raw("\n")
mt.add_info("_keys_")

View File

@@ -24,14 +24,11 @@ from oandapyV20 import API as oanda_API
from prawcore.exceptions import ResponseException
from tokenterminal import TokenTerminal
from openbb_terminal.core.models.credentials_model import LOCAL_CREDENTIALS
from openbb_terminal.core.session.current_user import (
get_current_user,
is_local,
set_credential,
)
from openbb_terminal.core.session.env_handler import write_to_dotenv
from openbb_terminal.core.session.hub_model import upload_config
from openbb_terminal.cryptocurrency.coinbase_helpers import (
CoinbaseApiException,
CoinbaseProAuth,
@@ -251,7 +248,7 @@ def get_keys(show: bool = False) -> pd.DataFrame:
def handle_credential(name: str, value: str, persist: bool = False):
"""Handle credential
"""Handle credential: set it for current user and optionally write to .env file.
Parameters
----------
@@ -262,20 +259,9 @@ def handle_credential(name: str, value: str, persist: bool = False):
persist: bool, optional
Write to .env file. By default, False.
"""
current_user = get_current_user()
local_user = is_local()
set_credential(name, value)
if local_user and persist:
if persist:
write_to_dotenv("OPENBB_" + name, value)
elif not local_user and name not in LOCAL_CREDENTIALS:
upload_config(
key=name,
value=str(value),
type_="keys",
auth_header=current_user.profile.get_auth_header(),
)
def set_av_key(key: str, persist: bool = False, show_output: bool = False) -> str:

View File

@@ -356,7 +356,6 @@ def test_fetch_user_configs_exception():
@pytest.mark.parametrize(
"key, value, type_, auth_header",
[
("key", "value", "keys", "auth_header"),
("key", "value", "settings", "auth_header"),
],
)
@@ -387,14 +386,14 @@ def test_upload_config_failure():
"openbb_terminal.core.session.hub_model.requests.patch",
return_value=mock_response,
) as requests_patch_mock:
result = hub_model.upload_config("key", "value", "keys", "auth_header")
result = hub_model.upload_config("key", "value", "settings", "auth_header")
assert result.status_code == mock_response.status_code
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_keys.key", "value": "value"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -404,14 +403,14 @@ def test_upload_config_connection_error():
) as requests_patch_mock:
requests_patch_mock.side_effect = requests.exceptions.ConnectionError()
result = hub_model.upload_config("key", "value", "keys", "auth_header")
result = hub_model.upload_config("key", "value", "settings", "auth_header")
assert result is None
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_keys.key", "value": "value"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -421,14 +420,14 @@ def test_upload_config_timeout():
) as requests_patch_mock:
requests_patch_mock.side_effect = requests.exceptions.Timeout()
result = hub_model.upload_config("key", "value", "keys", "auth_header")
result = hub_model.upload_config("key", "value", "settings", "auth_header")
assert result is None
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_keys.key", "value": "value"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT
@@ -438,14 +437,14 @@ def test_upload_config_exception():
) as requests_patch_mock:
requests_patch_mock.side_effect = Exception()
result = hub_model.upload_config("key", "value", "keys", "auth_header")
result = hub_model.upload_config("key", "value", "settings", "auth_header")
assert result is None
requests_patch_mock.assert_called_once()
_, kwargs = requests_patch_mock.call_args
assert kwargs["url"] == hub_model.BASE_URL + "terminal/user"
assert kwargs["headers"] == {"Authorization": "auth_header"}
assert kwargs["json"] == {"key": "features_keys.key", "value": "value"}
assert kwargs["json"] == {"key": "features_settings.key", "value": "value"}
assert kwargs["timeout"] == hub_model.TIMEOUT

View File

@@ -19,7 +19,7 @@
[/menu]
Register : [cmds]https://my.openbb.dev/register[/cmds]
Ask support : [cmds]https://openbb.co/support[/cmds]
Ask support : [cmds]https://my.openbb.dev/app/terminal/support[/cmds]
[yellow]
WARNING: This is a pre-release version published for testing.[/yellow][yellow]
Beware that your account will be deleted without notice.[/yellow]