From 45ff531be3188b7ff5880adae9b25dbe84700596 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Srokosz?= Date: Fri, 29 Oct 2021 12:10:05 +0200 Subject: [PATCH] Fix: incorrect API key validation (#40) --- src/__version__.py | 2 +- src/cli/authenticator.py | 7 ++++--- src/cli/login.py | 12 +++++++----- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/__version__.py b/src/__version__.py index 903a158..a5cfdf5 100644 --- a/src/__version__.py +++ b/src/__version__.py @@ -1 +1 @@ -__version__ = "3.4.0" +__version__ = "3.4.1" diff --git a/src/cli/authenticator.py b/src/cli/authenticator.py index a1df7a7..3b1b11d 100644 --- a/src/cli/authenticator.py +++ b/src/cli/authenticator.py @@ -24,10 +24,11 @@ def __init__(self): self.config = configparser.ConfigParser() self.config.read(['mwdb.cfg', self.CONFIG_PATH]) - def get_authenticated_mwdb(self, api_url=None): + def get_authenticated_mwdb(self, api_url=None, try_login=True): """ Gets pre-authenticated MWDB object based on local configuration :param api_url: Alternative API url provided explicitly by user + :param try_login: Ask for credentials if they're not saved :rtype: MWDB """ api_url = api_url or self.config.get("mwdb", "api_url", fallback=API_URL) @@ -44,8 +45,8 @@ def get_authenticated_mwdb(self, api_url=None): password = keyring.get_password("mwdb", username) api.login(username, password, warn=False) mwdb = MWDB(api=api) - # If not authenticated: ask for credentials - if mwdb.api.api_key is None: + # If credentials are not stored and try_login=True: ask for credentials + if try_login and mwdb.api.api_key is None: mwdb.login(warn=False) return mwdb diff --git a/src/cli/login.py b/src/cli/login.py index 25f5957..a7fe299 100644 --- a/src/cli/login.py +++ b/src/cli/login.py @@ -2,7 +2,7 @@ from . import main from .authenticator import MwdbAuthenticator -from ..exc import InvalidCredentialsError +from ..exc import InvalidCredentialsError, NotAuthenticatedError @main.command("login") @@ -28,11 +28,13 @@ def login_command(ctx, username, password, via_api_key, api_key): authenticator = MwdbAuthenticator() authenticator.store_login(username, password, api_key, api_url) try: + # Try to use credentials mwdb = authenticator.get_authenticated_mwdb(api_url) - # todo: Find more appropriate way to check successful authentication - mwdb.query("", raise_not_found=False) - except InvalidCredentialsError: - click.echo("Error: Login failed - invalid credentials.", err=True) + if api_key: + # Check if API key is correct + mwdb.api.get("auth/validate") + except (InvalidCredentialsError, NotAuthenticatedError) as e: + click.echo("Error: Login failed - {}".format(str(e)), err=True) authenticator.reset_login() ctx.abort()