Skip to content

Commit

Permalink
fix(login): prevent duplicate api-token names (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
AntoineDao committed Apr 10, 2022
1 parent 359e3f2 commit 69c49a6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
16 changes: 14 additions & 2 deletions pollination_apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,11 @@ def main(ctx: click.Context):
type=click.Choice(['staging', 'production']),
default='production'
)
def login(environment):
@click.option(
'-t', '--token-name', help='the name of the api tokern created for this client',
default='pollination-apps-cli',
)
def login(environment: str, token_name: str):
"""login to pollination"""

ctx = Context.from_file()
Expand All @@ -41,7 +45,15 @@ def login(environment):
client = ctx.client
client.set_host(env.api_host)
client.set_jwt(jwt)
ctx.api_token = client.create_api_token()
user = client.get_account()
if client.api_token_name_exists(name=token_name):

This comment has been minimized.

Copy link
@mostaphaRoudsari

mostaphaRoudsari Apr 11, 2022

Member

Hey @AntoineDao! In this case, can we retrieve the existing token instead of raising an error? That will avoid asking the user to manually delete the token and try to create a new one.

raise click.ClickException(
f'Login Failed -> API Token name {token_name} is already taken. '
'You can either:\n'
f'\t1. delete it from the web application at https://app.pollination.cloud/{user.username}?tab=settings\n'
'\t2. choose a new name by using the --token-name/-t flag'
)
ctx.api_token = client.create_api_token(name=token_name)

This comment has been minimized.

Copy link
@mostaphaRoudsari

mostaphaRoudsari Apr 11, 2022

Member

Also, I feel the check above can be done inside the create_api_token method.

ctx.save()


Expand Down
13 changes: 11 additions & 2 deletions pollination_apps/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import tarfile
import tempfile
from operator import truediv
from pathlib import Path

import pollination_sdk as sdk
Expand Down Expand Up @@ -36,11 +37,19 @@ def set_api_token(self, api_token: str):
def get_account(self) -> sdk.UserPrivate:
return self.auth.get_me()

def create_api_token(self) -> str:
def api_token_name_exists(self, name: str) -> bool:
token_list: sdk.APITokenList = self.api_tokens.list_tokens()
for token in token_list.resources:
token: sdk.APIToken
if token.name == name:
return True
return False

def create_api_token(self, name: str) -> str:
token: sdk.APITokenPrivate = self.api_tokens.create_token(
api_token_create=sdk.APITokenCreate(
token_id='pollination-apps-cli',
name='pollination-apps-cli'
name=name,
)
)
return token.token
Expand Down

0 comments on commit 69c49a6

Please sign in to comment.