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

Add --silent option #201

Merged
merged 5 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
28 changes: 17 additions & 11 deletions src/sumo/wrapper/_auth_provider.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import platform
from pathlib import Path
import msal
import os
from datetime import datetime, timedelta
Expand Down Expand Up @@ -71,6 +69,18 @@ def get_authorization(self):
pass


class AuthProviderSilent(AuthProvider):
def __init__(self, client_id, authority, resource_id):
super().__init__(resource_id)
cache = get_token_cache(resource_id, ".token")
self._app = msal.PublicClientApplication(
client_id=client_id, authority=authority, token_cache=cache
)
self._resource_id = resource_id

self._scope = scope_for_resource(resource_id)


class AuthProviderAccessToken(AuthProvider):
def __init__(self, access_token):
self._access_token = access_token
Expand Down Expand Up @@ -396,6 +406,11 @@ def get_auth_provider(
if os.path.exists(get_token_path(resource_id, ".sharedkey")):
return AuthProviderSumoToken(resource_id)
# ELSE
auth_silent = AuthProviderSilent(client_id, authority, resource_id)
token = auth_silent.get_token()
if token is not None:
return auth_silent
# ELSE
if interactive:
return AuthProviderInteractive(client_id, authority, resource_id)
# ELSE
Expand All @@ -416,12 +431,3 @@ def get_auth_provider(
]
):
return AuthProviderManaged(resource_id)
# ELSE
lockfile_path = Path.home() / ".config/chromium/SingletonLock"
if Path(lockfile_path).is_symlink() and not str(
Path(lockfile_path).resolve()
).__contains__(platform.node()):
# https://github.com/equinor/sumo-wrapper-python/issues/193
return AuthProviderDeviceCode(client_id, authority, resource_id)
# ELSE
return AuthProviderInteractive(client_id, authority, resource_id)
16 changes: 16 additions & 0 deletions src/sumo/wrapper/_version.py
adnejacobsen marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# file generated by setuptools_scm
# don't change, don't track in version control
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import Tuple, Union
VERSION_TUPLE = Tuple[Union[int, str], ...]
else:
VERSION_TUPLE = object

version: str
__version__: str
__version_tuple__: VERSION_TUPLE
version_tuple: VERSION_TUPLE

__version__ = version = '1.0.10.dev1+gb0c8c00.d20240515'
__version_tuple__ = version_tuple = (1, 0, 10, 'dev1', 'gb0c8c00.d20240515')
47 changes: 38 additions & 9 deletions src/sumo/wrapper/login.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging

import platform
from pathlib import Path
from argparse import ArgumentParser
from sumo.wrapper import SumoClient

Expand Down Expand Up @@ -33,7 +34,7 @@ def get_parser() -> ArgumentParser:
"--interactive",
dest="interactive",
action="store_true",
default=False,
default=True,
adnejacobsen marked this conversation as resolved.
Show resolved Hide resolved
help="Login interactively",
)

Expand All @@ -55,6 +56,15 @@ def get_parser() -> ArgumentParser:
help="Print access token",
)

parser.add_argument(
"-s",
"--silent",
dest="silent",
action="store_true",
default=False,
adnejacobsen marked this conversation as resolved.
Show resolved Hide resolved
help="Attempt acquire token silently",
)

return parser


Expand All @@ -64,20 +74,39 @@ def main():
env = args.env
logger.debug("env is %s", env)

print("Login to Sumo environment: " + env)
if args.silent:
args.interactive = False
adnejacobsen marked this conversation as resolved.
Show resolved Hide resolved
args.devicecode = False
args.print_token = False
else:
print("Login to Sumo environment: " + env)

if args.interactive:
lockfile_path = Path.home() / ".config/chromium/SingletonLock"
if Path(lockfile_path).is_symlink() and not str(
Path(lockfile_path).resolve()
).__contains__(platform.node()):
# https://github.com/equinor/sumo-wrapper-python/issues/193
args.interactive = False
args.devicecode = True

sumo = SumoClient(
args.env, interactive=args.interactive, devicecode=args.devicecode
)
token = sumo.authenticate()

if args.print_token:
print(f"TOKEN: {token}")

if token is not None:
print("Successfully logged in to Sumo environment: " + env)
if args.silent:
if token is None:
return 1
return 0
else:
print("Failed login to Sumo environment: " + env)
if args.print_token:
print(f"TOKEN: {token}")

if token is not None:
print("Successfully logged in to Sumo environment: " + env)
else:
print("Failed login to Sumo environment: " + env)


if __name__ == "__main__":
Expand Down
23 changes: 2 additions & 21 deletions src/sumo/wrapper/sumo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,27 +84,6 @@ def __init__(
access_token=access_token,
devicecode=devicecode,
)
if (
self.auth.get_token() is None
and refresh_token is None
and access_token is None
):
print("\n \033[31m !!! Falling back to device-code login:\033[0m")
self.auth = get_auth_provider(
client_id=APP_REGISTRATION[env]["CLIENT_ID"],
authority=f"{AUTHORITY_HOST_URI}/{TENANT_ID}",
resource_id=APP_REGISTRATION[env]["RESOURCE_ID"],
interactive=False,
refresh_token=None,
access_token=None,
devicecode=True,
)
if self.auth.get_token() is None:
print(
"\n\n \033[31m "
+ "NOTE! Login failed/timed out. Giving up."
+ "\033[0m"
)

if env == "localhost":
self.base_url = "http://localhost:8084/api/v1"
Expand All @@ -114,6 +93,8 @@ def __init__(
return

def authenticate(self):
if self.auth is None:
return None
return self.auth.get_token()

@property
Expand Down
Loading