From 4afcc518419c4dac4dabe7179d82d570fe1c2861 Mon Sep 17 00:00:00 2001 From: pycook Date: Thu, 9 Nov 2023 11:32:54 +0800 Subject: [PATCH] Dev api 231108 (#264) * perf(api): commands add-user * feat(api): add commands cmdb-agent-init --- cmdb-api/api/commands/click_acl.py | 64 +++++------------- cmdb-api/api/commands/click_cmdb.py | 96 +++++++++++---------------- cmdb-api/api/commands/common.py | 60 ----------------- cmdb-api/api/lib/perm/acl/resource.py | 1 - 4 files changed, 57 insertions(+), 164 deletions(-) diff --git a/cmdb-api/api/commands/click_acl.py b/cmdb-api/api/commands/click_acl.py index 8034c465..3588d8c5 100644 --- a/cmdb-api/api/commands/click_acl.py +++ b/cmdb-api/api/commands/click_acl.py @@ -1,6 +1,8 @@ import click from flask.cli import with_appcontext +from api.lib.perm.acl.user import UserCRUD + @click.command() @with_appcontext @@ -23,50 +25,18 @@ def init_acl(): role_rebuild.apply_async(args=(role.id, app.id), queue=ACL_QUEUE) -# @click.command() -# @with_appcontext -# def acl_clean(): -# from api.models.acl import Resource -# from api.models.acl import Permission -# from api.models.acl import RolePermission -# -# perms = RolePermission.get_by(to_dict=False) -# -# for r in perms: -# perm = Permission.get_by_id(r.perm_id) -# if perm and perm.app_id != r.app_id: -# resource_id = r.resource_id -# resource = Resource.get_by_id(resource_id) -# perm_name = perm.name -# existed = Permission.get_by(resource_type_id=resource.resource_type_id, name=perm_name, first=True, -# to_dict=False) -# if existed is not None: -# other = RolePermission.get_by(rid=r.rid, perm_id=existed.id, resource_id=resource_id) -# if not other: -# r.update(perm_id=existed.id) -# else: -# r.soft_delete() -# else: -# r.soft_delete() -# -# -# @click.command() -# @with_appcontext -# def acl_has_resource_role(): -# from api.models.acl import Role -# from api.models.acl import App -# from api.lib.perm.acl.cache import HasResourceRoleCache -# from api.lib.perm.acl.role import RoleCRUD -# -# roles = Role.get_by(to_dict=False) -# apps = App.get_by(to_dict=False) -# for role in roles: -# if role.app_id: -# res = RoleCRUD.recursive_resources(role.id, role.app_id) -# if res.get('resources') or res.get('groups'): -# HasResourceRoleCache.add(role.id, role.app_id) -# else: -# for app in apps: -# res = RoleCRUD.recursive_resources(role.id, app.id) -# if res.get('resources') or res.get('groups'): -# HasResourceRoleCache.add(role.id, app.id) +@click.command() +@with_appcontext +def add_user(): + """ + create a user + + is_admin: default is False + + """ + + username = click.prompt('Enter username', confirmation_prompt=False) + password = click.prompt('Enter password', hide_input=True, confirmation_prompt=True) + email = click.prompt('Enter email ', confirmation_prompt=False) + + UserCRUD.add(username=username, password=password, email=email) diff --git a/cmdb-api/api/commands/click_cmdb.py b/cmdb-api/api/commands/click_cmdb.py index c382fb39..0e428045 100644 --- a/cmdb-api/api/commands/click_cmdb.py +++ b/cmdb-api/api/commands/click_cmdb.py @@ -29,7 +29,6 @@ from api.lib.perm.acl.resource import ResourceCRUD from api.lib.perm.acl.resource import ResourceTypeCRUD from api.lib.perm.acl.role import RoleCRUD -from api.lib.perm.acl.user import UserCRUD from api.lib.secrets.inner import KeyManage from api.lib.secrets.inner import global_key_threshold from api.lib.secrets.secrets import InnerKVManger @@ -128,10 +127,10 @@ def cmdb_init_acl(): # 3. add resource and grant ci_types = CIType.get_by(to_dict=False) - type_id = ResourceType.get_by(name=ResourceTypeEnum.CI, first=True, to_dict=False).id + resource_type_id = ResourceType.get_by(name=ResourceTypeEnum.CI, first=True, to_dict=False).id for ci_type in ci_types: try: - ResourceCRUD.add(ci_type.name, type_id, app_id) + ResourceCRUD.add(ci_type.name, resource_type_id, app_id) except AbortException: pass @@ -141,10 +140,10 @@ def cmdb_init_acl(): [PermEnum.READ]) relation_views = PreferenceRelationView.get_by(to_dict=False) - type_id = ResourceType.get_by(name=ResourceTypeEnum.RELATION_VIEW, first=True, to_dict=False).id + resource_type_id = ResourceType.get_by(name=ResourceTypeEnum.RELATION_VIEW, first=True, to_dict=False).id for view in relation_views: try: - ResourceCRUD.add(view.name, type_id, app_id) + ResourceCRUD.add(view.name, resource_type_id, app_id) except AbortException: pass @@ -154,57 +153,6 @@ def cmdb_init_acl(): [PermEnum.READ]) -@click.command() -@click.option( - '-u', - '--user', - help='username' -) -@click.option( - '-p', - '--password', - help='password' -) -@click.option( - '-m', - '--mail', - help='mail' -) -@with_appcontext -def add_user(user, password, mail): - """ - create a user - - is_admin: default is False - - Example: flask add-user -u -p -m - """ - assert user is not None - assert password is not None - assert mail is not None - UserCRUD.add(username=user, password=password, email=mail) - - -@click.command() -@click.option( - '-u', - '--user', - help='username' -) -@with_appcontext -def del_user(user): - """ - delete a user - - Example: flask del-user -u - """ - assert user is not None - from api.models.acl import User - - u = User.get_by(username=user, first=True, to_dict=False) - u and UserCRUD.delete(u.uid) - - @click.command() @with_appcontext def cmdb_counter(): @@ -474,3 +422,39 @@ def cmdb_password_data_migrate(): if not failed and attr.is_index: attr.update(is_index=False) + + +@click.command() +@with_appcontext +def cmdb_agent_init(): + """ + Initialize the agent's permissions and obtain the key and secret + """ + + from api.models.acl import User + + user = User.get_by(username="cmdb_agent", first=True, to_dict=False) + if user is None: + click.echo( + click.style('user cmdb_agent does not exist, please use flask add-user to create it first', fg='red')) + return + + # grant + _app = AppCache.get('cmdb') or App.create(name='cmdb') + app_id = _app.id + + ci_types = CIType.get_by(to_dict=False) + resource_type_id = ResourceType.get_by(name=ResourceTypeEnum.CI, first=True, to_dict=False).id + for ci_type in ci_types: + try: + ResourceCRUD.add(ci_type.name, resource_type_id, app_id) + except AbortException: + pass + + ACLManager().grant_resource_to_role(ci_type.name, + "cmdb_agent", + ResourceTypeEnum.CI, + [PermEnum.READ, PermEnum.UPDATE, PermEnum.ADD, PermEnum.DELETE]) + + click.echo("Key : {}".format(click.style(user.key, bg='red'))) + click.echo("Secret: {}".format(click.style(user.secret, bg='red'))) diff --git a/cmdb-api/api/commands/common.py b/cmdb-api/api/commands/common.py index 1d10f1cf..6313ef61 100644 --- a/cmdb-api/api/commands/common.py +++ b/cmdb-api/api/commands/common.py @@ -84,66 +84,6 @@ def clean(): os.remove(full_pathname) -@click.command() -@click.option("--url", default=None, help="Url to test (ex. /static/image.png)") -@click.option( - "--order", default="rule", help="Property on Rule to order by (default: rule)" -) -@with_appcontext -def urls(url, order): - """Display all of the url matching routes for the project. - - Borrowed from Flask-Script, converted to use Click. - """ - rows = [] - column_headers = ("Rule", "Endpoint", "Arguments") - - if url: - try: - rule, arguments = current_app.url_map.bind("localhost").match( - url, return_rule=True - ) - rows.append((rule.rule, rule.endpoint, arguments)) - column_length = 3 - except (NotFound, MethodNotAllowed) as e: - rows.append(("<{}>".format(e), None, None)) - column_length = 1 - else: - rules = sorted( - current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order) - ) - for rule in rules: - rows.append((rule.rule, rule.endpoint, None)) - column_length = 2 - - str_template = "" - table_width = 0 - - if column_length >= 1: - max_rule_length = max(len(r[0]) for r in rows) - max_rule_length = max_rule_length if max_rule_length > 4 else 4 - str_template += "{:" + str(max_rule_length) + "}" - table_width += max_rule_length - - if column_length >= 2: - max_endpoint_length = max(len(str(r[1])) for r in rows) - max_endpoint_length = max_endpoint_length if max_endpoint_length > 8 else 8 - str_template += " {:" + str(max_endpoint_length) + "}" - table_width += 2 + max_endpoint_length - - if column_length >= 3: - max_arguments_length = max(len(str(r[2])) for r in rows) - max_arguments_length = max_arguments_length if max_arguments_length > 9 else 9 - str_template += " {:" + str(max_arguments_length) + "}" - table_width += 2 + max_arguments_length - - click.echo(str_template.format(*column_headers[:column_length])) - click.echo("-" * table_width) - - for row in rows: - click.echo(str_template.format(*row[:column_length])) - - @click.command() @with_appcontext def db_setup(): diff --git a/cmdb-api/api/lib/perm/acl/resource.py b/cmdb-api/api/lib/perm/acl/resource.py index e5841538..f5128d4d 100644 --- a/cmdb-api/api/lib/perm/acl/resource.py +++ b/cmdb-api/api/lib/perm/acl/resource.py @@ -276,7 +276,6 @@ def add(cls, name, type_id, app_id, uid=None): from api.tasks.acl import apply_trigger triggers = TriggerCRUD.match_triggers(app_id, r.name, r.resource_type_id, uid) - current_app.logger.info(triggers) for trigger in triggers: # auto trigger should be no uid apply_trigger.apply_async(args=(trigger.id,),