Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 9 commits into from
Apr 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion openbb_terminal/account/account_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def call_clear(self, other_args: List[str]):
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"]:
Expand Down
1 change: 1 addition & 0 deletions openbb_terminal/core/session/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

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"
Expand Down
19 changes: 15 additions & 4 deletions openbb_terminal/core/session/env_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,25 @@
]


def read_env() -> Dict[str, Any]:
__env_dict: Dict[str, Optional[str]] = {}
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


def read_env() -> Dict[str, Any]:
__env_dict: Dict[str, Optional[str]] = {}

for env_file in local_order:
for env_file in get_reading_order():
if env_file.exists():
__env_dict.update(**dotenv_values(env_file))

Expand Down
6 changes: 3 additions & 3 deletions openbb_terminal/core/session/hub_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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>".
Expand All @@ -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

Expand Down
4 changes: 2 additions & 2 deletions openbb_terminal/core/session/session_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

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,
Expand All @@ -18,7 +18,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]"
Expand Down
5 changes: 2 additions & 3 deletions openbb_terminal/core/session/session_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
)
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,
Expand Down Expand Up @@ -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(),
Expand Down
22 changes: 14 additions & 8 deletions openbb_terminal/keys_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,9 @@
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
Expand Down Expand Up @@ -72,15 +68,25 @@ def check_keys_status(self, reevaluate: bool = False) -> None:
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_")
Expand Down
18 changes: 2 additions & 16 deletions openbb_terminal/keys_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,11 @@
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,
Expand Down Expand Up @@ -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
----------
Expand All @@ -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:
Expand Down
17 changes: 8 additions & 9 deletions tests/openbb_terminal/session/test_hub_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
],
)
Expand Down Expand Up @@ -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


Expand All @@ -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


Expand All @@ -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


Expand All @@ -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


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]