Skip to content

Commit

Permalink
Remove login command
Browse files Browse the repository at this point in the history
  • Loading branch information
AlanCoding committed Nov 11, 2024
1 parent f10b280 commit 29636e0
Show file tree
Hide file tree
Showing 4 changed files with 1 addition and 127 deletions.
48 changes: 0 additions & 48 deletions awxkit/awxkit/api/pages/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,54 +147,6 @@ def load_authtoken(self, username='', password=''):

load_default_authtoken = load_authtoken

def _request_token(self, auth_urls, username, password, client_id, description, client_secret, scope):
req = collections.namedtuple('req', 'headers')({})
if client_id and client_secret:
HTTPBasicAuth(client_id, client_secret)(req)
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
resp = self.connection.post(
auth_urls["access_token"],
data={"grant_type": "password", "username": username, "password": password, "scope": scope},
headers=req.headers,
)
elif client_id:
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
resp = self.connection.post(
auth_urls["access_token"],
data={"grant_type": "password", "username": username, "password": password, "client_id": client_id, "scope": scope},
headers=req.headers,
)
else:
HTTPBasicAuth(username, password)(req)
resp = self.connection.post(
auth_urls['personal_token'],
json={"description": description, "application": None, "scope": scope},
headers=req.headers,
)
if resp.ok:
result = resp.json()
if client_id:
return result.pop('access_token', None)
else:
return result.pop('token', None)
else:
raise exception_from_status_code(resp.status_code)

def get_oauth2_token(self, username='', password='', client_id=None, description='AWX CLI', client_secret=None, scope='write'):
default_cred = config.credentials.default
username = username or default_cred.username
password = password or default_cred.password
# Try gateway first, fallback to controller
urls: AuthUrls = {"access_token": "/o/token/", "personal_token": f"{config.gateway_base_path}v1/tokens/"}
try:
return self._request_token(urls, username, password, client_id, description, client_secret, scope)
except exc.NotFound:
urls = {
"access_token": f"{config.api_base_path}o/token/",
"personal_token": f"{config.api_base_path}v2/users/{username}/personal_tokens/",
}
return self._request_token(urls, username, password, client_id, description, client_secret, scope)

def load_session(self, username='', password=''):
default_cred = config.credentials.default
self.connection.login(
Expand Down
7 changes: 1 addition & 6 deletions awxkit/awxkit/api/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,12 +277,7 @@ class Resources(object):
def __getattr__(self, resource):
if resource[:3] == '___':
raise AttributeError('No existing resource: {}'.format(resource))
# Currently we don't handle anything under:
# /api/o/
# /api/login/
# /api/logout/
# If/when we do we will probably need to modify this __getattr__ method
# Also, if we add another API version, this would be handled here
# If/when we add another API version, this would be handled here
prefix = 'v2'
resource = '_' + resource
return '{0}{1}'.format(getattr(self, prefix), getattr(self, resource))
Expand Down
38 changes: 0 additions & 38 deletions awxkit/awxkit/cli/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,44 +66,6 @@ def handle(self, client, parser):
raise NotImplementedError()


class Login(CustomCommand):
name = 'login'
help_text = 'authenticate and retrieve an OAuth2 token'

def print_help(self, parser):
add_authentication_arguments(parser, os.environ)
parser.print_help()

def handle(self, client, parser):
auth = parser.add_argument_group('OAuth2.0 Options')
auth.add_argument('--description', help='description of the generated OAuth2.0 token', metavar='TEXT')
auth.add_argument('--conf.client_id', metavar='TEXT')
auth.add_argument('--conf.client_secret', metavar='TEXT')
auth.add_argument('--conf.scope', choices=['read', 'write'], default='write')
if client.help:
self.print_help(parser)
raise SystemExit()
parsed = parser.parse_known_args()[0]
kwargs = {
'client_id': getattr(parsed, 'conf.client_id', None),
'client_secret': getattr(parsed, 'conf.client_secret', None),
'scope': getattr(parsed, 'conf.scope', None),
}
if getattr(parsed, 'description', None):
kwargs['description'] = parsed.description
try:
token = api.Api().get_oauth2_token(**kwargs)
except Exception as e:
self.print_help(parser)
cprint('Error retrieving an OAuth2.0 token ({}).'.format(e.__class__), 'red')
else:
fmt = client.get_config('format')
if fmt == 'human':
print('export CONTROLLER_OAUTH_TOKEN={}'.format(token))
else:
print(to_str(FORMATTERS[fmt]({'token': token}, '.')).strip())


class Config(CustomCommand):
name = 'config'
help_text = 'print current configuration values'
Expand Down
35 changes: 0 additions & 35 deletions awxkit/test/api/pages/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,38 +22,3 @@ def response(mocker):
"access_token": "my_token",
}
return r


@pytest.mark.parametrize(
("auth_creds", "url", "token"),
[
({"client_id": "foo", "client_secret": "bar"}, "/o/token/", "my_token"),
({"client_id": "foo"}, "/o/token/", "my_token"),
({}, "/api/gateway/v1/tokens/", "my_personal_token"),
],
)
def test_get_oauth2_token_from_gateway(mocker: MockerFixture, response: Response, auth_creds, url, token):
post = mocker.patch("requests.Session.post", return_value=response)
base = Base()
ret = base.get_oauth2_token(**auth_creds)
assert post.call_count == 1
assert post.call_args.args[0] == url
assert ret == token


@pytest.mark.parametrize(
("auth_creds", "url", "token"),
[
({"client_id": "foo", "client_secret": "bar"}, "/api/o/token/", "my_token"),
({"client_id": "foo"}, "/api/o/token/", "my_token"),
({}, "/api/v2/users/foo/personal_tokens/", "my_personal_token"),
],
)
def test_get_oauth2_token_from_controller(mocker: MockerFixture, response: Response, auth_creds, url, token):
type(response).ok = mocker.PropertyMock(side_effect=[False, True])
post = mocker.patch("requests.Session.post", return_value=response)
base = Base()
ret = base.get_oauth2_token(**auth_creds)
assert post.call_count == 2
assert post.call_args.args[0] == url
assert ret == token

0 comments on commit 29636e0

Please sign in to comment.