Skip to content

Commit 01fcd7f

Browse files
authored
Dev api 231108 (#264)
* perf(api): commands add-user * feat(api): add commands cmdb-agent-init
1 parent af254dd commit 01fcd7f

File tree

4 files changed

+57
-164
lines changed

4 files changed

+57
-164
lines changed

cmdb-api/api/commands/click_acl.py

Lines changed: 17 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import click
22
from flask.cli import with_appcontext
33

4+
from api.lib.perm.acl.user import UserCRUD
5+
46

57
@click.command()
68
@with_appcontext
@@ -23,50 +25,18 @@ def init_acl():
2325
role_rebuild.apply_async(args=(role.id, app.id), queue=ACL_QUEUE)
2426

2527

26-
# @click.command()
27-
# @with_appcontext
28-
# def acl_clean():
29-
# from api.models.acl import Resource
30-
# from api.models.acl import Permission
31-
# from api.models.acl import RolePermission
32-
#
33-
# perms = RolePermission.get_by(to_dict=False)
34-
#
35-
# for r in perms:
36-
# perm = Permission.get_by_id(r.perm_id)
37-
# if perm and perm.app_id != r.app_id:
38-
# resource_id = r.resource_id
39-
# resource = Resource.get_by_id(resource_id)
40-
# perm_name = perm.name
41-
# existed = Permission.get_by(resource_type_id=resource.resource_type_id, name=perm_name, first=True,
42-
# to_dict=False)
43-
# if existed is not None:
44-
# other = RolePermission.get_by(rid=r.rid, perm_id=existed.id, resource_id=resource_id)
45-
# if not other:
46-
# r.update(perm_id=existed.id)
47-
# else:
48-
# r.soft_delete()
49-
# else:
50-
# r.soft_delete()
51-
#
52-
#
53-
# @click.command()
54-
# @with_appcontext
55-
# def acl_has_resource_role():
56-
# from api.models.acl import Role
57-
# from api.models.acl import App
58-
# from api.lib.perm.acl.cache import HasResourceRoleCache
59-
# from api.lib.perm.acl.role import RoleCRUD
60-
#
61-
# roles = Role.get_by(to_dict=False)
62-
# apps = App.get_by(to_dict=False)
63-
# for role in roles:
64-
# if role.app_id:
65-
# res = RoleCRUD.recursive_resources(role.id, role.app_id)
66-
# if res.get('resources') or res.get('groups'):
67-
# HasResourceRoleCache.add(role.id, role.app_id)
68-
# else:
69-
# for app in apps:
70-
# res = RoleCRUD.recursive_resources(role.id, app.id)
71-
# if res.get('resources') or res.get('groups'):
72-
# HasResourceRoleCache.add(role.id, app.id)
28+
@click.command()
29+
@with_appcontext
30+
def add_user():
31+
"""
32+
create a user
33+
34+
is_admin: default is False
35+
36+
"""
37+
38+
username = click.prompt('Enter username', confirmation_prompt=False)
39+
password = click.prompt('Enter password', hide_input=True, confirmation_prompt=True)
40+
email = click.prompt('Enter email ', confirmation_prompt=False)
41+
42+
UserCRUD.add(username=username, password=password, email=email)

cmdb-api/api/commands/click_cmdb.py

Lines changed: 40 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@
2929
from api.lib.perm.acl.resource import ResourceCRUD
3030
from api.lib.perm.acl.resource import ResourceTypeCRUD
3131
from api.lib.perm.acl.role import RoleCRUD
32-
from api.lib.perm.acl.user import UserCRUD
3332
from api.lib.secrets.inner import KeyManage
3433
from api.lib.secrets.inner import global_key_threshold
3534
from api.lib.secrets.secrets import InnerKVManger
@@ -128,10 +127,10 @@ def cmdb_init_acl():
128127

129128
# 3. add resource and grant
130129
ci_types = CIType.get_by(to_dict=False)
131-
type_id = ResourceType.get_by(name=ResourceTypeEnum.CI, first=True, to_dict=False).id
130+
resource_type_id = ResourceType.get_by(name=ResourceTypeEnum.CI, first=True, to_dict=False).id
132131
for ci_type in ci_types:
133132
try:
134-
ResourceCRUD.add(ci_type.name, type_id, app_id)
133+
ResourceCRUD.add(ci_type.name, resource_type_id, app_id)
135134
except AbortException:
136135
pass
137136

@@ -141,10 +140,10 @@ def cmdb_init_acl():
141140
[PermEnum.READ])
142141

143142
relation_views = PreferenceRelationView.get_by(to_dict=False)
144-
type_id = ResourceType.get_by(name=ResourceTypeEnum.RELATION_VIEW, first=True, to_dict=False).id
143+
resource_type_id = ResourceType.get_by(name=ResourceTypeEnum.RELATION_VIEW, first=True, to_dict=False).id
145144
for view in relation_views:
146145
try:
147-
ResourceCRUD.add(view.name, type_id, app_id)
146+
ResourceCRUD.add(view.name, resource_type_id, app_id)
148147
except AbortException:
149148
pass
150149

@@ -154,57 +153,6 @@ def cmdb_init_acl():
154153
[PermEnum.READ])
155154

156155

157-
@click.command()
158-
@click.option(
159-
'-u',
160-
'--user',
161-
help='username'
162-
)
163-
@click.option(
164-
'-p',
165-
'--password',
166-
help='password'
167-
)
168-
@click.option(
169-
'-m',
170-
'--mail',
171-
help='mail'
172-
)
173-
@with_appcontext
174-
def add_user(user, password, mail):
175-
"""
176-
create a user
177-
178-
is_admin: default is False
179-
180-
Example: flask add-user -u <username> -p <password> -m <mail>
181-
"""
182-
assert user is not None
183-
assert password is not None
184-
assert mail is not None
185-
UserCRUD.add(username=user, password=password, email=mail)
186-
187-
188-
@click.command()
189-
@click.option(
190-
'-u',
191-
'--user',
192-
help='username'
193-
)
194-
@with_appcontext
195-
def del_user(user):
196-
"""
197-
delete a user
198-
199-
Example: flask del-user -u <username>
200-
"""
201-
assert user is not None
202-
from api.models.acl import User
203-
204-
u = User.get_by(username=user, first=True, to_dict=False)
205-
u and UserCRUD.delete(u.uid)
206-
207-
208156
@click.command()
209157
@with_appcontext
210158
def cmdb_counter():
@@ -474,3 +422,39 @@ def cmdb_password_data_migrate():
474422

475423
if not failed and attr.is_index:
476424
attr.update(is_index=False)
425+
426+
427+
@click.command()
428+
@with_appcontext
429+
def cmdb_agent_init():
430+
"""
431+
Initialize the agent's permissions and obtain the key and secret
432+
"""
433+
434+
from api.models.acl import User
435+
436+
user = User.get_by(username="cmdb_agent", first=True, to_dict=False)
437+
if user is None:
438+
click.echo(
439+
click.style('user cmdb_agent does not exist, please use flask add-user to create it first', fg='red'))
440+
return
441+
442+
# grant
443+
_app = AppCache.get('cmdb') or App.create(name='cmdb')
444+
app_id = _app.id
445+
446+
ci_types = CIType.get_by(to_dict=False)
447+
resource_type_id = ResourceType.get_by(name=ResourceTypeEnum.CI, first=True, to_dict=False).id
448+
for ci_type in ci_types:
449+
try:
450+
ResourceCRUD.add(ci_type.name, resource_type_id, app_id)
451+
except AbortException:
452+
pass
453+
454+
ACLManager().grant_resource_to_role(ci_type.name,
455+
"cmdb_agent",
456+
ResourceTypeEnum.CI,
457+
[PermEnum.READ, PermEnum.UPDATE, PermEnum.ADD, PermEnum.DELETE])
458+
459+
click.echo("Key : {}".format(click.style(user.key, bg='red')))
460+
click.echo("Secret: {}".format(click.style(user.secret, bg='red')))

cmdb-api/api/commands/common.py

Lines changed: 0 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -84,66 +84,6 @@ def clean():
8484
os.remove(full_pathname)
8585

8686

87-
@click.command()
88-
@click.option("--url", default=None, help="Url to test (ex. /static/image.png)")
89-
@click.option(
90-
"--order", default="rule", help="Property on Rule to order by (default: rule)"
91-
)
92-
@with_appcontext
93-
def urls(url, order):
94-
"""Display all of the url matching routes for the project.
95-
96-
Borrowed from Flask-Script, converted to use Click.
97-
"""
98-
rows = []
99-
column_headers = ("Rule", "Endpoint", "Arguments")
100-
101-
if url:
102-
try:
103-
rule, arguments = current_app.url_map.bind("localhost").match(
104-
url, return_rule=True
105-
)
106-
rows.append((rule.rule, rule.endpoint, arguments))
107-
column_length = 3
108-
except (NotFound, MethodNotAllowed) as e:
109-
rows.append(("<{}>".format(e), None, None))
110-
column_length = 1
111-
else:
112-
rules = sorted(
113-
current_app.url_map.iter_rules(), key=lambda rule: getattr(rule, order)
114-
)
115-
for rule in rules:
116-
rows.append((rule.rule, rule.endpoint, None))
117-
column_length = 2
118-
119-
str_template = ""
120-
table_width = 0
121-
122-
if column_length >= 1:
123-
max_rule_length = max(len(r[0]) for r in rows)
124-
max_rule_length = max_rule_length if max_rule_length > 4 else 4
125-
str_template += "{:" + str(max_rule_length) + "}"
126-
table_width += max_rule_length
127-
128-
if column_length >= 2:
129-
max_endpoint_length = max(len(str(r[1])) for r in rows)
130-
max_endpoint_length = max_endpoint_length if max_endpoint_length > 8 else 8
131-
str_template += " {:" + str(max_endpoint_length) + "}"
132-
table_width += 2 + max_endpoint_length
133-
134-
if column_length >= 3:
135-
max_arguments_length = max(len(str(r[2])) for r in rows)
136-
max_arguments_length = max_arguments_length if max_arguments_length > 9 else 9
137-
str_template += " {:" + str(max_arguments_length) + "}"
138-
table_width += 2 + max_arguments_length
139-
140-
click.echo(str_template.format(*column_headers[:column_length]))
141-
click.echo("-" * table_width)
142-
143-
for row in rows:
144-
click.echo(str_template.format(*row[:column_length]))
145-
146-
14787
@click.command()
14888
@with_appcontext
14989
def db_setup():

cmdb-api/api/lib/perm/acl/resource.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,6 @@ def add(cls, name, type_id, app_id, uid=None):
276276

277277
from api.tasks.acl import apply_trigger
278278
triggers = TriggerCRUD.match_triggers(app_id, r.name, r.resource_type_id, uid)
279-
current_app.logger.info(triggers)
280279
for trigger in triggers:
281280
# auto trigger should be no uid
282281
apply_trigger.apply_async(args=(trigger.id,),

0 commit comments

Comments
 (0)