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

feat(jans-cli-tui): save client summary #7153

Merged
merged 2 commits into from Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -54,6 +54,14 @@
INTROSPECTION_ALG_PROPERTIES = ('introspectionSignedResponseAlg', 'introspectionEncryptedResponseAlg', 'introspectionEncryptedResponseEnc')
APP = get_app()


def get_scope_by_inum(inum: str) -> dict:
for scope in common_data.scopes:
if scope['inum'] == inum or scope['dn'] == inum:
return scope
return {}


class EditClientDialog(JansGDialog, DialogUtils):
"""The Main Client Dialog that contain every thing related to The Client
"""
Expand Down Expand Up @@ -93,12 +101,6 @@ def __init__(
self.prepare_tabs()
self.create_window()

def get_scope_by_inum(self, inum: str) -> dict:

for scope in common_data.scopes:
if scope['inum'] == inum or scope['dn'] == inum:
return scope
return {}

def save(self) -> None:
"""method to invoked when saving the dialog (Save button is pressed)
Expand Down Expand Up @@ -212,7 +214,7 @@ def create_window(self) -> None:

def fill_client_scopes(self):
for scope_dn in self.data.get('scopes', []):
scope = self.get_scope_by_inum(scope_dn)
scope = get_scope_by_inum(scope_dn)
if scope:
label = scope['id']
if [scope_dn, label] not in self.client_scopes_entries:
Expand All @@ -232,9 +234,6 @@ def prepare_tabs(self) -> None:

schema = self.myparent.cli_object.get_schema_from_reference('', '#/components/schemas/Client')

import json
open("/tmp/cl.json", "w").write(json.dumps(schema, indent=2))

self.tabs = OrderedDict()

self.tf = True
Expand Down
119 changes: 69 additions & 50 deletions jans-cli-tui/cli_tui/plugins/010_auth_server/main.py
Expand Up @@ -23,19 +23,21 @@
from prompt_toolkit.lexers import PygmentsLexer, DynamicLexer
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.application import Application
from prompt_toolkit.formatted_text import HTML

from utils.static import DialogResult, cli_style, common_strings
from utils.background_tasks import retrieve_enabled_scripts
from utils.utils import DialogUtils
from utils.utils import common_data
from utils.multi_lang import _

from wui_components.jans_path_browser import jans_file_browser_dialog, BrowseType
from wui_components.jans_nav_bar import JansNavBar
from wui_components.jans_vetrical_nav import JansVerticalNav
from wui_components.jans_drop_down import DropDownWidget
from wui_components.jans_cli_dialog import JansGDialog
from view_property import ViewProperty
from edit_client_dialog import EditClientDialog
from edit_client_dialog import EditClientDialog, get_scope_by_inum
from edit_scope_dialog import EditScopeDialog
from ssa import SSA
from agama import Agama
Expand Down Expand Up @@ -177,6 +179,21 @@ def oauth_prepare_containers(self) -> None:
DynamicContainer(lambda: self.oauth_data_container['scopes'])
],style='class:outh_containers_scopes')


self.clients_container = JansVerticalNav(
myparent=self.app,
headers=['Client ID', 'Client Name', 'Grant Types', 'Subject Type'],
preferred_size= [0,0,30,0],
on_enter=self.edit_client,
on_display=self.app.data_display_dialog,
on_delete=self.delete_client,
jans_help=HTML(_("Press key <b>s</b> to save client summary")),
custom_key_bindings=[('s', self.save_client_summary)],
headerColor=cli_style.navbar_headcolor,
entriesColor=cli_style.navbar_entriescolor,
)
self.clients_container_buttons = VSplit([])

self.oauth_containers['clients'] = HSplit([
VSplit([
self.app.getTitledText(_("Search"), name='oauth:clients:search', jans_help=_(common_strings.enter_to_search), accept_handler=self.search_clients,style='class:outh_containers_clients.text'),
Expand All @@ -186,7 +203,8 @@ def oauth_prepare_containers(self) -> None:
padding=3,
width=D(),
),
DynamicContainer(lambda: self.oauth_data_container['clients'])
self.clients_container,
DynamicContainer(lambda: self.clients_container_buttons)
],style=cli_style.container)


Expand Down Expand Up @@ -271,9 +289,33 @@ def oauth_nav_selection_changed(

self.oauth_main_area = set_area


def save_client_summary(self, event):

def do_save(path):
try:
with open(path, "w") as w:
client_data = self.clients_container.all_data[self.clients_container.selectes]
for key in client_data:
val = client_data[key]
if key == 'scopes':
val = [get_scope_by_inum(scope).get('id') for scope in val]
val = json.dumps(val)
w.write(f'{key}: {val}\n')

self.app.pbar_text = _("File {} was saved".format(path))
self.app.show_message(_("Info"), _("File {} was successfully saved").format(path), tobefocused=self.clients_container)
except Exception as e:
self.app.show_message(_("Error!"), _("An error ocurred while saving") + ":\n{}".format(str(e)), tobefocused=self.clients_container)

file_browser_dialog = jans_file_browser_dialog(self.app, path=self.app.browse_path, browse_type=BrowseType.save_as, ok_handler=do_save)
self.app.show_jans_dialog(file_browser_dialog)



def oauth_update_clients(
self,
start_index: Optional[int]= 0,
start_index: Optional[int]= 0,
pattern: Optional[str]= '',
) -> None:
"""update the current clients data to server
Expand All @@ -283,6 +325,7 @@ def oauth_update_clients(
pattern (Optional[str], optional):endpoint arguments for the client data. Defaults to ''.
"""


async def coroutine():
endpoint_args ='limit:{},startIndex:{}'.format(self.app.entries_per_page, start_index)
if pattern:
Expand All @@ -302,58 +345,36 @@ async def coroutine():
self.app.show_message(_("Error getting clients"), str(response.text),tobefocused=self.oauth_containers['clients'])
return

data =[]
all_data = result.get('entries', [])
self.clients_container.clear()

for d in result.get('entries', []):
data.append(
[
for d in all_data:
self.clients_container.add_item([
d['inum'],
d.get('clientName', ''),
','.join(d.get('grantTypes', [])),
d.get('subjectType', '')
]
)
])

if data:
clients = VSplit([
Label(text=" ",width=1),
JansVerticalNav(
myparent=self.app,
headers=['Client ID', 'Client Name', 'Grant Types', 'Subject Type'],
preferred_size= [0,0,30,0],
data=data,
on_enter=self.edit_client,
on_display=self.app.data_display_dialog,
on_delete=self.delete_client,
get_help=(self.get_help,'Client'),
selectes=0,
headerColor=cli_style.navbar_headcolor,
entriesColor=cli_style.navbar_entriescolor,
all_data=result['entries']
)
])
buttons = []
if start_index > 0:
handler_partial = partial(self.oauth_update_clients, start_index-self.app.entries_per_page, pattern)
prev_button = Button(_("Prev"), handler=handler_partial)
prev_button.window.jans_help = _("Retreives previous %d entries") % self.app.entries_per_page
buttons.append(prev_button)
if result['start'] + self.app.entries_per_page < result['totalEntriesCount']:
handler_partial = partial(self.oauth_update_clients, start_index+self.app.entries_per_page, pattern)
next_button = Button(_("Next"), handler=handler_partial)
next_button.window.jans_help = _("Retreives next %d entries") % self.app.entries_per_page
buttons.append(next_button)

self.app.layout.focus(clients)
self.oauth_data_container['clients'] = HSplit([
clients,
VSplit(buttons, padding=5, align=HorizontalAlign.CENTER)
])

get_app().invalidate()
self.app.layout.focus(clients) ### it fix focuse on the last item deletion >> try on UMA-res >> edit_client_dialog >> oauth_update_uma_resources
self.clients_container.all_data = all_data

else:
buttons = []
if start_index > 0:
handler_partial = partial(self.oauth_update_clients, start_index-self.app.entries_per_page, pattern)
prev_button = Button(_("Prev"), handler=handler_partial)
prev_button.window.jans_help = _("Retreives previous %d entries") % self.app.entries_per_page
buttons.append(prev_button)
if result['start'] + self.app.entries_per_page < result['totalEntriesCount']:
handler_partial = partial(self.oauth_update_clients, start_index+self.app.entries_per_page, pattern)
next_button = Button(_("Next"), handler=handler_partial)
next_button.window.jans_help = _("Retreives next %d entries") % self.app.entries_per_page
buttons.append(next_button)

self.clients_container_buttons = VSplit(buttons, padding=3, width=D(), align=HorizontalAlign.CENTER)

self.app.layout.focus(self.clients_container)

if not all_data:
self.app.show_message(_("Oops"), _(common_strings.no_matching_result),tobefocused = self.oauth_containers['clients'])

asyncio.ensure_future(coroutine())
Expand Down Expand Up @@ -384,8 +405,6 @@ async def coroutine():
data_display_name.append(d.get('displayName',d.get('baseDn')))
data_base_dn.append(d.get('baseDn'))



for client_num in range(len(client_data)):

for scope_dn_num in range(len(client_data[client_num]['scopes'])):
Expand Down