Skip to content

Commit

Permalink
feat: jans-cli menu for exit, logout and configure
Browse files Browse the repository at this point in the history
  • Loading branch information
devrimyatar committed Nov 14, 2022
1 parent 96fe636 commit 6a04adf
Show file tree
Hide file tree
Showing 6 changed files with 135 additions and 8 deletions.
39 changes: 38 additions & 1 deletion jans-cli-tui/cli_tui/cli/config_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ def get_plugin_name_from_title(title):
parser.add_argument("--patch-remove", help="Key for remove patch operation. For example imgLocation")
parser.add_argument("-no-color", help="Do not colorize json dumps", action='store_true')
parser.add_argument("--log-dir", help="Log directory", default=log_dir)
parser.add_argument("-revoke-session", help="Revokes session", action='store_true')

parser.add_argument("--data", help="Path to json data file")
args = parser.parse_args()
Expand Down Expand Up @@ -424,6 +425,38 @@ def check_connection(self):

return True

def revoke_session(self):
self.cli_logger.debug("Revoking session info")
url = 'https://{}/jans-auth/restv1/revoke'.format(self.idp_host)
print(url,self.client_id, self.client_secret)
print(self.access_token)
try:

response = requests.post(
url=url,
auth=(self.client_id, self.client_secret),
data={"token": self.access_token, 'token_type_hint': 'access_token'},
verify=self.verify_ssl,
cert=self.mtls_client_cert
)
except Exception as e:
self.cli_logger.error(str(e))
if self.wrapped:
return str(e)

raise ValueError(
self.colored_text("Unable to connect jans-auth server:\n {}".format(str(e)), error_color))


self.log_response(response)

if self.wrapped:
return response
else:
print(response.status_code)
print(response.text)



def check_access_token(self):

Expand Down Expand Up @@ -1489,10 +1522,14 @@ def unescaped_split(self, s, delimeter, escape_char='\\'):

def main():


error_log_file = os.path.join(log_dir, 'cli_eorror.log')
cli_object = JCA_CLI(host, client_id, client_secret, access_token, test_client)

if args.revoke_session:
cli_object.revoke_session()
sys.exit()

if not os.path.exists(log_dir):
os.makedirs(log_dir)

Expand Down
5 changes: 3 additions & 2 deletions jans-cli-tui/cli_tui/jans_cli_tui.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,11 @@ def __init__(self):

self.nav_bar = JansNavBar(
self,
entries=[(plugin.pid, plugin.name) for plugin in self._plugins],
entries=[(plugin.pid, plugin.name) for plugin in self._plugins],
selection_changed=self.main_nav_selection_changed,
select=0,
jans_name='main:nav_bar'
jans_name='main:nav_bar',
last_to_right=True,
)
self.center_frame = FloatContainer(content=
Frame(
Expand Down
Empty file.
Empty file.
76 changes: 76 additions & 0 deletions jans-cli-tui/cli_tui/plugins/999_jans/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import os
import sys
import asyncio

from typing import Sequence


from prompt_toolkit.application import Application
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, Float
from prompt_toolkit.layout.dimension import D
from prompt_toolkit.widgets import Button, Label, Frame
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.widgets import Shadow
from prompt_toolkit.layout.controls import FormattedTextControl


from utils.multi_lang import _
from cli import config_cli


class Plugin:
"""This is a general class for plugins
"""
def __init__(
self,
app: Application
) -> None:
"""init for Plugin class "Jans CLI Menu"
Args:
app (_type_): _description_
"""
self.app = app
self.pid = 'jans-menu'
self.name = '[J]ans Cli'

self.menu_container = Frame(
body=HSplit([
Button(text=_("Exit Jans CLI"), handler=self.exit_cli),
Button(text=_("Logout and Exit Jans CLI"), handler=self.logout_exit_cli),
Button(text=_("Configure Jans CLI"), handler=self.configure_cli),
],
width=D()
),
height=D()
)


def process(self) -> None:
pass

def set_center_frame(self) -> None:
"""center frame content
"""

self.app.center_container = self.menu_container


def exit_cli(self) -> None:
"""Exits
"""
self.app.exit(result=False)


def logout_exit_cli(self) -> None:
"""Removes auth token and exits
"""
del config_cli.config['DEFAULT']['access_token_enc']
del config_cli.config['DEFAULT']['user_data']
config_cli.write_config()
self.exit_cli()

def configure_cli(self) -> None:
"""Configures CLI creds
"""
self.app.jans_creds_dialog()
23 changes: 18 additions & 5 deletions jans-cli-tui/cli_tui/wui_components/jans_nav_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ def __init__(
entries: list,
selection_changed: Callable,
select: int= 0,
jans_name: Optional[str] = ''
jans_name: Optional[str] = '',
last_to_right: Optional[bool] = False,
) -> Window:

"""init for JansNavBar
Expand All @@ -36,7 +37,7 @@ def __init__(
selection_changed (_type_): _description_
select (int, optional): _description_. Defaults to 0.
bgcolor (str, optional): _description_. Defaults to '#00ff44'.
last_to_right (bool, optional): move last item to rightmost.
Examples:
self.oauth_navbar = JansNavBar(
self,
Expand All @@ -51,6 +52,7 @@ def __init__(
self.cur_navbar_selection = select
self.selection_changed = selection_changed
self.jans_name = jans_name
self.last_to_right = last_to_right
self.cur_tab = entries[self.cur_navbar_selection][0]
self.create_window()

Expand Down Expand Up @@ -110,11 +112,14 @@ def add_key_binding(
def get_navbar_entries(self)-> AnyFormattedText:
"""Get all selective entries
Returns:
Returns:
merge_formatted_text: Merge (Concatenate) several pieces of formatted text together.
"""

result = []
nitems = len(self.navbar_entries)
total_text_lenght = 0

for i, entry in enumerate(self.navbar_entries):
display_text = entry[1]
re_search = shortcut_re.search(display_text)
Expand All @@ -124,11 +129,19 @@ def get_navbar_entries(self)-> AnyFormattedText:
display_text = display_text[:sc]+ '<style fg="{}">'.format(cli_style.shorcut_color) + shorcut_key + '</style>' +display_text[ec:]
self.add_key_binding(shorcut_key.lower())

total_text_lenght += len(entry[1].replace('[','').replace(']',''))
if i == self.cur_navbar_selection:
result.append(HTML('<style fg="{}" bg="{}">{}</style>'.format(cli_style.sub_navbar_selected_bgcolor, cli_style.sub_navbar_selected_fgcolor, display_text)))
else:
result.append(HTML('<b>{}</b>'.format(display_text)))
result.append(" ")
if self.last_to_right and i+2 == nitems:
screen_width = self.myparent.output.get_size().columns
remaining_space = (screen_width - total_text_lenght - len(self.navbar_entries[-1][1].replace('[','').replace(']','')) - 2)
sep_space = ' ' * remaining_space
else:
sep_space = ' '
total_text_lenght += len(sep_space)
result.append(sep_space)

return merge_formatted_text(result)

Expand Down

0 comments on commit 6a04adf

Please sign in to comment.