Skip to content

Commit 1b4b86f

Browse files
committed
CM-22206 Add "auth check" command
1 parent 8937ae8 commit 1b4b86f

File tree

1 file changed

+49
-1
lines changed

1 file changed

+49
-1
lines changed

cli/auth/auth_command.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,25 @@
1+
import json
2+
13
import click
24
import traceback
5+
6+
from requests import HTTPError
7+
38
from cli.auth.auth_manager import AuthManager
9+
from cli.user_settings.credentials_manager import CredentialsManager
410
from cli.exceptions.custom_exceptions import AuthProcessError, CycodeError
511
from cyclient import logger
12+
from cyclient.cycode_token_based_client import CycodeTokenBasedClient
613

714

8-
@click.command()
15+
@click.group(invoke_without_command=True)
916
@click.pass_context
1017
def authenticate(context: click.Context):
1118
""" Authenticates your machine to associate CLI with your cycode account """
19+
if context.invoked_subcommand is not None:
20+
# if it is a subcommand do nothing
21+
return
22+
1223
try:
1324
logger.debug("starting authentication process")
1425
auth_manager = AuthManager()
@@ -18,6 +29,43 @@ def authenticate(context: click.Context):
1829
_handle_exception(context, e)
1930

2031

32+
@authenticate.command(name='check')
33+
@click.option(
34+
'--output',
35+
default='text',
36+
help='Specify the output (text/json), the default is text',
37+
type=click.Choice(['text', 'json'])
38+
)
39+
@click.pass_context
40+
def authorization_check(context: click.Context, output: str):
41+
""" Check your machine associating CLI with your cycode account """
42+
def print_result(*, result: bool) -> None:
43+
# the current impl of printers supports only results of scans
44+
if output == 'text':
45+
secho_args = {
46+
True: {'message': 'You are authorized', 'fg': 'green'},
47+
False: {'message': 'You are not authorized', 'fg': 'red'}
48+
}
49+
50+
return click.secho(**secho_args[result])
51+
52+
return click.echo(json.dumps({'result': result}))
53+
54+
client_id, client_secret = CredentialsManager().get_credentials()
55+
if not client_id or not client_secret:
56+
return print_result(result=False)
57+
58+
try:
59+
# TODO(MarshalX): This property performs HTTP request to refresh the token. This must be the method.
60+
if CycodeTokenBasedClient(client_id, client_secret).api_token:
61+
return print_result(result=True)
62+
except (CycodeError, HTTPError): # TODO(MarshalX): "HTTPError: 401" should be wrapped with our custom exception
63+
if context.obj['verbose']:
64+
click.secho(f'Error: {traceback.format_exc()}', fg='red', nl=False)
65+
66+
return print_result(result=False)
67+
68+
2169
def _handle_exception(context: click.Context, e: Exception):
2270
verbose = context.obj["verbose"]
2371
if verbose:

0 commit comments

Comments
 (0)