Compare commits

..

77 Commits

Author SHA1 Message Date
simontigers
693ae4ff05 fix: deploy init common (#407) 2024-03-01 17:21:32 +08:00
pycook
a1a9d99eb4 release: v2.3.12 2024-03-01 17:04:38 +08:00
dagongren
e045e0fb43 fix(cmdb-ui):to lowercase (#406) 2024-03-01 13:52:30 +08:00
pycook
09376dbd2b feat(api): CIType inheritance (#405) 2024-03-01 13:51:13 +08:00
dagongren
7fda5a1e7b feat(cmdb-ui):ci type inherit (#404) 2024-03-01 13:39:20 +08:00
dagongren
113b84763f feat:ci detail share (#403) 2024-02-27 16:13:28 +08:00
dagongren
190170acad fix(cmdb-ui):triggers webhook headers (#402) 2024-02-26 13:46:40 +08:00
pycook
513d2af4b8 feat(api): Remove many-to-many restrictions (#401) 2024-02-26 10:17:53 +08:00
pycook
4588bd8996 fix(api): db-setup commands (#399)
fix(api): db-setup commands
2024-02-23 11:05:11 +08:00
dagongren
082da5fade fix(cmdb-ui):resource search common attrs (#397) 2024-02-22 16:19:12 +08:00
pycook
013b116eb5 feat(acl): login channel add ssh options (#396) 2024-02-21 18:10:44 +08:00
simontigers
208d29165b fix: grant common perm after create new employee (#394) 2024-02-04 13:48:02 +08:00
dagongren
d510330cde fix(cmdb-ui):fix multiple default value (#395) 2024-02-04 11:49:44 +08:00
wang-liang0615
ea4f0fc2a5 fix(ui):login email-》username (#393) 2024-01-31 15:52:27 +08:00
pycook
9bcdaacdc4 docs: update init sql
docs: update init sql
2024-01-26 13:57:36 +08:00
pycook
5045581ddf feat(api): Auto-increment id can be used as primary key (#391) 2024-01-26 13:12:17 +08:00
simontigers
232913172c fix: change common_setting task queue (#390) 2024-01-25 17:39:52 +08:00
pycook
157e1809ed release: 2.3.11 2024-01-13 15:06:51 +08:00
pycook
ab8ccf7d1b ui: lint 2024-01-12 18:21:47 +08:00
wang-liang0615
ae1f0f6b4f lint regexSelect (#382) 2024-01-12 18:09:03 +08:00
wang-liang0615
ff47e0ade6 feat:citype regex check & pref:edit is_list (#380) 2024-01-12 17:09:44 +08:00
pycook
0dd272fb04 feat(api): password supports regular check 2024-01-12 16:56:10 +08:00
pycook
6bc5c1516d feat(api): Attributes support regular check (#379)
feat(api): Attributes support regular check
2024-01-12 13:05:37 +08:00
wang-liang0615
4a4b9e6ef0 feat(cmdb-ui):preference citype order (#378) 2024-01-12 11:14:53 +08:00
pycook
6e3f9478b3 Dev api 240111 (#377)
* feat(api): My subscription supports CIType sorting

* feat(api): db change
2024-01-11 18:01:37 +08:00
pycook
691051c254 perf(api): /api/v0.1/ci/adc/statistics
perf(api): /api/v0.1/ci/adc/statistics
2024-01-11 10:10:01 +08:00
pycook
8f066e95a6 fix(api): grant by attr (#373) 2024-01-10 16:52:27 +08:00
pycook
75bca39bf6 fix(api): commands add-user 2024-01-10 11:56:39 +08:00
pycook
3360e4d0fe feat(db): set variable sql_mode
feat(db): set variable sql_mode
2024-01-10 10:28:15 +08:00
wang-liang0615
521fcd0ba2 fix(ui):some fix (#370)
* pref(ui):some bugfix & some style

* fix(ui):some fix
2024-01-10 09:46:02 +08:00
wang-liang0615
fc113425cb pref(ui):some bugfix & some style (#369) 2024-01-09 14:48:13 +08:00
pycook
81a76a9632 fix(api): cmdb-init-acl commands (#368) 2024-01-09 10:04:53 +08:00
wang-liang0615
9ec105ca37 fix(ui):logout (#365) 2024-01-04 16:12:20 +08:00
wang-liang0615
1e1c92a3ef refactor(ui):extract pager components (#364) 2024-01-04 13:41:07 +08:00
pycook
0b3cad8215 feat: update docker-compose 2024-01-04 10:26:47 +08:00
pycook
ed41a72900 release: v2.3.10 2024-01-03 19:23:42 +08:00
wang-liang0615
27854d4e0a fix(acl-ui):operation history (#363) 2024-01-03 17:41:42 +08:00
wang-liang0615
0372459f9d fix(ui) (#362) 2024-01-03 17:09:25 +08:00
simontigers
f56378e2b5 fix(api): common edit department return (#359)
fix(api): common edit department return (#359)
2024-01-03 16:42:14 +08:00
wang-liang0615
00b276d5e7 format(ui) (#361) 2024-01-03 16:35:50 +08:00
wang-liang0615
3faefbe8d3 feat(ui):i18n (#360)
* feat(ui):i18n

* i18n

* feat(ui):i18n
2024-01-03 16:03:15 +08:00
simontigers
4261f6fb57 fix(api): common department allow parent (#358)
* fix(api): common department edit method

* fix(api): common department edit method

* fix(api): common department allow parent
2024-01-03 15:19:08 +08:00
wang-liang0615
c98199e98e feat(ui):i18n (#357)
* feat(ui):i18n

* i18n
2024-01-03 14:58:47 +08:00
simontigers
82ea1ddc79 fix(api): common department edit method (#356)
* fix(api): common department edit method

* fix(api): common department edit method
2024-01-03 14:31:54 +08:00
simontigers
995e581315 fix(api): common department edit method (#355) 2024-01-03 14:26:40 +08:00
pycook
ec8f626b8f docs: update install (#354) 2024-01-03 13:58:35 +08:00
wang-liang0615
ec884c92e1 feat(ui):i18n (#352) 2024-01-03 13:29:38 +08:00
simontigers
9ee2776bdd fix(api): common i18n wide (#351)
* fix(api): common_i18n wide

* fix(api): department i18n
2024-01-03 13:26:58 +08:00
simontigers
7186bdac9c fix(api): common_i18n wide (#350) 2024-01-03 12:29:49 +08:00
wang-liang0615
0a9964375a feat(ui):add packages (#349) 2024-01-03 09:42:32 +08:00
wang-liang0615
bff45d00b6 i18n (#348) 2024-01-02 18:04:53 +08:00
wang-liang0615
e429ad59ff feat(ui):i18n (#347)
* feat(acl-ui):i18n

* feat(base-ui):i18n

* feat(cmdb-ui):i18n
2024-01-02 17:53:07 +08:00
pycook
ace160ae19 Dev api 231229 (#345)
* fix(api): predefined value for float

* feat(api): update public clouds config

* feat(api): commands add-user support is_admin
2023-12-29 13:44:23 +08:00
wang-liang0615
7036fe023c style(ui):global.less (#344) 2023-12-28 11:00:00 +08:00
wang-liang0615
341f5dba53 fix(cmdb-ui):model relation table (#343) 2023-12-27 13:24:01 +08:00
wang-liang0615
5883c1616e feat:Batch import and download templates support predefined values (#342) 2023-12-27 13:18:05 +08:00
simontigers
bee0a3a3e5 feat(api): common i18n (#340) 2023-12-26 10:06:15 +08:00
pycook
7a79a8bbf7 feat(api): i18n
feat(api): i18n
2023-12-25 21:51:44 +08:00
pycook
100a889cb8 fix(api): CI revoke permission (#337) 2023-12-25 12:15:20 +08:00
kdyq007
b093569453 [更新] 修复 LDAP 登录失败的问题 (#336)
Co-authored-by: sherlock <sherlock@gmail.com>
2023-12-25 09:36:31 +08:00
pycook
3919dfdfbb release: 2.3.9 2023-12-23 12:51:09 +08:00
pycook
ef85ba2542 feat(api): update cmdb-init-acl commands (#335) 2023-12-23 12:44:01 +08:00
pycook
3d5c2ec5bc Merge branch 'master' of github.com:veops/cmdb 2023-12-23 12:31:52 +08:00
pycook
c143d6ae5b fix(api): role grant 2023-12-23 12:30:52 +08:00
simontigers
10b273ee81 feat(api): add update_last_login_by_uid (#333) 2023-12-22 18:43:20 +08:00
wang-liang0615
855cb91b31 feat(cmdb-ui):ci type import&export,pref(cmdb-ui):download ci xlsx name, pref(cmdb-ui):ci detail history merge row method (#331)
* pref(cmdb-ui):download ci xlsx name

* pref(cmdb-ui):ci detail history merge row method

* feat(cmdb-ui):ci type import&export
2023-12-22 15:42:20 +08:00
pycook
ffae57642c fix(api): ci relation search
fix(api): ci relation search
2023-12-22 15:35:02 +08:00
simontigers
9ed1108c20 feat(api): add get_file_binary_str and save (#329) 2023-12-22 15:33:05 +08:00
simontigers
72b2f8b6de fix(api): refresh rid after create and import employee (#328) 2023-12-22 15:24:48 +08:00
pycook
20f3e917fe pref(api): import and export of CIType templates
pref(api): import and export of CIType templates
2023-12-22 14:32:03 +08:00
pycook
c430515377 fix(api): add CI (#326) 2023-12-22 11:19:16 +08:00
simontigers
a6e2aca281 fix(api): svg upload (#321) 2023-12-21 18:58:35 +08:00
wang-liang0615
18313b7bd1 fix(acl_ui):permission (#325) 2023-12-21 17:22:49 +08:00
wang-liang0615
dbc44a8ad6 fix(ui):common double menu (#324) 2023-12-21 14:59:39 +08:00
wang-liang0615
f143e30cf5 feat(ui):批量导入模型根据create权限过滤&&模型配置页面权限 (#323) 2023-12-21 14:23:38 +08:00
wang-liang0615
4beece5a6e fix:open triggerForm from attributeCard (#322) 2023-12-21 14:18:00 +08:00
pycook
920295d955 feat: Fixed db volume name 2023-12-21 10:26:51 +08:00
257 changed files with 26504 additions and 22860 deletions

3
.gitignore vendored
View File

@@ -43,7 +43,8 @@ cmdb-api/api/uploaded_files
cmdb-api/migrations/versions
# Translations
*.mo
#*.mo
messages.pot
# Mr Developer
.mr.developer.cfg

View File

@@ -5,8 +5,8 @@ name = "pypi"
[packages]
# Flask
Flask = "==2.3.2"
Werkzeug = ">=2.3.6"
Flask = "==2.2.5"
Werkzeug = "==2.2.3"
click = ">=5.0"
# Api
Flask-RESTful = "==0.3.10"
@@ -27,6 +27,8 @@ Flask-Cors = ">=3.0.8"
ldap3 = "==2.9.1"
pycryptodome = "==3.12.0"
cryptography = ">=41.0.2"
# i18n
flask-babel = "==4.0.0"
# Caching
Flask-Caching = ">=1.0.0"
# Environment variable parsing

View File

@@ -12,12 +12,14 @@ from pathlib import Path
from flask import Flask
from flask import jsonify
from flask import make_response
from flask import request
from flask.blueprints import Blueprint
from flask.cli import click
from flask.json.provider import DefaultJSONProvider
from flask_babel.speaklater import LazyString
import api.views.entry
from api.extensions import (bcrypt, cache, celery, cors, db, es, login_manager, migrate, rd)
from api.extensions import (bcrypt, babel, cache, celery, cors, db, es, login_manager, migrate, rd)
from api.extensions import inner_secrets
from api.lib.perm.authentication.cas import CAS
from api.lib.perm.authentication.oauth2 import OAuth2
@@ -72,7 +74,7 @@ class ReverseProxy(object):
class MyJSONEncoder(DefaultJSONProvider):
def default(self, o):
if isinstance(o, (decimal.Decimal, datetime.date, datetime.time)):
if isinstance(o, (decimal.Decimal, datetime.date, datetime.time, LazyString)):
return str(o)
if isinstance(o, datetime.datetime):
@@ -117,7 +119,13 @@ def configure_upload_dir(app):
def register_extensions(app):
"""Register Flask extensions."""
def get_locale():
accept_languages = app.config.get('ACCEPT_LANGUAGES', ['en', 'zh'])
return request.accept_languages.best_match(accept_languages)
bcrypt.init_app(app)
babel.init_app(app, locale_selector=get_locale)
cache.init_app(app)
db.init_app(app)
cors.init_app(app)

View File

@@ -35,8 +35,22 @@ def add_user():
"""
from api.models.acl import App
from api.lib.perm.acl.cache import AppCache
from api.lib.perm.acl.cache import RoleCache
from api.lib.perm.acl.role import RoleCRUD
from api.lib.perm.acl.role import RoleRelationCRUD
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)
is_admin = click.prompt('Admin (Y/N) ', confirmation_prompt=False, type=bool, default=False)
UserCRUD.add(username=username, password=password, email=email)
if is_admin:
app = AppCache.get('acl') or App.create(name='acl')
acl_admin = RoleCache.get_by_name(app.id, 'acl_admin') or RoleCRUD.add_role('acl_admin', app.id, True)
rid = RoleCache.get_by_name(None, username).id
RoleRelationCRUD.add(acl_admin, acl_admin.id, [rid], app.id)

View File

@@ -5,6 +5,7 @@ import copy
import datetime
import json
import time
import uuid
import click
import requests
@@ -114,10 +115,20 @@ def cmdb_init_acl():
_app = AppCache.get('cmdb') or App.create(name='cmdb')
app_id = _app.id
current_app.test_request_context().push()
# 1. add resource type
for resource_type in ResourceTypeEnum.all():
try:
ResourceTypeCRUD.add(app_id, resource_type, '', PermEnum.all())
perms = PermEnum.all()
if resource_type in (ResourceTypeEnum.CI_FILTER, ResourceTypeEnum.PAGE):
perms = [PermEnum.READ]
elif resource_type == ResourceTypeEnum.CI_TYPE_RELATION:
perms = [PermEnum.ADD, PermEnum.DELETE, PermEnum.GRANT]
elif resource_type == ResourceTypeEnum.RELATION_VIEW:
perms = [PermEnum.READ, PermEnum.UPDATE, PermEnum.DELETE, PermEnum.GRANT]
ResourceTypeCRUD.add(app_id, resource_type, '', perms)
except AbortException:
pass
@@ -168,12 +179,27 @@ def cmdb_counter():
from api.lib.cmdb.cache import CMDBCounterCache
current_app.test_request_context().push()
if not UserCache.get('worker'):
from api.lib.perm.acl.user import UserCRUD
UserCRUD.add(username='worker', password=uuid.uuid4().hex, email='worker@xxx.com')
login_user(UserCache.get('worker'))
i = 0
while True:
try:
db.session.remove()
CMDBCounterCache.reset()
if i % 5 == 0:
CMDBCounterCache.flush_adc_counter()
i = 0
CMDBCounterCache.flush_sub_counter()
i += 1
except:
import traceback
print(traceback.format_exc())

View File

@@ -4,7 +4,7 @@ from flask.cli import with_appcontext
from werkzeug.datastructures import MultiDict
from api.lib.common_setting.acl import ACLManager
from api.lib.common_setting.employee import EmployeeAddForm
from api.lib.common_setting.employee import EmployeeAddForm, GrantEmployeeACLPerm
from api.lib.common_setting.resp_format import ErrFormat
from api.models.common_setting import Employee, Department
@@ -158,50 +158,11 @@ class InitDepartment(object):
def init_backend_resource(self):
acl = self.check_app('backend')
resources_types = acl.get_all_resources_types()
perms = ['read', 'grant', 'delete', 'update']
acl_rid = self.get_admin_user_rid()
results = list(filter(lambda t: t['name'] == '操作权限', resources_types['groups']))
if len(results) == 0:
payload = dict(
app_id=acl.app_name,
name='操作权限',
description='',
perms=perms
)
resource_type = acl.create_resources_type(payload)
else:
resource_type = results[0]
resource_type_id = resource_type['id']
existed_perms = resources_types.get('id2perms', {}).get(resource_type_id, [])
existed_perms = [p['name'] for p in existed_perms]
new_perms = []
for perm in perms:
if perm not in existed_perms:
new_perms.append(perm)
if len(new_perms) > 0:
resource_type['perms'] = existed_perms + new_perms
acl.update_resources_type(resource_type_id, resource_type)
resource_list = acl.get_resource_by_type(None, None, resource_type['id'])
for name in ['公司信息', '公司架构', '通知设置']:
target = list(filter(lambda r: r['name'] == name, resource_list))
if len(target) == 0:
payload = dict(
type_id=resource_type['id'],
app_id=acl.app_name,
name=name,
)
resource = acl.create_resource(payload)
else:
resource = target[0]
if acl_rid > 0:
acl.grant_resource(acl_rid, resource['id'], perms)
if acl_rid == 0:
return
GrantEmployeeACLPerm(acl).grant_by_rid(acl_rid, True)
@staticmethod
def check_app(app_name):

View File

@@ -5,9 +5,7 @@ from glob import glob
from subprocess import call
import click
from flask import current_app
from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
from api.extensions import db
@@ -90,3 +88,53 @@ def db_setup():
"""create tables
"""
db.create_all()
try:
db.session.execute("set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,"
"ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'")
db.session.commit()
except:
pass
try:
db.session.execute("set global tidb_enable_noop_functions='ON'")
db.session.commit()
except:
pass
@click.group()
def translate():
"""Translation and localization commands."""
@translate.command()
@click.argument('lang')
def init(lang):
"""Initialize a new language."""
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('extract command failed')
if os.system(
'pybabel init -i messages.pot -d api/translations -l ' + lang):
raise RuntimeError('init command failed')
os.remove('messages.pot')
@translate.command()
def update():
"""Update all languages."""
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('extract command failed')
if os.system('pybabel update -i messages.pot -d api/translations'):
raise RuntimeError('update command failed')
os.remove('messages.pot')
@translate.command()
def compile():
"""Compile all languages."""
if os.system('pybabel compile -d api/translations'):
raise RuntimeError('compile command failed')

View File

@@ -2,6 +2,7 @@
from celery import Celery
from flask_babel import Babel
from flask_bcrypt import Bcrypt
from flask_caching import Cache
from flask_cors import CORS
@@ -14,6 +15,7 @@ from api.lib.utils import ESHandler
from api.lib.utils import RedisHandler
bcrypt = Bcrypt()
babel = Babel()
login_manager = LoginManager()
db = SQLAlchemy(session_options={"autoflush": False})
migrate = Migrate()

View File

@@ -189,7 +189,8 @@ class AttributeManager(object):
return attr
def get_attribute(self, key, choice_web_hook_parse=True, choice_other_parse=True):
attr = AttributeCache.get(key).to_dict()
attr = AttributeCache.get(key) or dict()
attr = attr and attr.to_dict()
if attr.get("is_choice"):
attr["choice_value"] = self.get_choice_values(
attr["id"],

View File

@@ -330,8 +330,8 @@ class AutoDiscoveryCICRUD(DBMixin):
@staticmethod
def get_attributes_by_type_id(type_id):
from api.lib.cmdb.cache import CITypeAttributesCache
attributes = [i[1] for i in CITypeAttributesCache.get2(type_id) or []]
from api.lib.cmdb.ci_type import CITypeAttributeManager
attributes = [i[1] for i in CITypeAttributeManager.get_all_attributes(type_id) or []]
attr_names = set()
adts = AutoDiscoveryCITypeCRUD.get_by_type_id(type_id)

File diff suppressed because it is too large Load Diff

View File

@@ -1,427 +1,344 @@
[
{
"name": "amiLaunchIndex",
"type": "整数",
"desc": "The AMI launch index, which can be used to find this instance in the launch group.",
"example": "0"
},
{
"name": "architecture",
"type": "文本",
"desc": "The architecture of the image.",
"example": "x86_64"
},
{
"name": "blockDeviceMapping",
"type": "json",
"desc": "Any block device mapping entries for the instance.",
"example": {
"item": {
"deviceName": "/dev/xvda",
"ebs": {
"volumeId": "vol-1234567890abcdef0",
"status": "attached",
"attachTime": "2015-12-22T10:44:09.000Z",
"deleteOnTermination": "true"
}
}
}
},
{
"name": "bootMode",
"type": "文本",
"desc": "The boot mode that was specified by the AMI. If the value is uefi-preferred, the AMI supports both UEFI and Legacy BIOS. The currentInstanceBootMode parameter is the boot mode that is used to boot the instance at launch or start.",
"example": null
},
{
"name": "capacityReservationId",
"type": "文本",
"desc": "The ID of the Capacity Reservation.",
"example": null
},
{
"name": "capacityReservationSpecification",
"type": "json",
"desc": "Information about the Capacity Reservation targeting option.",
"example": null
},
{
"name": "clientToken",
"type": "文本",
"desc": "The idempotency token you provided when you launched the instance, if applicable.",
"example": "xMcwG14507example"
},
{
"name": "cpuOptions",
"type": "json",
"desc": "The CPU options for the instance.",
"example": {
"coreCount": "1",
"threadsPerCore": "1"
}
},
{
"name": "currentInstanceBootMode",
"type": "文本",
"desc": "The boot mode that is used to boot the instance at launch or start. For more information, see Boot modes in the Amazon EC2 User Guide.",
"example": null
},
{
"name": "dnsName",
"type": "文本",
"desc": "[IPv4 only] The public DNS name assigned to the instance. This name is not available until the instance enters the running state. This name is only available if you've enabled DNS hostnames for your VPC.",
"example": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com"
},
{
"name": "ebsOptimized",
"type": "Boolean",
"desc": "Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance.",
"example": "false"
},
{
"name": "elasticGpuAssociationSet",
"type": "json",
"desc": "The Elastic GPU associated with the instance.",
"example": null
},
{
"name": "elasticInferenceAcceleratorAssociationSet",
"type": "json",
"desc": "The elastic inference accelerator associated with the instance.",
"example": null
},
{
"name": "enaSupport",
"type": "Boolean",
"desc": "Specifies whether enhanced networking with ENA is enabled.",
"example": null
},
{
"name": "enclaveOptions",
"type": "json",
"desc": "Indicates whether the instance is enabled for AWS Nitro Enclaves.",
"example": null
},
{
"name": "groupSet",
"type": "json",
"desc": "The security groups for the instance.",
"example": {
"item": {
"groupId": "sg-e4076980",
"groupName": "SecurityGroup1"
}
}
},
{
"name": "hibernationOptions",
"type": "json",
"desc": "Indicates whether the instance is enabled for hibernation.",
"example": null
},
{
"name": "hypervisor",
"type": "文本",
"desc": "The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors.",
"example": "xen"
},
{
"name": "iamInstanceProfile",
"type": "json",
"desc": "The IAM instance profile associated with the instance, if applicable.",
"example": {
"arn": "arn:aws:iam::123456789012:instance-profile/AdminRole",
"id": "ABCAJEDNCAA64SSD123AB"
}
},
{
"name": "imageId",
"type": "文本",
"desc": "The ID of the AMI used to launch the instance.",
"example": "ami-bff32ccc"
},
{
"name": "instanceId",
"type": "文本",
"desc": "The ID of the instance.",
"example": "i-1234567890abcdef0"
},
{
"name": "instanceLifecycle",
"type": "文本",
"desc": "Indicates whether this is a Spot Instance or a Scheduled Instance.",
"example": null
},
{
"name": "instanceState",
"type": "json",
"desc": "The current state of the instance.",
"example": {
"code": "16",
"name": "running"
}
},
{
"name": "instanceType",
"type": "文本",
"desc": "The instance type.",
"example": "t2.micro"
},
{
"name": "ipAddress",
"type": "文本",
"desc": "The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable.",
"example": "54.194.252.215"
},
{
"name": "ipv6Address",
"type": "文本",
"desc": "The IPv6 address assigned to the instance.",
"example": null
},
{
"name": "kernelId",
"type": "文本",
"desc": "The kernel associated with this instance, if applicable.",
"example": null
},
{
"name": "keyName",
"type": "文本",
"desc": "The name of the key pair, if this instance was launched with an associated key pair.",
"example": "my_keypair"
},
{
"name": "launchTime",
"type": "Time",
"desc": "The time the instance was launched.",
"example": "2018-05-08T16:46:19.000Z"
},
{
"name": "licenseSet",
"type": "json",
"desc": "The license configurations for the instance.",
"example": null
},
{
"name": "maintenanceOptions",
"type": "json",
"desc": "Provides information on the recovery and maintenance options of your instance.",
"example": null
},
{
"name": "metadataOptions",
"type": "json",
"desc": "The metadata options for the instance.",
"example": null
},
{
"name": "monitoring",
"type": "json",
"desc": "The monitoring for the instance.",
"example": {
"state": "disabled"
}
},
{
"name": "networkInterfaceSet",
"type": "json",
"desc": "The network interfaces for the instance.",
"example": {
"item": {
"networkInterfaceId": "eni-551ba033",
"subnetId": "subnet-56f5f633",
"vpcId": "vpc-11112222",
"description": "Primary network interface",
"ownerId": "123456789012",
"status": "in-use",
"macAddress": "02:dd:2c:5e:01:69",
"privateIpAddress": "192.168.1.88",
"privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal",
"sourceDestCheck": "true",
"groupSet": {
"item": {
"groupId": "sg-e4076980",
"groupName": "SecurityGroup1"
}
},
"attachment": {
"attachmentId": "eni-attach-39697adc",
"deviceIndex": "0",
"status": "attached",
"attachTime": "2018-05-08T16:46:19.000Z",
"deleteOnTermination": "true"
},
"association": {
"publicIp": "54.194.252.215",
"publicDnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com",
"ipOwnerId": "amazon"
},
"privateIpAddressesSet": {
"item": {
"privateIpAddress": "192.168.1.88",
"privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal",
"primary": "true",
"association": {
"publicIp": "54.194.252.215",
"publicDnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com",
"ipOwnerId": "amazon"
}
}
},
"ipv6AddressesSet": {
"item": {
"ipv6Address": "2001:db8:1234:1a2b::123"
}
}
}
}
},
{
"name": "outpostArn",
"type": "文本",
"desc": "The Amazon Resource Name (ARN) of the Outpost.",
"example": null
},
{
"name": "placement",
"type": "json",
"desc": "The location where the instance launched, if applicable.",
"example": {
"availabilityZone": "eu-west-1c",
"groupName": null,
"tenancy": "default"
}
},
{
"name": "platform",
"type": "文本",
"desc": "The value is Windows for Windows instances; otherwise blank.",
"example": null
},
{
"name": "platformDetails",
"type": "文本",
"desc": "The platform details value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.",
"example": null
},
{
"name": "privateDnsName",
"type": "文本",
"desc": "[IPv4 only] The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state.",
"example": "ip-192-168-1-88.eu-west-1.compute.internal"
},
{
"name": "privateDnsNameOptions",
"type": "json",
"desc": "The options for the instance hostname.",
"example": null
},
{
"name": "privateIpAddress",
"type": "文本",
"desc": "The private IPv4 address assigned to the instance.",
"example": "192.168.1.88"
},
{
"name": "productCodes",
"type": "json",
"desc": "The product codes attached to this instance, if applicable.",
"example": null
},
{
"name": "ramdiskId",
"type": "文本",
"desc": "The RAM disk associated with this instance, if applicable.",
"example": null
},
{
"name": "reason",
"type": "文本",
"desc": "The reason for the most recent state transition. This might be an empty string.",
"example": null
},
{
"name": "rootDeviceName",
"type": "文本",
"desc": "The device name of the root device volume (for example, /dev/sda1).",
"example": "/dev/xvda"
},
{
"name": "rootDeviceType",
"type": "文本",
"desc": "The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume.",
"example": "ebs"
},
{
"name": "sourceDestCheck",
"type": "Boolean",
"desc": "Indicates whether source/destination checking is enabled.",
"example": "true"
},
{
"name": "spotInstanceRequestId",
"type": "文本",
"desc": "If the request is a Spot Instance request, the ID of the request.",
"example": null
},
{
"name": "sriovNetSupport",
"type": "文本",
"desc": "Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.",
"example": null
},
{
"name": "stateReason",
"type": "json",
"desc": "The reason for the most recent state transition.",
"example": null
},
{
"name": "subnetId",
"type": "文本",
"desc": "The ID of the subnet in which the instance is running.",
"example": "subnet-56f5f633"
},
{
"name": "tagSet",
"type": "json",
"desc": "Any tags assigned to the instance.",
"example": {
"item": {
"key": "Name",
"value": "Server_1"
}
}
},
{
"name": "tpmSupport",
"type": "文本",
"desc": "If the instance is configured for NitroTPM support, the value is v2.0. For more information, see NitroTPM in the Amazon EC2 User Guide.",
"example": null
},
{
"name": "usageOperation",
"type": "文本",
"desc": "The usage operation value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.",
"example": null
},
{
"name": "usageOperationUpdateTime",
"type": "Time",
"desc": "The time that the usage operation was last updated.",
"example": null
},
{
"name": "virtualizationType",
"type": "文本",
"desc": "The virtualization type of the instance.",
"example": "hvm"
},
{
"name": "vpcId",
"type": "文本",
"desc": "The ID of the VPC in which the instance is running.",
"example": "vpc-11112222"
}
[
{
"name": "amiLaunchIndex",
"type": "Integer",
"desc": "The AMI launch index, which can be used to find this instance in the launch group.",
"example": ""
},
{
"name": "architecture",
"type": "String",
"desc": "The architecture of the image.",
"example": "i386"
},
{
"name": "blockDeviceMapping",
"type": "Array of InstanceBlockDeviceMapping objects",
"desc": "Any block device mapping entries for the instance.",
"example": ""
},
{
"name": "bootMode",
"type": "String",
"desc": "The boot mode that was specified by the AMI. If the value is uefi-preferred, the AMI supports both UEFI and Legacy BIOS. The currentInstanceBootMode parameter is the boot mode that is used to boot the instance at launch or start. For more information, see Boot modes in the Amazon EC2 User Guide.",
"example": "legacy-bios"
},
{
"name": "capacityReservationId",
"type": "String",
"desc": "The ID of the Capacity Reservation.",
"example": ""
},
{
"name": "capacityReservationSpecification",
"type": "CapacityReservationSpecificationResponse object",
"desc": "Information about the Capacity Reservation targeting option.",
"example": ""
},
{
"name": "clientToken",
"type": "String",
"desc": "The idempotency token you provided when you launched the instance, if applicable.",
"example": ""
},
{
"name": "cpuOptions",
"type": "CpuOptions object",
"desc": "The CPU options for the instance.",
"example": ""
},
{
"name": "currentInstanceBootMode",
"type": "String",
"desc": "The boot mode that is used to boot the instance at launch or start. For more information, see Boot modes in the Amazon EC2 User Guide.",
"example": "legacy-bios"
},
{
"name": "dnsName",
"type": "String",
"desc": "[IPv4 only] The public DNS name assigned to the instance. This name is not available until the instance enters the running state. This name is only available if you've enabled DNS hostnames for your VPC.",
"example": ""
},
{
"name": "ebsOptimized",
"type": "Boolean",
"desc": "Indicates whether the instance is optimized for Amazon EBS I/O. This optimization provides dedicated throughput to Amazon EBS and an optimized configuration stack to provide optimal I/O performance. This optimization isn't available with all instance types. Additional usage charges apply when using an EBS Optimized instance.",
"example": ""
},
{
"name": "elasticGpuAssociationSet",
"type": "Array of ElasticGpuAssociation objects",
"desc": "The Elastic GPU associated with the instance.",
"example": ""
},
{
"name": "elasticInferenceAcceleratorAssociationSet",
"type": "Array of ElasticInferenceAcceleratorAssociation objects",
"desc": "The elastic inference accelerator associated with the instance.",
"example": ""
},
{
"name": "enaSupport",
"type": "Boolean",
"desc": "Specifies whether enhanced networking with ENA is enabled.",
"example": ""
},
{
"name": "enclaveOptions",
"type": "EnclaveOptions object",
"desc": "Indicates whether the instance is enabled for AWS Nitro Enclaves.",
"example": ""
},
{
"name": "groupSet",
"type": "Array of GroupIdentifier objects",
"desc": "The security groups for the instance.",
"example": ""
},
{
"name": "hibernationOptions",
"type": "HibernationOptions object",
"desc": "Indicates whether the instance is enabled for hibernation.",
"example": ""
},
{
"name": "hypervisor",
"type": "String",
"desc": "The hypervisor type of the instance. The value xen is used for both Xen and Nitro hypervisors.",
"example": "ovm"
},
{
"name": "iamInstanceProfile",
"type": "IamInstanceProfile object",
"desc": "The IAM instance profile associated with the instance, if applicable.",
"example": ""
},
{
"name": "imageId",
"type": "String",
"desc": "The ID of the AMI used to launch the instance.",
"example": ""
},
{
"name": "instanceId",
"type": "String",
"desc": "The ID of the instance.",
"example": ""
},
{
"name": "instanceLifecycle",
"type": "String",
"desc": "Indicates whether this is a Spot Instance or a Scheduled Instance.",
"example": "spot"
},
{
"name": "instanceState",
"type": "InstanceState object",
"desc": "The current state of the instance.",
"example": ""
},
{
"name": "instanceType",
"type": "String",
"desc": "The instance type.",
"example": "a1.medium"
},
{
"name": "ipAddress",
"type": "String",
"desc": "The public IPv4 address, or the Carrier IP address assigned to the instance, if applicable. A Carrier IP address only applies to an instance launched in a subnet associated with a Wavelength Zone.",
"example": "Required: No"
},
{
"name": "ipv6Address",
"type": "String",
"desc": "The IPv6 address assigned to the instance.",
"example": ""
},
{
"name": "kernelId",
"type": "String",
"desc": "The kernel associated with this instance, if applicable.",
"example": ""
},
{
"name": "keyName",
"type": "String",
"desc": "The name of the key pair, if this instance was launched with an associated key pair.",
"example": ""
},
{
"name": "launchTime",
"type": "Timestamp",
"desc": "The time the instance was launched.",
"example": ""
},
{
"name": "licenseSet",
"type": "Array of LicenseConfiguration objects",
"desc": "The license configurations for the instance.",
"example": ""
},
{
"name": "maintenanceOptions",
"type": "InstanceMaintenanceOptions object",
"desc": "Provides information on the recovery and maintenance options of your instance.",
"example": ""
},
{
"name": "metadataOptions",
"type": "InstanceMetadataOptionsResponse object",
"desc": "The metadata options for the instance.",
"example": ""
},
{
"name": "monitoring",
"type": "Monitoring object",
"desc": "The monitoring for the instance.",
"example": ""
},
{
"name": "networkInterfaceSet",
"type": "Array of InstanceNetworkInterface objects",
"desc": "The network interfaces for the instance.",
"example": ""
},
{
"name": "outpostArn",
"type": "String",
"desc": "The Amazon Resource Name (ARN) of the Outpost.",
"example": ""
},
{
"name": "placement",
"type": "Placement object",
"desc": "The location where the instance launched, if applicable.",
"example": ""
},
{
"name": "platform",
"type": "String",
"desc": "The platform. This value is windows for Windows instances; otherwise, it is empty.",
"example": "windows"
},
{
"name": "platformDetails",
"type": "String",
"desc": "The platform details value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.",
"example": ""
},
{
"name": "privateDnsName",
"type": "String",
"desc": "[IPv4 only] The private DNS hostname name assigned to the instance. This DNS hostname can only be used inside the Amazon EC2 network. This name is not available until the instance enters the running state. The Amazon-provided DNS server resolves Amazon-provided private DNS hostnames if you've enabled DNS resolution and DNS hostnames in your VPC. If you are not using the Amazon-provided DNS server in your VPC, your custom domain name servers must resolve the hostname as appropriate.",
"example": "Required: No"
},
{
"name": "privateDnsNameOptions",
"type": "PrivateDnsNameOptionsResponse object",
"desc": "The options for the instance hostname.",
"example": ""
},
{
"name": "privateIpAddress",
"type": "String",
"desc": "The private IPv4 address assigned to the instance.",
"example": ""
},
{
"name": "productCodes",
"type": "Array of ProductCode objects",
"desc": "The product codes attached to this instance, if applicable.",
"example": ""
},
{
"name": "ramdiskId",
"type": "String",
"desc": "The RAM disk associated with this instance, if applicable.",
"example": ""
},
{
"name": "reason",
"type": "String",
"desc": "The reason for the most recent state transition. This might be an empty string.",
"example": ""
},
{
"name": "rootDeviceName",
"type": "String",
"desc": "The device name of the root device volume (for example, /dev/sda1).",
"example": ""
},
{
"name": "rootDeviceType",
"type": "String",
"desc": "The root device type used by the AMI. The AMI can use an EBS volume or an instance store volume.",
"example": "ebs"
},
{
"name": "sourceDestCheck",
"type": "Boolean",
"desc": "Indicates whether source/destination checking is enabled.",
"example": ""
},
{
"name": "spotInstanceRequestId",
"type": "String",
"desc": "If the request is a Spot Instance request, the ID of the request.",
"example": ""
},
{
"name": "sriovNetSupport",
"type": "String",
"desc": "Specifies whether enhanced networking with the Intel 82599 Virtual Function interface is enabled.",
"example": ""
},
{
"name": "stateReason",
"type": "StateReason object",
"desc": "The reason for the most recent state transition.",
"example": ""
},
{
"name": "subnetId",
"type": "String",
"desc": "The ID of the subnet in which the instance is running.",
"example": ""
},
{
"name": "tagSet",
"type": "Array of Tag objects",
"desc": "Any tags assigned to the instance.",
"example": ""
},
{
"name": "tpmSupport",
"type": "String",
"desc": "If the instance is configured for NitroTPM support, the value is v2.0. For more information, see NitroTPM in the Amazon EC2 User Guide.",
"example": ""
},
{
"name": "usageOperation",
"type": "String",
"desc": "The usage operation value for the instance. For more information, see AMI billing information fields in the Amazon EC2 User Guide.",
"example": ""
},
{
"name": "usageOperationUpdateTime",
"type": "Timestamp",
"desc": "The time that the usage operation was last updated.",
"example": ""
},
{
"name": "virtualizationType",
"type": "String",
"desc": "The virtualization type of the instance.",
"example": "hvm"
},
{
"name": "vpcId",
"type": "String",
"desc": "The ID of the VPC in which the instance is running.",
"example": ""
}
]

View File

@@ -1,292 +1,284 @@
[
{
"name": "status",
"type": "文本",
"example": "ACTIVE",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u72b6\u6001\u3002\n\n\u53d6\u503c\u8303\u56f4:\n\nACTIVE\u3001BUILD\u3001DELETED\u3001ERROR\u3001HARD_REBOOT\u3001MIGRATING\u3001PAUSED\u3001REBOOT\u3001REBUILD\u3001RESIZE\u3001REVERT_RESIZE\u3001SHUTOFF\u3001SHELVED\u3001SHELVED_OFFLOADED\u3001SOFT_DELETED\u3001SUSPENDED\u3001VERIFY_RESIZE\n\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u72b6\u6001\u8bf4\u660e\u8bf7\u53c2\u8003[\u4e91\u670d\u52a1\u5668\u72b6\u6001](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)"
},
{
"name": "updated",
"type": "文本",
"example": "2019-05-22T03:30:52Z",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u66f4\u65b0\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:30:52Z"
},
{
"name": "auto_terminate_time",
"type": "文本",
"example": "2020-01-19T03:30:52Z",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u81ea\u52a8\u91ca\u653e\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2020-01-19T03:30:52Z"
},
{
"name": "hostId",
"type": "文本",
"example": "c7145889b2e3202cd295ceddb1742ff8941b827b586861fd0acedf64",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u4e3b\u673a\u7684\u4e3b\u673aID\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:host",
"type": "文本",
"example": "pod01.cn-north-1c",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u4e3b\u673a\u7684\u4e3b\u673a\u540d\u79f0\u3002"
},
{
"name": "addresses",
"type": "json",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u7f51\u7edc\u5c5e\u6027\u3002"
},
{
"name": "key_name",
"type": "文本",
"example": "KeyPair-test",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u4f7f\u7528\u7684\u5bc6\u94a5\u5bf9\u540d\u79f0\u3002"
},
{
"name": "image",
"type": "json",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u955c\u50cf\u4fe1\u606f\u3002"
},
{
"name": "OS-EXT-STS:task_state",
"type": "文本",
"example": "rebooting",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5f53\u524d\u4efb\u52a1\u7684\u72b6\u6001\u3002\n\n\u53d6\u503c\u8303\u56f4\u8bf7\u53c2\u8003[\u4e91\u670d\u52a1\u5668\u72b6\u6001](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)\u88683\u3002"
},
{
"name": "OS-EXT-STS:vm_state",
"type": "文本",
"example": "active",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5f53\u524d\u72b6\u6001\u3002\n\n\u4e91\u670d\u52a1\u5668\u72b6\u6001\u8bf4\u660e\u8bf7\u53c2\u8003[\u4e91\u670d\u52a1\u5668\u72b6\u6001](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:instance_name",
"type": "文本",
"example": "instance-0048a91b",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u522b\u540d\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:hypervisor_hostname",
"type": "文本",
"example": "nova022@36",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u865a\u62df\u5316\u4e3b\u673a\u540d\u3002"
},
{
"name": "flavor",
"type": "json",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u89c4\u683c\u4fe1\u606f\u3002"
},
{
"name": "id",
"type": "文本",
"example": "4f4b3dfa-eb70-47cf-a60a-998a53bd6666",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668ID,\u683c\u5f0f\u4e3aUUID\u3002"
},
{
"name": "security_groups",
"type": "json",
"example": {
"$ref": "#/definitions/ServerSecurityGroup"
},
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u5b89\u5168\u7ec4\u5217\u8868\u3002"
},
{
"name": "OS-EXT-AZ:availability_zone",
"type": "文本",
"example": "cn-north-1c",
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5728\u53ef\u7528\u533a\u540d\u79f0\u3002"
},
{
"name": "user_id",
"type": "文本",
"example": "05498fe56b8010d41f7fc01e280b6666",
"desc": "\u521b\u5efa\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u7528\u6237ID,\u683c\u5f0f\u4e3aUUID\u3002"
},
{
"name": "name",
"type": "文本",
"example": "ecs-test-server",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u540d\u79f0\u3002"
},
{
"name": "created",
"type": "文本",
"example": "2017-07-15T11:30:52Z",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u521b\u5efa\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:19:19Z"
},
{
"name": "tenant_id",
"type": "文本",
"example": "743b4c0428d94531b9f2add666646666",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u79df\u6237ID,\u5373\u9879\u76eeid,\u548cproject_id\u8868\u793a\u76f8\u540c\u7684\u6982\u5ff5,\u683c\u5f0f\u4e3aUUID\u3002"
},
{
"name": "OS-DCF:diskConfig",
"type": "文本",
"example": "AUTO",
"desc": "\u6269\u5c55\u5c5e\u6027, diskConfig\u7684\u7c7b\u578b\u3002\n\n- MANUAL,\u955c\u50cf\u7a7a\u95f4\u4e0d\u4f1a\u6269\u5c55\u3002\n- AUTO,\u7cfb\u7edf\u76d8\u955c\u50cf\u7a7a\u95f4\u4f1a\u81ea\u52a8\u6269\u5c55\u4e3a\u4e0eflavor\u5927\u5c0f\u4e00\u81f4\u3002"
},
{
"name": "accessIPv4",
"type": "文本",
"example": null,
"desc": "\u9884\u7559\u5c5e\u6027\u3002"
},
{
"name": "accessIPv6",
"type": "文本",
"example": null,
"desc": "\u9884\u7559\u5c5e\u6027\u3002"
},
{
"name": "fault",
"type": "文本",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6545\u969c\u4fe1\u606f\u3002\n\n\u53ef\u9009\u53c2\u6570,\u5728\u5f39\u6027\u4e91\u670d\u52a1\u5668\u72b6\u6001\u4e3aERROR\u4e14\u5b58\u5728\u5f02\u5e38\u7684\u60c5\u51b5\u4e0b\u8fd4\u56de\u3002"
},
{
"name": "progress",
"type": "整数",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u8fdb\u5ea6\u3002"
},
{
"name": "OS-EXT-STS:power_state",
"type": "整数",
"example": 4,
"desc": "\u6269\u5c55\u5c5e\u6027,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7535\u6e90\u72b6\u6001\u3002"
},
{
"name": "config_drive",
"type": "文本",
"example": null,
"desc": "config drive\u4fe1\u606f\u3002"
},
{
"name": "metadata",
"type": "json",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5143\u6570\u636e\u3002\n\n> \u8bf4\u660e:\n> \n> \u5143\u6570\u636e\u5305\u542b\u7cfb\u7edf\u9ed8\u8ba4\u6dfb\u52a0\u5b57\u6bb5\u548c\u7528\u6237\u8bbe\u7f6e\u7684\u5b57\u6bb5\u3002\n\n\u7cfb\u7edf\u9ed8\u8ba4\u6dfb\u52a0\u5b57\u6bb5\n\n1. charging_mode\n\u4e91\u670d\u52a1\u5668\u7684\u8ba1\u8d39\u7c7b\u578b\u3002\n\n- \u201c0\u201d:\u6309\u9700\u8ba1\u8d39(\u5373postPaid-\u540e\u4ed8\u8d39\u65b9\u5f0f)\u3002\n- \u201c1\u201d:\u6309\u5305\u5e74\u5305\u6708\u8ba1\u8d39(\u5373prePaid-\u9884\u4ed8\u8d39\u65b9\u5f0f)\u3002\"2\":\u7ade\u4ef7\u5b9e\u4f8b\u8ba1\u8d39\n\n2. metering.order_id\n\u6309\u201c\u5305\u5e74/\u5305\u6708\u201d\u8ba1\u8d39\u7684\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u8ba2\u5355ID\u3002\n\n3. metering.product_id\n\u6309\u201c\u5305\u5e74/\u5305\u6708\u201d\u8ba1\u8d39\u7684\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u4ea7\u54c1ID\u3002\n\n4. vpc_id\n\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u7684\u865a\u62df\u79c1\u6709\u4e91ID\u3002\n\n5. EcmResStatus\n\u4e91\u670d\u52a1\u5668\u7684\u51bb\u7ed3\u72b6\u6001\u3002\n\n- normal:\u4e91\u670d\u52a1\u5668\u6b63\u5e38\u72b6\u6001(\u672a\u88ab\u51bb\u7ed3)\u3002\n- freeze:\u4e91\u670d\u52a1\u5668\u88ab\u51bb\u7ed3\u3002\n\n> \u5f53\u4e91\u670d\u52a1\u5668\u88ab\u51bb\u7ed3\u6216\u8005\u89e3\u51bb\u540e,\u7cfb\u7edf\u9ed8\u8ba4\u6dfb\u52a0\u8be5\u5b57\u6bb5,\u4e14\u8be5\u5b57\u6bb5\u5fc5\u9009\u3002\n\n6. metering.image_id\n\u4e91\u670d\u52a1\u5668\u64cd\u4f5c\u7cfb\u7edf\u5bf9\u5e94\u7684\u955c\u50cfID\n\n7. metering.imagetype\n\u955c\u50cf\u7c7b\u578b,\u76ee\u524d\u652f\u6301:\n\n- \u516c\u5171\u955c\u50cf(gold)\n- \u79c1\u6709\u955c\u50cf(private)\n- \u5171\u4eab\u955c\u50cf(shared)\n\n8. metering.resourcespeccode\n\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u8d44\u6e90\u89c4\u683c\u3002\n\n9. image_name\n\u4e91\u670d\u52a1\u5668\u64cd\u4f5c\u7cfb\u7edf\u5bf9\u5e94\u7684\u955c\u50cf\u540d\u79f0\u3002\n\n10. os_bit\n\u64cd\u4f5c\u7cfb\u7edf\u4f4d\u6570,\u4e00\u822c\u53d6\u503c\u4e3a\u201c32\u201d\u6216\u8005\u201c64\u201d\u3002\n\n11. lockCheckEndpoint\n\u56de\u8c03URL,\u7528\u4e8e\u68c0\u67e5\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u52a0\u9501\u662f\u5426\u6709\u6548\u3002\n\n- \u5982\u679c\u6709\u6548,\u5219\u4e91\u670d\u52a1\u5668\u4fdd\u6301\u9501\u5b9a\u72b6\u6001\u3002\n- \u5982\u679c\u65e0\u6548,\u89e3\u9664\u9501\u5b9a\u72b6\u6001,\u5220\u9664\u5931\u6548\u7684\u9501\u3002\n\n12. lockSource\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6765\u81ea\u54ea\u4e2a\u670d\u52a1\u3002\u8ba2\u5355\u52a0\u9501(ORDER)\n\n13. lockSourceId\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u52a0\u9501\u6765\u81ea\u54ea\u4e2aID\u3002lockSource\u4e3a\u201cORDER\u201d\u65f6,lockSourceId\u4e3a\u8ba2\u5355ID\u3002\n\n14. lockScene\n\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u52a0\u9501\u7c7b\u578b\u3002\n\n- \u6309\u9700\u8f6c\u5305\u5468\u671f(TO_PERIOD_LOCK)\n\n15. virtual_env_type\n\n- IOS\u955c\u50cf\u521b\u5efa\u865a\u62df\u673a,\"virtual_env_type\": \"IsoImage\" \u5c5e\u6027;\n- \u975eIOS\u955c\u50cf\u521b\u5efa\u865a\u62df\u673a,\u572819.5.0\u7248\u672c\u4ee5\u540e\u521b\u5efa\u7684\u865a\u62df\u673a\u5c06\u4e0d\u4f1a\u6dfb\u52a0virtual_env_type \u5c5e\u6027,\u800c\u5728\u6b64\u4e4b\u524d\u7684\u7248\u672c\u521b\u5efa\u7684\u865a\u62df\u673a\u53ef\u80fd\u4f1a\u8fd4\u56de\"virtual_env_type\": \"FusionCompute\"\u5c5e\u6027 \u3002\n\n> virtual_env_type\u5c5e\u6027\u4e0d\u5141\u8bb8\u7528\u6237\u589e\u52a0\u3001\u5220\u9664\u548c\u4fee\u6539\u3002\n\n16. metering.resourcetype\n\u4e91\u670d\u52a1\u5668\u5bf9\u5e94\u7684\u8d44\u6e90\u7c7b\u578b\u3002\n\n17. os_type\n\u64cd\u4f5c\u7cfb\u7edf\u7c7b\u578b,\u53d6\u503c\u4e3a:Linux\u3001Windows\u3002\n\n18. cascaded.instance_extrainfo\n\u7cfb\u7edf\u5185\u90e8\u865a\u62df\u673a\u6269\u5c55\u4fe1\u606f\u3002\n\n19. __support_agent_list\n\u4e91\u670d\u52a1\u5668\u662f\u5426\u652f\u6301\u4f01\u4e1a\u4e3b\u673a\u5b89\u5168\u3001\u4e3b\u673a\u76d1\u63a7\u3002\n\n- \u201chss\u201d:\u4f01\u4e1a\u4e3b\u673a\u5b89\u5168\n- \u201cces\u201d:\u4e3b\u673a\u76d1\u63a7\n\n20. agency_name\n\u59d4\u6258\u7684\u540d\u79f0\u3002\n\n\u59d4\u6258\u662f\u7531\u79df\u6237\u7ba1\u7406\u5458\u5728\u7edf\u4e00\u8eab\u4efd\u8ba4\u8bc1\u670d\u52a1(Identity and Access Management,IAM)\u4e0a\u521b\u5efa\u7684,\u53ef\u4ee5\u4e3a\u5f39\u6027\u4e91\u670d\u52a1\u5668\u63d0\u4f9b\u8bbf\u95ee\u4e91\u670d\u52a1\u7684\u4e34\u65f6\u51ed\u8bc1\u3002"
},
{
"name": "OS-SRV-USG:launched_at",
"type": "文本",
"example": "2018-08-15T14:21:22.000000",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u542f\u52a8\u65f6\u95f4\u3002\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:23:59.000000"
},
{
"name": "OS-SRV-USG:terminated_at",
"type": "文本",
"example": "2019-05-22T03:23:59.000000",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u5220\u9664\u65f6\u95f4\u3002\n\n\u65f6\u95f4\u683c\u5f0f\u4f8b\u5982:2019-05-22T03:23:59.000000"
},
{
"name": "os-extended-volumes:volumes_attached",
"type": "json",
"example": {
"$ref": "#/definitions/ServerExtendVolumeAttachment"
},
"desc": "\u6302\u8f7d\u5230\u5f39\u6027\u4e91\u670d\u52a1\u5668\u4e0a\u7684\u78c1\u76d8\u3002"
},
{
"name": "description",
"type": "文本",
"example": "ecs description",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u63cf\u8ff0\u4fe1\u606f\u3002"
},
{
"name": "host_status",
"type": "文本",
"example": "UP",
"desc": "nova-compute\u72b6\u6001\u3002\n\n- UP:\u670d\u52a1\u6b63\u5e38\n- UNKNOWN:\u72b6\u6001\u672a\u77e5\n- DOWN:\u670d\u52a1\u5f02\u5e38\n- MAINTENANCE:\u7ef4\u62a4\u72b6\u6001\n- \u7a7a\u5b57\u7b26\u4e32:\u5f39\u6027\u4e91\u670d\u52a1\u5668\u65e0\u4e3b\u673a\u4fe1\u606f"
},
{
"name": "OS-EXT-SRV-ATTR:hostname",
"type": "文本",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u4e3b\u673a\u540d\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:reservation_id",
"type": "文本",
"example": "r-f06p3js8",
"desc": "\u6279\u91cf\u521b\u5efa\u573a\u666f,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u9884\u7559ID\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:launch_index",
"type": "整数",
"example": null,
"desc": "\u6279\u91cf\u521b\u5efa\u573a\u666f,\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7684\u542f\u52a8\u987a\u5e8f\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:kernel_id",
"type": "文本",
"example": null,
"desc": "\u82e5\u4f7f\u7528AMI\u683c\u5f0f\u7684\u955c\u50cf,\u5219\u8868\u793akernel image\u7684UUID;\u5426\u5219,\u7559\u7a7a\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:ramdisk_id",
"type": "文本",
"example": null,
"desc": "\u82e5\u4f7f\u7528AMI\u683c\u5f0f\u955c\u50cf,\u5219\u8868\u793aramdisk image\u7684UUID;\u5426\u5219,\u7559\u7a7a\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:root_device_name",
"type": "文本",
"example": "/dev/vda",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7cfb\u7edf\u76d8\u7684\u8bbe\u5907\u540d\u79f0\u3002"
},
{
"name": "OS-EXT-SRV-ATTR:user_data",
"type": "文本",
"example": "IyEvYmluL2Jhc2gKZWNobyAncm9vdDokNiRjcGRkSjckWm5WZHNiR253Z0l0SGlxUjZxbWtLTlJaeU9lZUtKd3dPbG9XSFdUeGFzWjA1STYwdnJYRTdTUTZGbEpFbWlXZ21WNGNmZ1pac1laN1BkMTBLRndyeC8nIHwgY2hwYXNzd2Q6666",
"desc": "\u521b\u5efa\u5f39\u6027\u4e91\u670d\u52a1\u5668\u65f6\u6307\u5b9a\u7684user_data\u3002"
},
{
"name": "locked",
"type": "boolean",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u662f\u5426\u4e3a\u9501\u5b9a\u72b6\u6001\u3002\n\n- true:\u9501\u5b9a\n- false:\u672a\u9501\u5b9a"
},
{
"name": "tags",
"type": "文本、多值",
"example": {
"type": "文本"
},
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6807\u7b7e\u3002"
},
{
"name": "os:scheduler_hints",
"type": "json",
"example": null,
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u8c03\u5ea6\u4fe1\u606f"
},
{
"name": "enterprise_project_id",
"type": "文本",
"example": "0",
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u6240\u5c5e\u7684\u4f01\u4e1a\u9879\u76eeID\u3002"
},
{
"name": "sys_tags",
"type": "文本、多值",
"example": {
"$ref": "#/definitions/ServerSystemTag"
},
"desc": "\u5f39\u6027\u4e91\u670d\u52a1\u5668\u7cfb\u7edf\u6807\u7b7e\u3002"
},
{
"name": "cpu_options",
"type": "json",
"example": null,
"desc": "\u81ea\u5b9a\u4e49CPU\u9009\u9879\u3002"
},
{
"name": "hypervisor",
"type": "文本",
"example": null,
"desc": "hypervisor\u4fe1\u606f\u3002"
}
[
{
"name": "status",
"type": "string",
"desc": "弹性云服务器状态。\n\n取值范围:\n\nACTIVE、BUILD、DELETED、ERROR、HARD_REBOOT、MIGRATING、PAUSED、REBOOT、REBUILD、RESIZE、REVERT_RESIZE、SHUTOFF、SHELVED、SHELVED_OFFLOADED、SOFT_DELETED、SUSPENDED、VERIFY_RESIZE\n\n弹性云服务器状态说明请参考[云服务器状态](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)",
"example": "ACTIVE"
},
{
"name": "updated",
"type": "string",
"desc": "弹性云服务器更新时间。\n\n时间格式例如:2019-05-22T03:30:52Z",
"example": "2019-05-22T03:30:52Z"
},
{
"name": "auto_terminate_time",
"type": "string",
"desc": "弹性云服务器定时删除时间。\n\n时间格式例如:2020-01-19T03:30:52Z",
"example": "2020-01-19T03:30:52Z"
},
{
"name": "hostId",
"type": "string",
"desc": "弹性云服务器所在主机的主机ID。",
"example": "c7145889b2e3202cd295ceddb1742ff8941b827b586861fd0acedf64"
},
{
"name": "OS-EXT-SRV-ATTR:host",
"type": "string",
"desc": "弹性云服务器所在主机的主机名称。",
"example": "pod01.cn-north-1c"
},
{
"name": "addresses",
"type": "object",
"desc": "弹性云服务器的网络属性。",
"example": ""
},
{
"name": "key_name",
"type": "string",
"desc": "弹性云服务器使用的密钥对名称。",
"example": "KeyPair-test"
},
{
"name": "image",
"type": "",
"desc": "弹性云服务器镜像信息。",
"example": ""
},
{
"name": "OS-EXT-STS:task_state",
"type": "string",
"desc": "扩展属性,弹性云服务器当前任务的状态。\n\n取值范围请参考[云服务器状态](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)表3。",
"example": "rebooting"
},
{
"name": "OS-EXT-STS:vm_state",
"type": "string",
"desc": "扩展属性,弹性云服务器当前状态。\n\n云服务器状态说明请参考[云服务器状态](https://support.huaweicloud.com/api-ecs/ecs_08_0002.html)。",
"example": "active"
},
{
"name": "OS-EXT-SRV-ATTR:instance_name",
"type": "string",
"desc": "扩展属性,弹性云服务器别名。",
"example": "instance-0048a91b"
},
{
"name": "OS-EXT-SRV-ATTR:hypervisor_hostname",
"type": "string",
"desc": "扩展属性,弹性云服务器所在虚拟化主机名。",
"example": "nova022@36"
},
{
"name": "flavor",
"type": "",
"desc": "弹性云服务器规格信息。",
"example": ""
},
{
"name": "id",
"type": "string",
"desc": "弹性云服务器ID,格式为UUID。",
"example": "4f4b3dfa-eb70-47cf-a60a-998a53bd6666"
},
{
"name": "security_groups",
"type": "array",
"desc": "弹性云服务器所属安全组列表。",
"example": ""
},
{
"name": "OS-EXT-AZ:availability_zone",
"type": "string",
"desc": "扩展属性,弹性云服务器所在可用区名称。",
"example": "cn-north-1c"
},
{
"name": "user_id",
"type": "string",
"desc": "创建弹性云服务器的用户ID,格式为UUID。",
"example": "05498fe56b8010d41f7fc01e280b6666"
},
{
"name": "name",
"type": "string",
"desc": "弹性云服务器名称。",
"example": "ecs-test-server"
},
{
"name": "created",
"type": "string",
"desc": "弹性云服务器创建时间。\n\n时间格式例如:2019-05-22T03:19:19Z",
"example": "2017-07-15T11:30:52Z"
},
{
"name": "tenant_id",
"type": "string",
"desc": "弹性云服务器所属租户ID,即项目id,和project_id表示相同的概念,格式为UUID。",
"example": "743b4c0428d94531b9f2add666646666"
},
{
"name": "OS-DCF:diskConfig",
"type": "string",
"desc": "扩展属性, diskConfig的类型。\n\n- MANUAL,镜像空间不会扩展。\n- AUTO,系统盘镜像空间会自动扩展为与flavor大小一致。",
"example": "AUTO"
},
{
"name": "accessIPv4",
"type": "string",
"desc": "预留属性。",
"example": ""
},
{
"name": "accessIPv6",
"type": "string",
"desc": "预留属性。",
"example": ""
},
{
"name": "fault",
"type": "",
"desc": "弹性云服务器故障信息。\n\n可选参数,在弹性云服务器状态为ERROR且存在异常的情况下返回。",
"example": ""
},
{
"name": "progress",
"type": "integer",
"desc": "弹性云服务器进度。",
"example": 0
},
{
"name": "OS-EXT-STS:power_state",
"type": "integer",
"desc": "扩展属性,弹性云服务器电源状态。",
"example": 4
},
{
"name": "config_drive",
"type": "string",
"desc": "config drive信息。",
"example": ""
},
{
"name": "metadata",
"type": "object",
"desc": "弹性云服务器元数据。\n\n> 说明:\n> \n> 元数据包含系统默认添加字段和用户设置的字段。\n\n系统默认添加字段\n\n1. charging_mode\n云服务器的计费类型。\n\n- “0”:按需计费(即postPaid-后付费方式)。\n- “1”:按包年包月计费(即prePaid-预付费方式)。\"2\":竞价实例计费\n\n2. metering.order_id\n按“包年/包月”计费的云服务器对应的订单ID。\n\n3. metering.product_id\n按“包年/包月”计费的云服务器对应的产品ID。\n\n4. vpc_id\n云服务器所属的虚拟私有云ID。\n\n5. EcmResStatus\n云服务器的冻结状态。\n\n- normal:云服务器正常状态(未被冻结)。\n- freeze:云服务器被冻结。\n\n> 当云服务器被冻结或者解冻后,系统默认添加该字段,且该字段必选。\n\n6. metering.image_id\n云服务器操作系统对应的镜像ID\n\n7. metering.imagetype\n镜像类型,目前支持:\n\n- 公共镜像(gold)\n- 私有镜像(private)\n- 共享镜像(shared)\n\n8. metering.resourcespeccode\n云服务器对应的资源规格。\n\n9. image_name\n云服务器操作系统对应的镜像名称。\n\n10. os_bit\n操作系统位数,一般取值为“32”或者“64”。\n\n11. lockCheckEndpoint\n回调URL,用于检查弹性云服务器的加锁是否有效。\n\n- 如果有效,则云服务器保持锁定状态。\n- 如果无效,解除锁定状态,删除失效的锁。\n\n12. lockSource\n弹性云服务器来自哪个服务。订单加锁(ORDER)\n\n13. lockSourceId\n弹性云服务器的加锁来自哪个ID。lockSource为“ORDER”时,lockSourceId为订单ID。\n\n14. lockScene\n弹性云服务器的加锁类型。\n\n- 按需转包周期(TO_PERIOD_LOCK)\n\n15. virtual_env_type\n\n- IOS镜像创建虚拟机,\"virtual_env_type\": \"IsoImage\" 属性;\n- 非IOS镜像创建虚拟机,在19.5.0版本以后创建的虚拟机将不会添加virtual_env_type 属性,而在此之前的版本创建的虚拟机可能会返回\"virtual_env_type\": \"FusionCompute\"属性 。\n\n> virtual_env_type属性不允许用户增加、删除和修改。\n\n16. metering.resourcetype\n云服务器对应的资源类型。\n\n17. os_type\n操作系统类型,取值为:Linux、Windows。\n\n18. cascaded.instance_extrainfo\n系统内部虚拟机扩展信息。\n\n19. __support_agent_list\n云服务器是否支持企业主机安全、主机监控。\n\n- “hss”:企业主机安全\n- “ces”:主机监控\n\n20. agency_name\n委托的名称。\n\n委托是由租户管理员在统一身份认证服务(Identity and Access Management,IAM)上创建的,可以为弹性云服务器提供访问云服务的临时凭证。",
"example": ""
},
{
"name": "OS-SRV-USG:launched_at",
"type": "string",
"desc": "弹性云服务器启动时间。时间格式例如:2019-05-22T03:23:59.000000",
"example": "2018-08-15T14:21:22.000000"
},
{
"name": "OS-SRV-USG:terminated_at",
"type": "string",
"desc": "弹性云服务器删除时间。\n\n时间格式例如:2019-05-22T03:23:59.000000",
"example": "2019-05-22T03:23:59.000000"
},
{
"name": "os-extended-volumes:volumes_attached",
"type": "array",
"desc": "挂载到弹性云服务器上的磁盘。",
"example": ""
},
{
"name": "description",
"type": "string",
"desc": "弹性云服务器的描述信息。",
"example": "ecs description"
},
{
"name": "host_status",
"type": "string",
"desc": "nova-compute状态。\n\n- UP:服务正常\n- UNKNOWN:状态未知\n- DOWN:服务异常\n- MAINTENANCE:维护状态\n- 空字符串:弹性云服务器无主机信息",
"example": "UP"
},
{
"name": "OS-EXT-SRV-ATTR:hostname",
"type": "string",
"desc": "弹性云服务器的主机名。",
"example": ""
},
{
"name": "OS-EXT-SRV-ATTR:reservation_id",
"type": "string",
"desc": "批量创建场景,弹性云服务器的预留ID。",
"example": "r-f06p3js8"
},
{
"name": "OS-EXT-SRV-ATTR:launch_index",
"type": "integer",
"desc": "批量创建场景,弹性云服务器的启动顺序。",
"example": 0
},
{
"name": "OS-EXT-SRV-ATTR:kernel_id",
"type": "string",
"desc": "若使用AMI格式的镜像,则表示kernel image的UUID;否则,留空。",
"example": ""
},
{
"name": "OS-EXT-SRV-ATTR:ramdisk_id",
"type": "string",
"desc": "若使用AMI格式镜像,则表示ramdisk image的UUID;否则,留空。",
"example": ""
},
{
"name": "OS-EXT-SRV-ATTR:root_device_name",
"type": "string",
"desc": "弹性云服务器系统盘的设备名称。",
"example": "/dev/vda"
},
{
"name": "OS-EXT-SRV-ATTR:user_data",
"type": "string",
"desc": "创建弹性云服务器时指定的user_data。",
"example": "IyEvYmluL2Jhc2gKZWNobyAncm9vdDokNiRjcGRkSjckWm5WZHNiR253Z0l0SGlxUjZxbWtLTlJaeU9lZUtKd3dPbG9XSFdUeGFzWjA1STYwdnJYRTdTUTZGbEpFbWlXZ21WNGNmZ1pac1laN1BkMTBLRndyeC8nIHwgY2hwYXNzd2Q6666"
},
{
"name": "locked",
"type": "boolean",
"desc": "弹性云服务器是否为锁定状态。\n\n- true:锁定\n- false:未锁定",
"example": false
},
{
"name": "tags",
"type": "array",
"desc": "弹性云服务器标签。",
"example": ""
},
{
"name": "os:scheduler_hints",
"type": "",
"desc": "弹性云服务器调度信息",
"example": ""
},
{
"name": "enterprise_project_id",
"type": "string",
"desc": "弹性云服务器所属的企业项目ID。",
"example": "0"
},
{
"name": "sys_tags",
"type": "array",
"desc": "弹性云服务器系统标签。",
"example": ""
},
{
"name": "cpu_options",
"type": "",
"desc": "自定义CPU选项。",
"example": ""
},
{
"name": "hypervisor",
"type": "",
"desc": "hypervisor信息。",
"example": ""
}
]

View File

@@ -1,297 +1,248 @@
[
{
"name": "Placement",
"type": "json",
"desc": "实例所在的位置。",
"example": {
"HostId": "host-h3m57oik",
"ProjectId": 1174660,
"HostIds": [],
"Zone": "ap-guangzhou-1",
"HostIps": []
}
},
{
"name": "InstanceId",
"type": "文本",
"desc": "实例ID。",
"example": "ins-xlsyru2j"
},
{
"name": "InstanceType",
"type": "文本",
"desc": "实例机型。",
"example": "S2.SMALL2"
},
{
"name": "CPU",
"type": "整数",
"desc": "实例的CPU核数,单位:。",
"example": 1
},
{
"name": "Memory",
"type": "整数",
"desc": "实例内存容量单位GB。",
"example": 1
},
{
"name": "RestrictState",
"type": "文本",
"desc": "实例业务状态。取值范围: NORMAL表示正常状态的实例 EXPIRED表示过期的实例 PROTECTIVELY_ISOLATED表示被安全隔离的实例。",
"example": "PROTECTIVELY_ISOLATED"
},
{
"name": "InstanceName",
"type": "文本",
"desc": "实例名称。",
"example": "test"
},
{
"name": "InstanceChargeType",
"type": "文本",
"desc": "实例计费模式。取值范围: PREPAID表示预付费即包年包月 POSTPAID_BY_HOUR表示后付费即按量计费 CDHPAID专用宿主机付费即只对专用宿主机计费不对专用宿主机上的实例计费。 SPOTPAID表示竞价实例付费。",
"example": "POSTPAID_BY_HOUR"
},
{
"name": "SystemDisk",
"type": "json",
"desc": "实例系统盘信息。",
"example": {
"DiskSize": 50,
"CdcId": null,
"DiskId": "disk-czsodtl1",
"DiskType": "CLOUD_SSD"
}
},
{
"name": "DataDisks",
"type": "json",
"desc": "实例数据盘信息。",
"example": [
{
"DeleteWithInstance": true,
"Encrypt": true,
"CdcId": null,
"DiskType": "CLOUD_SSD",
"ThroughputPerformance": 0,
"KmsKeyId": null,
"DiskSize": 50,
"SnapshotId": null,
"DiskId": "disk-bzsodtn1"
}
]
},
{
"name": "PrivateIpAddresses",
"type": "文本、多值",
"desc": "实例主网卡的内网IP列表。",
"example": [
"172.16.32.78"
]
},
{
"name": "PublicIpAddresses",
"type": "文本、多值",
"desc": "实例主网卡的公网IP列表。 注意:此字段可能返回 null表示取不到有效值。",
"example": [
"123.207.11.190"
]
},
{
"name": "InternetAccessible",
"type": "json",
"desc": "实例带宽信息。",
"example": {
"PublicIpAssigned": true,
"InternetChargeType": "TRAFFIC_POSTPAID_BY_HOUR",
"BandwidthPackageId": null,
"InternetMaxBandwidthOut": 1
}
},
{
"name": "VirtualPrivateCloud",
"type": "json",
"desc": "实例所属虚拟私有网络信息。",
"example": {
"SubnetId": "subnet-mv4sn55k",
"AsVpcGateway": false,
"Ipv6AddressCount": 1,
"VpcId": "vpc-m0cnatxj",
"PrivateIpAddresses": [
"172.16.3.59"
]
}
},
{
"name": "ImageId",
"type": "文本",
"desc": "生产实例所使用的镜像ID。",
"example": "img-8toqc6s3"
},
{
"name": "RenewFlag",
"type": "文本",
"desc": "自动续费标识。取值范围: NOTIFY_AND_MANUAL_RENEW表示通知即将过期但不自动续费 NOTIFY_AND_AUTO_RENEW表示通知即将过期而且自动续费 DISABLE_NOTIFY_AND_MANUAL_RENEW表示不通知即将过期也不自动续费。 注意后付费模式本项为null",
"example": "NOTIFY_AND_MANUAL_RENEW"
},
{
"name": "CreatedTime",
"type": "json",
"desc": "创建时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。",
"example": "2020-09-22T00:00:00+00:00"
},
{
"name": "ExpiredTime",
"type": "json",
"desc": "到期时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。注意后付费模式本项为null",
"example": "2020-09-22T00:00:00+00:00"
},
{
"name": "OsName",
"type": "文本",
"desc": "操作系统名称。",
"example": "CentOS 7.4 64bit"
},
{
"name": "SecurityGroupIds",
"type": "文本、多值",
"desc": "实例所属安全组。该参数可以通过调用 DescribeSecurityGroups 的返回值中的sgId字段来获取。",
"example": [
"sg-p1ezv4wz"
]
},
{
"name": "LoginSettings",
"type": "json",
"desc": "实例登录设置。目前只返回实例所关联的密钥。",
"example": {
"Password": "123qwe!@#QWE",
"KeepImageLogin": "False",
"KeyIds": [
"skey-b4vakk62"
]
}
},
{
"name": "InstanceState",
"type": "文本",
"desc": "实例状态。取值范围: PENDING表示创建中 LAUNCH_FAILED表示创建失败 RUNNING表示运行中 STOPPED表示关机 STARTING表示开机中 STOPPING表示关机中 REBOOTING表示重启中 SHUTDOWN表示停止待销毁 TERMINATING表示销毁中。",
"example": "RUNNING"
},
{
"name": "Tags",
"type": "json",
"desc": "实例关联的标签列表。",
"example": [
{
"Value": "test",
"Key": "test"
}
]
},
{
"name": "StopChargingMode",
"type": "文本",
"desc": "实例的关机计费模式。 取值范围: KEEP_CHARGING关机继续收费 STOP_CHARGING关机停止收费NOT_APPLICABLE实例处于非关机状态或者不适用关机停止计费的条件",
"example": "NOT_APPLICABLE"
},
{
"name": "Uuid",
"type": "文本",
"desc": "实例全局唯一ID",
"example": "e85f1388-0422-410d-8e50-bef540e78c18"
},
{
"name": "LatestOperation",
"type": "文本",
"desc": "实例的最新操作。例StopInstances、ResetInstance。 注意:此字段可能返回 null表示取不到有效值。",
"example": "ResetInstancesType"
},
{
"name": "LatestOperationState",
"type": "文本",
"desc": "实例的最新操作状态。取值范围: SUCCESS表示操作成功 OPERATING表示操作执行中 FAILED表示操作失败 注意:此字段可能返回 null表示取不到有效值。",
"example": "SUCCESS"
},
{
"name": "LatestOperationRequestId",
"type": "文本",
"desc": "实例最新操作的唯一请求 ID。 注意:此字段可能返回 null表示取不到有效值。",
"example": "c7de1287-061d-4ace-8caf-6ad8e5a2f29a"
},
{
"name": "DisasterRecoverGroupId",
"type": "文本",
"desc": "分散置放群组ID。 注意:此字段可能返回 null表示取不到有效值。",
"example": ""
},
{
"name": "IPv6Addresses",
"type": "文本、多值",
"desc": "实例的IPv6地址。 注意:此字段可能返回 null表示取不到有效值。",
"example": [
"2001:0db8:86a3:08d3:1319:8a2e:0370:7344"
]
},
{
"name": "CamRoleName",
"type": "文本",
"desc": "CAM角色名。 注意:此字段可能返回 null表示取不到有效值。",
"example": ""
},
{
"name": "HpcClusterId",
"type": "文本",
"desc": "高性能计算集群ID。 注意:此字段可能返回 null表示取不到有效值。",
"example": ""
},
{
"name": "RdmaIpAddresses",
"type": "文本、多值",
"desc": "高性能计算集群IP列表。 注意:此字段可能返回 null表示取不到有效值。",
"example": []
},
{
"name": "IsolatedSource",
"type": "文本",
"desc": "实例隔离类型。取值范围: ARREAR表示欠费隔离 EXPIRE表示到期隔离 MANMADE表示主动退还隔离 NOTISOLATED表示未隔离 注意:此字段可能返回 null表示取不到有效值。",
"example": "NOTISOLATED"
},
{
"name": "GPUInfo",
"type": "json",
"desc": "GPU信息。如果是gpu类型子机该值会返回GPU信息如果是其他类型子机则不返回。 注意:此字段可能返回 null表示取不到有效值。",
"example": null
},
{
"name": "LicenseType",
"type": "文本",
"desc": "实例的操作系统许可类型默认为TencentCloud",
"example": null
},
{
"name": "DisableApiTermination",
"type": "Boolean",
"desc": "实例销毁保护标志表示是否允许通过api接口删除实例。取值范围 TRUE表示开启实例保护不允许通过api接口删除实例 FALSE表示关闭实例保护允许通过api接口删除实例 默认取值FALSE。",
"example": null
},
{
"name": "DefaultLoginUser",
"type": "文本",
"desc": "默认登录用户。",
"example": null
},
{
"name": "DefaultLoginPort",
"type": "整数",
"desc": "默认登录端口。",
"example": null
},
{
"name": "LatestOperationErrorMsg",
"type": "文本",
"desc": "实例的最新操作错误信息。 注意:此字段可能返回 null表示取不到有效值。",
"example": null
}
[
{
"name": "Placement",
"type": "Placement",
"desc": "实例所在的位置。",
"example": ""
},
{
"name": "InstanceId",
"type": "String",
"desc": "实例ID。",
"example": "ins-9bxebleo"
},
{
"name": "InstanceType",
"type": "String",
"desc": "实例机型。",
"example": "S1.SMALL1"
},
{
"name": "CPU",
"type": "Integer",
"desc": "实例的CPU核数单位。",
"example": "1"
},
{
"name": "Memory",
"type": "Integer",
"desc": "实例内存容量,单位:GB。",
"example": "1"
},
{
"name": "RestrictState",
"type": "String",
"desc": "NORMAL表示正常状态的实例\nEXPIRED表示过期的实例\nPROTECTIVELY_ISOLATED表示被安全隔离的实例。",
"example": "NORMAL"
},
{
"name": "InstanceName",
"type": "String",
"desc": "实例名称。",
"example": "测试实例"
},
{
"name": "InstanceChargeType",
"type": "String",
"desc": "PREPAID表示预付费即包年包月\nPOSTPAID_BY_HOUR表示后付费即按量计费\nCDHPAID专用宿主机付费即只对专用宿主机计费不对专用宿主机上的实例计费。\nSPOTPAID表示竞价实例付费。",
"example": "PREPAID"
},
{
"name": "SystemDisk",
"type": "SystemDisk",
"desc": "实例系统盘信息。",
"example": ""
},
{
"name": "DataDisks",
"type": "Array of DataDisk",
"desc": "实例数据盘信息。",
"example": ""
},
{
"name": "PrivateIpAddresses",
"type": "Array of String",
"desc": "实例主网卡的内网IP列表。",
"example": "[\"172.16.32.78\"]"
},
{
"name": "PublicIpAddresses",
"type": "Array of String",
"desc": "实例主网卡的公网IP列表。注意此字段可能返回 null表示取不到有效值。",
"example": "[\"123.207.11.190\"]"
},
{
"name": "InternetAccessible",
"type": "InternetAccessible",
"desc": "实例带宽信息。",
"example": ""
},
{
"name": "VirtualPrivateCloud",
"type": "VirtualPrivateCloud",
"desc": "实例所属虚拟私有网络信息。",
"example": ""
},
{
"name": "ImageId",
"type": "String",
"desc": "生产实例所使用的镜像ID。",
"example": "img-9qabwvbn"
},
{
"name": "RenewFlag",
"type": "String",
"desc": "NOTIFY_AND_MANUAL_RENEW表示通知即将过期但不自动续费\nNOTIFY_AND_AUTO_RENEW表示通知即将过期而且自动续费\nDISABLE_NOTIFY_AND_MANUAL_RENEW表示不通知即将过期也不自动续费。\n注意后付费模式本项为null",
"example": "NOTIFY_AND_MANUAL_RENEW"
},
{
"name": "CreatedTime",
"type": "Timestamp ISO8601",
"desc": "创建时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。",
"example": "2020-03-10T02:43:51Z"
},
{
"name": "ExpiredTime",
"type": "Timestamp ISO8601",
"desc": "到期时间。按照ISO8601标准表示并且使用UTC时间。格式为YYYY-MM-DDThh:mm:ssZ。注意后付费模式本项为null",
"example": "2020-04-10T02:47:36Z"
},
{
"name": "OsName",
"type": "String",
"desc": "操作系统名称。",
"example": "CentOS 7.6 64bit"
},
{
"name": "SecurityGroupIds",
"type": "Array of String",
"desc": "实例所属安全组。该参数可以通过调用 DescribeSecurityGroups 的返回值中的sgId字段来获取。",
"example": "[\"sg-p1ezv4wz\"]"
},
{
"name": "LoginSettings",
"type": "LoginSettings",
"desc": "实例登录设置。目前只返回实例所关联的密钥。",
"example": ""
},
{
"name": "InstanceState",
"type": "String",
"desc": "PENDING表示创建中\nLAUNCH_FAILED表示创建失败\nRUNNING表示运行中\nSTOPPED表示关机\nSTARTING表示开机中\nSTOPPING表示关机中\nREBOOTING表示重启中\nSHUTDOWN表示停止待销毁\nTERMINATING表示销毁中。",
"example": ""
},
{
"name": "Tags",
"type": "Array of Tag",
"desc": "实例关联的标签列表。",
"example": ""
},
{
"name": "StopChargingMode",
"type": "String",
"desc": "KEEP_CHARGING关机继续收费\nSTOP_CHARGING关机停止收费\nNOT_APPLICABLE实例处于非关机状态或者不适用关机停止计费的条件",
"example": "NOT_APPLICABLE"
},
{
"name": "Uuid",
"type": "String",
"desc": "实例全局唯一ID",
"example": "68b510db-b4c1-4630-a62b-73d0c7c970f9"
},
{
"name": "LatestOperation",
"type": "String",
"desc": "实例的最新操作。例StopInstances、ResetInstance。注意此字段可能返回 null表示取不到有效值。",
"example": "RenewInstances"
},
{
"name": "LatestOperationState",
"type": "String",
"desc": "SUCCESS表示操作成功\nOPERATING表示操作执行中\nFAILED表示操作失败注意此字段可能返回 null表示取不到有效值。",
"example": "SUCCESS"
},
{
"name": "LatestOperationRequestId",
"type": "String",
"desc": "实例最新操作的唯一请求 ID。注意此字段可能返回 null表示取不到有效值。",
"example": "3554eb5b-1cfa-471a-ae76-dc436c9d43e8"
},
{
"name": "DisasterRecoverGroupId",
"type": "String",
"desc": "分散置放群组ID。注意此字段可能返回 null表示取不到有效值。",
"example": "null"
},
{
"name": "IPv6Addresses",
"type": "Array of String",
"desc": "实例的IPv6地址。注意此字段可能返回 null表示取不到有效值。",
"example": "null"
},
{
"name": "CamRoleName",
"type": "String",
"desc": "CAM角色名。注意此字段可能返回 null表示取不到有效值。",
"example": "null"
},
{
"name": "HpcClusterId",
"type": "String",
"desc": "高性能计算集群ID。注意此字段可能返回 null表示取不到有效值。",
"example": "null"
},
{
"name": "RdmaIpAddresses",
"type": "Array of String",
"desc": "高性能计算集群IP列表。注意此字段可能返回 null表示取不到有效值。",
"example": "null"
},
{
"name": "DedicatedClusterId",
"type": "String",
"desc": "实例所在的专用集群ID。注意此字段可能返回 null表示取不到有效值。",
"example": "cluster-du3jken"
},
{
"name": "IsolatedSource",
"type": "String",
"desc": "ARREAR表示欠费隔离\nEXPIRE表示到期隔离\nMANMADE表示主动退还隔离\nNOTISOLATED表示未隔离",
"example": ""
},
{
"name": "GPUInfo",
"type": "GPUInfo",
"desc": "GPU信息。如果是gpu类型子机该值会返回GPU信息如果是其他类型子机则不返回。注意此字段可能返回 null表示取不到有效值。",
"example": ""
},
{
"name": "LicenseType",
"type": "String",
"desc": "实例的操作系统许可类型默认为TencentCloud",
"example": "TencentCloud"
},
{
"name": "DisableApiTermination",
"type": "Boolean",
"desc": "TRUE表示开启实例保护不允许通过api接口删除实例\nFALSE表示关闭实例保护允许通过api接口删除实例默认取值FALSE。",
"example": "false"
},
{
"name": "DefaultLoginUser",
"type": "String",
"desc": "默认登录用户。",
"example": "root"
},
{
"name": "DefaultLoginPort",
"type": "Integer",
"desc": "默认登录端口。",
"example": "22"
},
{
"name": "LatestOperationErrorMsg",
"type": "String",
"desc": "实例的最新操作错误信息。注意:此字段可能返回 null表示取不到有效值。",
"example": "None"
}
]

View File

@@ -5,10 +5,14 @@ from __future__ import unicode_literals
from flask import current_app
from api.extensions import cache
from api.extensions import db
from api.lib.cmdb.custom_dashboard import CustomDashboardManager
from api.models.cmdb import Attribute
from api.models.cmdb import CI
from api.models.cmdb import CIType
from api.models.cmdb import CITypeAttribute
from api.models.cmdb import PreferenceShowAttributes
from api.models.cmdb import PreferenceTreeView
from api.models.cmdb import RelationType
@@ -226,7 +230,9 @@ class CITypeAttributeCache(object):
class CMDBCounterCache(object):
KEY = 'CMDB::Counter'
KEY = 'CMDB::Counter::dashboard'
KEY2 = 'CMDB::Counter::adc'
KEY3 = 'CMDB::Counter::sub'
@classmethod
def get(cls):
@@ -429,3 +435,47 @@ class CMDBCounterCache(object):
return
return numfound
@classmethod
def flush_adc_counter(cls):
res = db.session.query(CI.type_id, CI.is_auto_discovery)
result = dict()
for i in res:
result.setdefault(i.type_id, dict(total=0, auto_discovery=0))
result[i.type_id]['total'] += 1
if i.is_auto_discovery:
result[i.type_id]['auto_discovery'] += 1
cache.set(cls.KEY2, result, timeout=0)
return result
@classmethod
def get_adc_counter(cls):
return cache.get(cls.KEY2) or cls.flush_adc_counter()
@classmethod
def flush_sub_counter(cls):
result = dict(type_id2users=dict())
types = db.session.query(PreferenceShowAttributes.type_id,
PreferenceShowAttributes.uid, PreferenceShowAttributes.created_at).filter(
PreferenceShowAttributes.deleted.is_(False)).group_by(
PreferenceShowAttributes.uid, PreferenceShowAttributes.type_id)
for i in types:
result['type_id2users'].setdefault(i.type_id, []).append(i.uid)
types = PreferenceTreeView.get_by(to_dict=False)
for i in types:
result['type_id2users'].setdefault(i.type_id, [])
if i.uid not in result['type_id2users'][i.type_id]:
result['type_id2users'][i.type_id].append(i.uid)
cache.set(cls.KEY3, result, timeout=0)
return result
@classmethod
def get_sub_counter(cls):
return cache.get(cls.KEY3) or cls.flush_sub_counter()

View File

@@ -14,8 +14,8 @@ from werkzeug.exceptions import BadRequest
from api.extensions import db
from api.extensions import rd
from api.lib.cmdb.cache import AttributeCache
from api.lib.cmdb.cache import CITypeAttributesCache
from api.lib.cmdb.cache import CITypeCache
from api.lib.cmdb.cache import CMDBCounterCache
from api.lib.cmdb.ci_type import CITypeAttributeManager
from api.lib.cmdb.ci_type import CITypeManager
from api.lib.cmdb.ci_type import CITypeRelationManager
@@ -52,7 +52,6 @@ from api.models.cmdb import AttributeHistory
from api.models.cmdb import AutoDiscoveryCI
from api.models.cmdb import CI
from api.models.cmdb import CIRelation
from api.models.cmdb import CITypeAttribute
from api.models.cmdb import CITypeRelation
from api.models.cmdb import CITypeTrigger
from api.tasks.cmdb import ci_cache
@@ -218,15 +217,7 @@ class CIManager(object):
@classmethod
def get_ad_statistics(cls):
res = CI.get_by(to_dict=False)
result = dict()
for i in res:
result.setdefault(i.type_id, dict(total=0, auto_discovery=0))
result[i.type_id]['total'] += 1
if i.is_auto_discovery:
result[i.type_id]['auto_discovery'] += 1
return result
return CMDBCounterCache.get_adc_counter()
@staticmethod
def ci_is_exist(unique_key, unique_value, type_id):
@@ -317,14 +308,18 @@ class CIManager(object):
"""
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
ci_type = CITypeManager.check_is_existed(ci_type_name)
raw_dict = copy.deepcopy(ci_dict)
unique_key = AttributeCache.get(ci_type.unique_id) or abort(
400, ErrFormat.unique_value_not_found.format("unique_id={}".format(ci_type.unique_id)))
if (unique_key.default and unique_key.default.get('default') == AttributeDefaultValueEnum.AUTO_INC_ID and
not ci_dict.get(unique_key.name)):
ci_dict[unique_key.name] = cls._auto_inc_id(unique_key)
unique_value = ci_dict.get(unique_key.name) or ci_dict.get(unique_key.alias) or ci_dict.get(unique_key.id)
unique_value = unique_value or abort(400, ErrFormat.unique_key_required.format(unique_key.name))
attrs = CITypeAttributesCache.get2(ci_type_name)
attrs = CITypeAttributeManager.get_all_attributes(ci_type.id)
ci_type_attrs_name = {attr.name: attr for _, attr in attrs}
ci_type_attrs_alias = {attr.alias: attr for _, attr in attrs}
ci_attr2type_attr = {type_attr.attr_id: type_attr for type_attr, _ in attrs}
@@ -354,7 +349,8 @@ class CIManager(object):
if attr.default.get('default') and attr.default.get('default') in (
AttributeDefaultValueEnum.CREATED_AT, AttributeDefaultValueEnum.UPDATED_AT):
ci_dict[attr.name] = now
elif attr.default.get('default') == AttributeDefaultValueEnum.AUTO_INC_ID:
elif (attr.default.get('default') == AttributeDefaultValueEnum.AUTO_INC_ID and
not ci_dict.get(attr.name)):
ci_dict[attr.name] = cls._auto_inc_id(attr)
elif ((attr.name not in ci_dict and attr.alias not in ci_dict) or (
ci_dict.get(attr.name) is None and ci_dict.get(attr.alias) is None)):
@@ -368,6 +364,8 @@ class CIManager(object):
if attr.default and attr.default.get('default') == AttributeDefaultValueEnum.UPDATED_AT:
ci_dict[attr.name] = now
value_manager = AttributeValueManager()
computed_attrs = []
for _, attr in attrs:
if attr.is_computed:
@@ -378,7 +376,8 @@ class CIManager(object):
elif attr.alias in ci_dict:
password_dict[attr.id] = ci_dict.pop(attr.alias)
value_manager = AttributeValueManager()
if attr.re_check and password_dict.get(attr.id):
value_manager.check_re(attr.re_check, password_dict[attr.id])
if computed_attrs:
value_manager.handle_ci_compute_attributes(ci_dict, computed_attrs, ci)
@@ -386,7 +385,7 @@ class CIManager(object):
cls._valid_unique_constraint(ci_type.id, ci_dict, ci and ci.id)
ref_ci_dict = dict()
for k in ci_dict:
for k in copy.deepcopy(ci_dict):
if k.startswith("$") and "." in k:
ref_ci_dict[k] = ci_dict[k]
continue
@@ -395,9 +394,13 @@ class CIManager(object):
k not in ci_type_attrs_alias and _no_attribute_policy == ExistPolicy.REJECT):
return abort(400, ErrFormat.attribute_not_found.format(k))
if limit_attrs and ci_type_attrs_name.get(k) not in limit_attrs and (
ci_type_attrs_alias.get(k) not in limit_attrs):
return abort(403, ErrFormat.ci_filter_perm_attr_no_permission.format(k))
_attr_name = ((ci_type_attrs_name.get(k) and ci_type_attrs_name[k].name) or
(ci_type_attrs_alias.get(k) and ci_type_attrs_alias[k].name))
if limit_attrs and _attr_name not in limit_attrs:
if k in raw_dict:
return abort(403, ErrFormat.ci_filter_perm_attr_no_permission.format(k))
else:
ci_dict.pop(k)
ci_dict = {k: v for k, v in ci_dict.items() if k in ci_type_attrs_name or k in ci_type_attrs_alias}
@@ -429,13 +432,17 @@ class CIManager(object):
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
ci = self.confirm_ci_existed(ci_id)
attrs = CITypeAttributesCache.get2(ci.type_id)
raw_dict = copy.deepcopy(ci_dict)
attrs = CITypeAttributeManager.get_all_attributes(ci.type_id)
ci_type_attrs_name = {attr.name: attr for _, attr in attrs}
ci_attr2type_attr = {type_attr.attr_id: type_attr for type_attr, _ in attrs}
for _, attr in attrs:
if attr.default and attr.default.get('default') == AttributeDefaultValueEnum.UPDATED_AT:
ci_dict[attr.name] = now
value_manager = AttributeValueManager()
password_dict = dict()
computed_attrs = list()
for _, attr in attrs:
@@ -447,7 +454,8 @@ class CIManager(object):
elif attr.alias in ci_dict:
password_dict[attr.id] = ci_dict.pop(attr.alias)
value_manager = AttributeValueManager()
if attr.re_check and password_dict.get(attr.id):
value_manager.check_re(attr.re_check, password_dict[attr.id])
if computed_attrs:
value_manager.handle_ci_compute_attributes(ci_dict, computed_attrs, ci)
@@ -463,9 +471,12 @@ class CIManager(object):
key2attr = value_manager.valid_attr_value(ci_dict, ci.type_id, ci.id, ci_type_attrs_name,
ci_attr2type_attr=ci_attr2type_attr)
if limit_attrs:
for k in ci_dict:
for k in copy.deepcopy(ci_dict):
if k not in limit_attrs:
return abort(403, ErrFormat.ci_filter_perm_attr_no_permission.format(k))
if k in raw_dict:
return abort(403, ErrFormat.ci_filter_perm_attr_no_permission.format(k))
else:
ci_dict.pop(k)
try:
record_id = value_manager.create_or_update_attr_value(ci, ci_dict, key2attr)
@@ -513,8 +524,7 @@ class CIManager(object):
ci_delete_trigger.apply_async(args=(trigger, OperateType.DELETE, ci_dict), queue=CMDB_QUEUE)
attrs = CITypeAttribute.get_by(type_id=ci.type_id, to_dict=False)
attrs = [AttributeCache.get(attr.attr_id) for attr in attrs]
attrs = [i for _, i in CITypeAttributeManager.get_all_attributes(type_id=ci.type_id)]
for attr in attrs:
value_table = TableMap(attr=attr).table
for item in value_table.get_by(ci_id=ci_id, to_dict=False):

View File

@@ -5,8 +5,10 @@ import copy
import toposort
from flask import abort
from flask import current_app
from flask import session
from flask_login import current_user
from toposort import toposort_flatten
from werkzeug.exceptions import BadRequest
from api.extensions import db
from api.lib.cmdb.attribute import AttributeManager
@@ -22,6 +24,7 @@ from api.lib.cmdb.const import ResourceTypeEnum
from api.lib.cmdb.const import RoleEnum
from api.lib.cmdb.const import ValueTypeEnum
from api.lib.cmdb.history import CITypeHistoryManager
from api.lib.cmdb.perms import CIFilterPermsCRUD
from api.lib.cmdb.relation_type import RelationTypeManager
from api.lib.cmdb.resp_format import ErrFormat
from api.lib.cmdb.value import AttributeValueManager
@@ -39,10 +42,12 @@ from api.models.cmdb import CITypeAttributeGroup
from api.models.cmdb import CITypeAttributeGroupItem
from api.models.cmdb import CITypeGroup
from api.models.cmdb import CITypeGroupItem
from api.models.cmdb import CITypeInheritance
from api.models.cmdb import CITypeRelation
from api.models.cmdb import CITypeTrigger
from api.models.cmdb import CITypeUniqueConstraint
from api.models.cmdb import CustomDashboard
from api.models.cmdb import PreferenceCITypeOrder
from api.models.cmdb import PreferenceRelationView
from api.models.cmdb import PreferenceSearchOption
from api.models.cmdb import PreferenceShowAttributes
@@ -72,15 +77,18 @@ class CITypeManager(object):
return CIType.get_by_id(ci_type.id)
@staticmethod
def get_ci_types(type_name=None):
def get_ci_types(type_name=None, like=True):
resources = None
if current_app.config.get('USE_ACL') and not is_app_admin('cmdb'):
resources = set([i.get('name') for i in ACLManager().get_resources("CIType")])
resources = set([i.get('name') for i in ACLManager().get_resources(ResourceTypeEnum.CI_TYPE)])
ci_types = CIType.get_by() if type_name is None else CIType.get_by_like(name=type_name)
ci_types = CIType.get_by() if type_name is None else (
CIType.get_by_like(name=type_name) if like else CIType.get_by(name=type_name))
res = list()
for type_dict in ci_types:
type_dict["unique_key"] = AttributeCache.get(type_dict["unique_id"]).name
attr = AttributeCache.get(type_dict["unique_id"])
type_dict["unique_key"] = attr and attr.name
type_dict['parent_ids'] = CITypeInheritanceManager.get_parents(type_dict['id'])
if resources is None or type_dict['name'] in resources:
res.append(type_dict)
@@ -113,6 +121,9 @@ class CITypeManager(object):
@classmethod
@kwargs_required("name")
def add(cls, **kwargs):
if current_app.config.get('USE_ACL') and not is_app_admin('cmdb'):
if ErrFormat.ci_type_config not in {i['name'] for i in ACLManager().get_resources(ResourceTypeEnum.PAGE)}:
return abort(403, ErrFormat.no_permission2)
unique_key = kwargs.pop("unique_key", None) or kwargs.pop("unique_id", None)
unique_key = AttributeCache.get(unique_key) or abort(404, ErrFormat.unique_key_not_define)
@@ -124,14 +135,23 @@ class CITypeManager(object):
kwargs["unique_id"] = unique_key.id
kwargs['uid'] = current_user.uid
parent_ids = kwargs.pop('parent_ids', None)
ci_type = CIType.create(**kwargs)
CITypeInheritanceManager.add(parent_ids, ci_type.id)
CITypeAttributeManager.add(ci_type.id, [unique_key.id], is_required=True)
CITypeCache.clean(ci_type.name)
if current_app.config.get("USE_ACL"):
ACLManager().add_resource(ci_type.name, ResourceTypeEnum.CI)
try:
ACLManager().add_resource(ci_type.name, ResourceTypeEnum.CI)
except BadRequest:
pass
ACLManager().grant_resource_to_role(ci_type.name,
RoleEnum.CMDB_READ_ALL,
ResourceTypeEnum.CI,
@@ -211,13 +231,19 @@ class CITypeManager(object):
for table in [PreferenceTreeView, PreferenceShowAttributes, PreferenceSearchOption, CustomDashboard,
CITypeGroupItem, CITypeAttributeGroup, CITypeAttribute, CITypeUniqueConstraint, CITypeTrigger,
AutoDiscoveryCIType, CIFilterPerms]:
AutoDiscoveryCIType, CIFilterPerms, PreferenceCITypeOrder]:
for item in table.get_by(type_id=type_id, to_dict=False):
item.soft_delete(commit=False)
for item in AutoDiscoveryCI.get_by(type_id=type_id, to_dict=False):
item.delete(commit=False)
for item in CITypeInheritance.get_by(parent_id=type_id, to_dict=False):
item.delete(commit=False)
for item in CITypeInheritance.get_by(child_id=type_id, to_dict=False):
item.delete(commit=False)
db.session.commit()
ci_type.soft_delete()
@@ -230,6 +256,100 @@ class CITypeManager(object):
ACLManager().del_resource(ci_type.name, ResourceTypeEnum.CI)
class CITypeInheritanceManager(object):
cls = CITypeInheritance
@classmethod
def get_parents(cls, type_id):
return [i.parent_id for i in cls.cls.get_by(child_id=type_id, to_dict=False)]
@classmethod
def recursive_children(cls, type_id):
result = []
def _get_child(_id):
children = [i.child_id for i in cls.cls.get_by(parent_id=_id, to_dict=False)]
result.extend(children)
for child_id in children:
_get_child(child_id)
_get_child(type_id)
return result
@classmethod
def base(cls, type_id):
result = []
q = []
def _get_parents(_type_id):
parents = [i.parent_id for i in cls.cls.get_by(child_id=_type_id, to_dict=False)]
for i in parents[::-1]:
q.append(i)
try:
out = q.pop(0)
except IndexError:
return
result.append(out)
_get_parents(out)
_get_parents(type_id)
return result[::-1]
@classmethod
def add(cls, parent_ids, child_id):
rels = {}
for i in cls.cls.get_by(to_dict=False):
rels.setdefault(i.child_id, set()).add(i.parent_id)
try:
toposort_flatten(rels)
except toposort.CircularDependencyError as e:
current_app.logger.warning(str(e))
return abort(400, ErrFormat.circular_dependency_error)
for parent_id in parent_ids or []:
if parent_id == child_id:
return abort(400, ErrFormat.circular_dependency_error)
existed = cls.cls.get_by(parent_id=parent_id, child_id=child_id, first=True, to_dict=False)
if existed is None:
rels.setdefault(child_id, set()).add(parent_id)
try:
toposort_flatten(rels)
except toposort.CircularDependencyError as e:
current_app.logger.warning(str(e))
return abort(400, ErrFormat.circular_dependency_error)
cls.cls.create(parent_id=parent_id, child_id=child_id, commit=False)
db.session.commit()
@classmethod
def delete(cls, parent_id, child_id):
existed = cls.cls.get_by(parent_id=parent_id, child_id=child_id, first=True, to_dict=False)
if existed is not None:
children = cls.recursive_children(child_id) + [child_id]
for _id in children:
if CI.get_by(type_id=_id, to_dict=False, first=True) is not None:
return abort(400, ErrFormat.ci_exists_and_cannot_delete_inheritance)
attr_ids = set([i.id for _, i in CITypeAttributeManager.get_all_attributes(parent_id)])
for _id in children:
for attr_id in attr_ids:
for i in PreferenceShowAttributes.get_by(type_id=_id, attr_id=attr_id, to_dict=False):
i.soft_delete(commit=False)
db.session.commit()
existed.soft_delete()
class CITypeGroupManager(object):
cls = CITypeGroup
@@ -243,7 +363,6 @@ class CITypeGroupManager(object):
else:
resources = {i['name']: i['permissions'] for i in resources if PermEnum.READ in i.get("permissions")}
current_app.logger.info(resources)
groups = sorted(CITypeGroup.get_by(), key=lambda x: x['order'] or 0)
group_types = set()
for group in groups:
@@ -251,6 +370,7 @@ class CITypeGroupManager(object):
ci_type = CITypeCache.get(t['type_id']).to_dict()
if resources is None or (ci_type and ci_type['name'] in resources):
ci_type['permissions'] = resources[ci_type['name']] if resources is not None else None
ci_type['inherited'] = True if CITypeInheritanceManager.get_parents(ci_type['id']) else False
group.setdefault("ci_types", []).append(ci_type)
group_types.add(t["type_id"])
@@ -260,6 +380,7 @@ class CITypeGroupManager(object):
for ci_type in ci_types:
if ci_type["id"] not in group_types and (resources is None or ci_type['name'] in resources):
ci_type['permissions'] = resources.get(ci_type['name']) if resources is not None else None
ci_type['inherited'] = True if CITypeInheritanceManager.get_parents(ci_type['id']) else False
other_types['ci_types'].append(ci_type)
groups.append(other_types)
@@ -283,7 +404,10 @@ class CITypeGroupManager(object):
"""
existed = CITypeGroup.get_by_id(gid) or abort(
404, ErrFormat.ci_type_group_not_found.format("id={}".format(gid)))
if name is not None:
if name is not None and name != existed.name:
if RoleEnum.CONFIG not in session.get("acl", {}).get("parentRoles", []) and not is_app_admin("cmdb"):
return abort(403, ErrFormat.role_required.format(RoleEnum.CONFIG))
existed.update(name=name)
max_order = max([i.order or 0 for i in CITypeGroupItem.get_by(group_id=gid, to_dict=False)] or [0])
@@ -348,40 +472,62 @@ class CITypeAttributeManager(object):
return attr.name
@staticmethod
def get_attr_names_by_type_id(type_id):
return [AttributeCache.get(attr.attr_id).name for attr in CITypeAttributesCache.get(type_id)]
def get_all_attributes(type_id):
parent_ids = CITypeInheritanceManager.base(type_id)
result = []
for _type_id in parent_ids + [type_id]:
result.extend(CITypeAttributesCache.get2(_type_id))
return result
@classmethod
def get_attr_names_by_type_id(cls, type_id):
return [attr.name for _, attr in cls.get_all_attributes(type_id)]
@staticmethod
def get_attributes_by_type_id(type_id, choice_web_hook_parse=True, choice_other_parse=True):
has_config_perm = ACLManager('cmdb').has_permission(
CITypeManager.get_name_by_id(type_id), ResourceTypeEnum.CI, PermEnum.CONFIG)
attrs = CITypeAttributesCache.get(type_id)
result = list()
for attr in sorted(attrs, key=lambda x: (x.order, x.id)):
attr_dict = AttributeManager().get_attribute(attr.attr_id, choice_web_hook_parse, choice_other_parse)
attr_dict["is_required"] = attr.is_required
attr_dict["order"] = attr.order
attr_dict["default_show"] = attr.default_show
if not has_config_perm:
attr_dict.pop('choice_web_hook', None)
attr_dict.pop('choice_other', None)
parent_ids = CITypeInheritanceManager.base(type_id)
result.append(attr_dict)
result = list()
id2pos = dict()
type2name = {i: CITypeCache.get(i) for i in parent_ids}
for _type_id in parent_ids + [type_id]:
attrs = CITypeAttributesCache.get(_type_id)
for attr in sorted(attrs, key=lambda x: (x.order, x.id)):
attr_dict = AttributeManager().get_attribute(attr.attr_id, choice_web_hook_parse, choice_other_parse)
attr_dict["is_required"] = attr.is_required
attr_dict["order"] = attr.order
attr_dict["default_show"] = attr.default_show
attr_dict["inherited"] = False if _type_id == type_id else True
attr_dict["inherited_from"] = type2name.get(_type_id) and type2name[_type_id].alias
if not has_config_perm:
attr_dict.pop('choice_web_hook', None)
attr_dict.pop('choice_other', None)
if attr_dict['id'] not in id2pos:
id2pos[attr_dict['id']] = len(result)
result.append(attr_dict)
else:
result[id2pos[attr_dict['id']]] = attr_dict
return result
@staticmethod
def get_common_attributes(type_ids):
@classmethod
def get_common_attributes(cls, type_ids):
has_config_perm = False
for type_id in type_ids:
has_config_perm |= ACLManager('cmdb').has_permission(
CITypeManager.get_name_by_id(type_id), ResourceTypeEnum.CI, PermEnum.CONFIG)
result = CITypeAttribute.get_by(__func_in___key_type_id=list(map(int, type_ids)), to_dict=False)
result = {type_id: [i for _, i in cls.get_all_attributes(type_id)] for type_id in type_ids}
attr2types = {}
for i in result:
attr2types.setdefault(i.attr_id, []).append(i.type_id)
for type_id in result:
for i in result[type_id]:
attr2types.setdefault(i.id, []).append(type_id)
attrs = []
for attr_id in attr2types:
@@ -515,8 +661,18 @@ class CITypeAttributeManager(object):
attr_id = _from.get('attr_id')
from_group_id = _from.get('group_id')
to_group_id = _to.get('group_id')
from_group_name = _from.get('group_name')
to_group_name = _to.get('group_name')
order = _to.get('order')
if from_group_name:
from_group = CITypeAttributeGroup.get_by(type_id=type_id, name=from_group_name, first=True, to_dict=False)
from_group_id = from_group and from_group.id
if to_group_name:
to_group = CITypeAttributeGroup.get_by(type_id=type_id, name=to_group_name, first=True, to_dict=False)
to_group_id = to_group and to_group.id
if from_group_id != to_group_id:
if from_group_id is not None:
CITypeAttributeGroupManager.delete_item(from_group_id, attr_id)
@@ -576,6 +732,11 @@ class CITypeRelationManager(object):
ci_type_dict = CITypeCache.get(type_id).to_dict()
ci_type_dict["ctr_id"] = relation_inst.id
ci_type_dict["attributes"] = CITypeAttributeManager.get_attributes_by_type_id(ci_type_dict["id"])
attr_filter = CIFilterPermsCRUD.get_attr_filter(type_id)
if attr_filter:
ci_type_dict["attributes"] = [attr for attr in (ci_type_dict["attributes"] or [])
if attr['name'] in attr_filter]
ci_type_dict["relation_type"] = relation_inst.relation_type.name
ci_type_dict["constraint"] = relation_inst.constraint
@@ -637,15 +798,15 @@ class CITypeRelationManager(object):
current_app.logger.warning(str(e))
return abort(400, ErrFormat.circular_dependency_error)
if constraint == ConstraintEnum.Many2Many:
other_c = CITypeRelation.get_by(parent_id=p.id, constraint=ConstraintEnum.Many2Many,
to_dict=False, first=True)
other_p = CITypeRelation.get_by(child_id=c.id, constraint=ConstraintEnum.Many2Many,
to_dict=False, first=True)
if other_c and other_c.child_id != c.id:
return abort(400, ErrFormat.m2m_relation_constraint.format(p.name, other_c.child.name))
if other_p and other_p.parent_id != p.id:
return abort(400, ErrFormat.m2m_relation_constraint.format(other_p.parent.name, c.name))
# if constraint == ConstraintEnum.Many2Many:
# other_c = CITypeRelation.get_by(parent_id=p.id, constraint=ConstraintEnum.Many2Many,
# to_dict=False, first=True)
# other_p = CITypeRelation.get_by(child_id=c.id, constraint=ConstraintEnum.Many2Many,
# to_dict=False, first=True)
# if other_c and other_c.child_id != c.id:
# return abort(400, ErrFormat.m2m_relation_constraint.format(p.name, other_c.child.name))
# if other_p and other_p.parent_id != p.id:
# return abort(400, ErrFormat.m2m_relation_constraint.format(other_p.parent.name, c.name))
existed = cls._get(p.id, c.id)
if existed is not None:
@@ -720,25 +881,66 @@ class CITypeAttributeGroupManager(object):
@staticmethod
def get_by_type_id(type_id, need_other=False):
groups = CITypeAttributeGroup.get_by(type_id=type_id)
groups = sorted(groups, key=lambda x: x["order"] or 0)
grouped = list()
parent_ids = CITypeInheritanceManager.base(type_id)
groups = []
id2type = {i: CITypeCache.get(i).alias for i in parent_ids}
for _type_id in parent_ids + [type_id]:
_groups = CITypeAttributeGroup.get_by(type_id=_type_id)
_groups = sorted(_groups, key=lambda x: x["order"] or 0)
for i in _groups:
if type_id != _type_id:
i['inherited'] = True
i['inherited_from'] = id2type[_type_id]
else:
i['inherited'] = False
groups.extend(_groups)
grouped = set()
attributes = CITypeAttributeManager.get_attributes_by_type_id(type_id)
id2attr = {i['id']: i for i in attributes}
id2attr = {i.get('id'): i for i in attributes}
group2pos = dict()
attr2pos = dict()
result = []
for group in groups:
items = CITypeAttributeGroupItem.get_by(group_id=group["id"], to_dict=False)
items = sorted(items, key=lambda x: x.order or 0)
group["attributes"] = [id2attr.get(i.attr_id) for i in items if i.attr_id in id2attr]
grouped.extend([i.attr_id for i in items])
if group['name'] not in group2pos:
group_pos = len(result)
group['attributes'] = []
result.append(group)
group2pos[group['name']] = group_pos
else:
group_pos = group2pos[group['name']]
attr = None
for i in items:
if i.attr_id in id2attr:
attr = id2attr[i.attr_id]
attr['inherited'] = group['inherited']
attr['inherited_from'] = group.get('inherited_from')
result[group_pos]['attributes'].append(attr)
if i.attr_id in attr2pos:
result[attr2pos[i.attr_id][0]]['attributes'].remove(attr2pos[i.attr_id][1])
attr2pos[i.attr_id] = [group_pos, attr]
group.pop('inherited_from', None)
grouped |= set([i.attr_id for i in items])
if need_other:
grouped = set(grouped)
other_attributes = [attr for attr in attributes if attr["id"] not in grouped]
groups.append(dict(attributes=other_attributes))
result.append(dict(attributes=other_attributes))
return groups
return result
@staticmethod
def create_or_update(type_id, name, attr_order, group_order=0, is_update=False):
@@ -872,10 +1074,16 @@ class CITypeAttributeGroupManager(object):
@classmethod
def transfer(cls, type_id, _from, _to):
current_app.logger.info("CIType[{0}] {1} -> {2}".format(type_id, _from, _to))
from_group = CITypeAttributeGroup.get_by_id(_from)
if isinstance(_from, int):
from_group = CITypeAttributeGroup.get_by_id(_from)
else:
from_group = CITypeAttributeGroup.get_by(name=_from, first=True, to_dict=False)
from_group or abort(404, ErrFormat.ci_type_attribute_group_not_found.format("id={}".format(_from)))
to_group = CITypeAttributeGroup.get_by_id(_to)
if isinstance(_to, int):
to_group = CITypeAttributeGroup.get_by_id(_to)
else:
to_group = CITypeAttributeGroup.get_by(name=_to, first=True, to_dict=False)
to_group or abort(404, ErrFormat.ci_type_attribute_group_not_found.format("id={}".format(_to)))
from_order, to_order = from_group.order, to_group.order
@@ -891,97 +1099,58 @@ class CITypeAttributeGroupManager(object):
class CITypeTemplateManager(object):
@staticmethod
def __import(cls, data):
id2obj_dicts = {i['id']: i for i in data}
existed = cls.get_by(deleted=None, to_dict=False)
id2existed = {i.id: i for i in existed}
existed_ids = [i.id for i in existed]
existed_no_delete_ids = [i.id for i in existed if not i.deleted]
def __import(cls, data, unique_key='name'):
id2obj_dicts = {i[unique_key]: i for i in data}
existed = cls.get_by(to_dict=False)
id2existed = {getattr(i, unique_key): i for i in existed}
existed_ids = [getattr(i, unique_key) for i in existed]
id_map = dict()
# add
for added_id in set(id2obj_dicts.keys()) - set(existed_ids):
_id = id2obj_dicts[added_id].pop('id', None)
id2obj_dicts[added_id].pop('created_at', None)
id2obj_dicts[added_id].pop('updated_at', None)
id2obj_dicts[added_id].pop('uid', None)
if cls == CIType:
CITypeManager.add(**id2obj_dicts[added_id])
__id = CITypeManager.add(**id2obj_dicts[added_id])
CITypeCache.clean(__id)
elif cls == CITypeRelation:
CITypeRelationManager.add(id2obj_dicts[added_id].get('parent_id'),
id2obj_dicts[added_id].get('child_id'),
id2obj_dicts[added_id].get('relation_type_id'),
id2obj_dicts[added_id].get('constraint'),
)
__id = CITypeRelationManager.add(id2obj_dicts[added_id].get('parent_id'),
id2obj_dicts[added_id].get('child_id'),
id2obj_dicts[added_id].get('relation_type_id'),
id2obj_dicts[added_id].get('constraint'),
)
else:
cls.create(flush=True, **id2obj_dicts[added_id])
obj = cls.create(flush=True, **id2obj_dicts[added_id])
if cls == Attribute:
AttributeCache.clean(obj)
__id = obj.id
id_map[_id] = __id
# update
for updated_id in set(id2obj_dicts.keys()) & set(existed_ids):
_id = id2obj_dicts[updated_id].pop('id', None)
id2existed[updated_id].update(flush=True, **id2obj_dicts[updated_id])
id_map[_id] = id2existed[updated_id].id
if cls == Attribute:
AttributeCache.clean(id2existed[updated_id])
if cls == CIType:
deleted = id2existed[updated_id].deleted
CITypeManager.update(updated_id, **id2obj_dicts[updated_id])
if deleted and current_app.config.get("USE_ACL"):
type_name = id2obj_dicts[updated_id]['name']
ACLManager().add_resource(type_name, ResourceTypeEnum.CI)
ACLManager().grant_resource_to_role(type_name,
RoleEnum.CMDB_READ_ALL,
ResourceTypeEnum.CI,
permissions=[PermEnum.READ])
ACLManager().grant_resource_to_role(type_name,
current_user.username,
ResourceTypeEnum.CI)
CITypeCache.clean(id2existed[updated_id].id)
else:
id2existed[updated_id].update(flush=True, **id2obj_dicts[updated_id])
# delete
for deleted_id in set(existed_no_delete_ids) - set(id2obj_dicts.keys()):
if cls == CIType:
id2existed[deleted_id].soft_delete(flush=True)
CITypeCache.clean(deleted_id)
CITypeHistoryManager.add(CITypeOperateType.DELETE, deleted_id, change=id2existed[deleted_id].to_dict())
if current_app.config.get("USE_ACL"):
ACLManager().del_resource(id2existed[deleted_id].name, ResourceTypeEnum.CI)
else:
id2existed[deleted_id].soft_delete(flush=True)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
raise Exception(str(e))
def _import_ci_types(self, ci_types):
for i in ci_types:
i.pop("unique_key", None)
self.__import(CIType, ci_types)
def _import_ci_type_groups(self, ci_type_groups):
_ci_type_groups = copy.deepcopy(ci_type_groups)
for i in _ci_type_groups:
i.pop('ci_types', None)
self.__import(CITypeGroup, _ci_type_groups)
# import group type items
for group in ci_type_groups:
existed = CITypeGroupItem.get_by(group_id=group['id'], to_dict=False)
for i in existed:
i.soft_delete()
for order, ci_type in enumerate(group.get('ci_types') or []):
payload = dict(group_id=group['id'], type_id=ci_type['id'], order=order)
CITypeGroupItem.create(**payload)
def _import_relation_types(self, relation_types):
self.__import(RelationType, relation_types)
def _import_ci_type_relations(self, ci_type_relations):
for i in ci_type_relations:
i.pop('parent', None)
i.pop('child', None)
i.pop('relation_type', None)
self.__import(CITypeRelation, ci_type_relations)
return id_map
def _import_attributes(self, type2attributes):
attributes = [attr for type_id in type2attributes for attr in type2attributes[type_id]]
@@ -990,122 +1159,262 @@ class CITypeTemplateManager(object):
i.pop('default_show', None)
i.pop('is_required', None)
i.pop('order', None)
i.pop('choice_web_hook', None)
i.pop('choice_other', None)
i.pop('order', None)
choice_value = i.pop('choice_value', None)
if not choice_value:
i['is_choice'] = False
attrs.append((i, choice_value))
self.__import(Attribute, [i[0] for i in attrs])
attr_id_map = self.__import(Attribute, [i[0] for i in copy.deepcopy(attrs)])
for i, choice_value in attrs:
if choice_value:
AttributeManager.add_choice_values(i['id'], i['value_type'], choice_value)
if choice_value and not i.get('choice_web_hook') and not i.get('choice_other'):
AttributeManager.add_choice_values(attr_id_map.get(i['id'], i['id']), i['value_type'], choice_value)
return attr_id_map
def _import_ci_types(self, ci_types, attr_id_map):
for i in ci_types:
i.pop("unique_key", None)
i['unique_id'] = attr_id_map.get(i['unique_id'], i['unique_id'])
i['uid'] = current_user.uid
return self.__import(CIType, ci_types)
def _import_ci_type_groups(self, ci_type_groups, type_id_map):
_ci_type_groups = copy.deepcopy(ci_type_groups)
for i in _ci_type_groups:
i.pop('ci_types', None)
group_id_map = self.__import(CITypeGroup, _ci_type_groups)
# import group type items
for group in ci_type_groups:
for order, ci_type in enumerate(group.get('ci_types') or []):
payload = dict(group_id=group_id_map.get(group['id'], group['id']),
type_id=type_id_map.get(ci_type['id'], ci_type['id']),
order=order)
existed = CITypeGroupItem.get_by(group_id=payload['group_id'], type_id=payload['type_id'],
first=True, to_dict=False)
if existed is None:
CITypeGroupItem.create(flush=True, **payload)
else:
existed.update(flush=True, **payload)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
raise Exception(str(e))
def _import_relation_types(self, relation_types):
return self.__import(RelationType, relation_types)
@staticmethod
def _import_type_attributes(type2attributes):
# add type attribute
def _import_ci_type_relations(ci_type_relations, type_id_map, relation_type_id_map):
for i in ci_type_relations:
i.pop('parent', None)
i.pop('child', None)
i.pop('relation_type', None)
i['parent_id'] = type_id_map.get(i['parent_id'], i['parent_id'])
i['child_id'] = type_id_map.get(i['child_id'], i['child_id'])
i['relation_type_id'] = relation_type_id_map.get(i['relation_type_id'], i['relation_type_id'])
try:
CITypeRelationManager.add(i.get('parent_id'),
i.get('child_id'),
i.get('relation_type_id'),
i.get('constraint'),
)
except BadRequest:
pass
@staticmethod
def _import_type_attributes(type2attributes, type_id_map, attr_id_map):
for type_id in type2attributes:
CITypeAttributesCache.clean(type_id_map.get(int(type_id), type_id))
for type_id in type2attributes:
existed = CITypeAttribute.get_by(type_id=type_id, to_dict=False)
existed_attr_ids = {i.attr_id: i for i in existed}
new_attr_ids = {i['id']: i for i in type2attributes[type_id]}
existed = CITypeAttributesCache.get2(type_id_map.get(int(type_id), type_id))
existed_attr_names = {attr.name: ta for ta, attr in existed}
handled = set()
for attr in type2attributes[type_id]:
payload = dict(type_id=type_id,
attr_id=attr['id'],
payload = dict(type_id=type_id_map.get(int(type_id), type_id),
attr_id=attr_id_map.get(attr['id'], attr['id']),
default_show=attr['default_show'],
is_required=attr['is_required'],
order=attr['order'])
if attr['id'] not in existed_attr_ids: # new
CITypeAttribute.create(flush=True, **payload)
else: # update
existed_attr_ids[attr['id']].update(**payload)
if attr['name'] not in handled:
if attr['name'] not in existed_attr_names: # new
CITypeAttribute.create(flush=True, **payload)
else: # update
existed_attr_names[attr['name']].update(flush=True, **payload)
# delete
for i in existed:
if i.attr_id not in new_attr_ids:
i.soft_delete()
handled.add(attr['name'])
try:
db.session.commit()
except Exception as e:
db.session.rollback()
raise Exception(str(e))
for type_id in type2attributes:
CITypeAttributesCache.clean(type_id_map.get(int(type_id), type_id))
@staticmethod
def _import_attribute_group(type2attribute_group):
def _import_attribute_group(type2attribute_group, type_id_map, attr_id_map):
for type_id in type2attribute_group:
existed = CITypeAttributeGroup.get_by(type_id=type_id, to_dict=False)
for i in existed:
i.soft_delete()
for group in type2attribute_group[type_id] or []:
_group = copy.deepcopy(group)
_group.pop('attributes', None)
_group.pop('id', None)
new = CITypeAttributeGroup.create(**_group)
existed = CITypeAttributeGroup.get_by(name=_group['name'],
type_id=type_id_map.get(_group['type_id'], _group['type_id']),
first=True, to_dict=False)
if existed is None:
_group['type_id'] = type_id_map.get(_group['type_id'], _group['type_id'])
existed = CITypeAttributeGroupItem.get_by(group_id=new.id, to_dict=False)
for i in existed:
i.soft_delete()
existed = CITypeAttributeGroup.create(flush=True, **_group)
for order, attr in enumerate(group['attributes'] or []):
CITypeAttributeGroupItem.create(group_id=new.id, attr_id=attr['id'], order=order)
item_existed = CITypeAttributeGroupItem.get_by(group_id=existed.id,
attr_id=attr_id_map.get(attr['id'], attr['id']),
first=True, to_dict=False)
if item_existed is None:
CITypeAttributeGroupItem.create(group_id=existed.id,
attr_id=attr_id_map.get(attr['id'], attr['id']),
order=order)
else:
item_existed.update(flush=True, order=order)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
raise Exception(str(e))
@staticmethod
def _import_auto_discovery_rules(rules):
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD
for rule in rules:
ci_type = CITypeCache.get(rule.pop('type_name', None))
adr = rule.pop('adr', {}) or {}
if ci_type:
rule['type_id'] = ci_type.id
if rule.get('adr_name'):
ad_rule = AutoDiscoveryRuleCRUD.get_by_name(rule.pop("adr_name"))
adr.pop('created_at', None)
adr.pop('updated_at', None)
adr.pop('id', None)
if ad_rule:
rule['adr_id'] = ad_rule.id
ad_rule.update(**adr)
elif adr:
ad_rule = AutoDiscoveryRuleCRUD().add(**adr)
rule['adr_id'] = ad_rule.id
else:
continue
rule.pop("id", None)
rule.pop("created_at", None)
rule.pop("updated_at", None)
rule['uid'] = current_user.uid
try:
AutoDiscoveryCITypeCRUD.add(**rule)
except Exception as e:
current_app.logger.warning("import auto discovery rules failed: {}".format(e))
existed = False
for i in AutoDiscoveryCIType.get_by(type_id=ci_type.id, adr_id=rule['adr_id'], to_dict=False):
if ((i.extra_option or {}).get('alias') or None) == (
(rule.get('extra_option') or {}).get('alias') or None):
existed = True
AutoDiscoveryCITypeCRUD().update(i.id, **rule)
break
if not existed:
try:
AutoDiscoveryCITypeCRUD().add(**rule)
except Exception as e:
current_app.logger.warning("import auto discovery rules failed: {}".format(e))
@staticmethod
def _import_icons(icons):
from api.lib.common_setting.upload_file import CommonFileCRUD
for icon_name in icons:
if icons[icon_name]:
try:
CommonFileCRUD().save_str_to_file(icon_name, icons[icon_name])
except Exception as e:
current_app.logger.warning("save icon failed: {}".format(e))
def import_template(self, tpt):
import time
s = time.time()
self._import_attributes(tpt.get('type2attributes') or {})
attr_id_map = self._import_attributes(tpt.get('type2attributes') or {})
current_app.logger.info('import attributes cost: {}'.format(time.time() - s))
s = time.time()
self._import_ci_types(tpt.get('ci_types') or [])
ci_type_id_map = self._import_ci_types(tpt.get('ci_types') or [], attr_id_map)
current_app.logger.info('import ci_types cost: {}'.format(time.time() - s))
s = time.time()
self._import_ci_type_groups(tpt.get('ci_type_groups') or [])
self._import_ci_type_groups(tpt.get('ci_type_groups') or [], ci_type_id_map)
current_app.logger.info('import ci_type_groups cost: {}'.format(time.time() - s))
s = time.time()
self._import_relation_types(tpt.get('relation_types') or [])
relation_type_id_map = self._import_relation_types(tpt.get('relation_types') or [])
current_app.logger.info('import relation_types cost: {}'.format(time.time() - s))
s = time.time()
self._import_ci_type_relations(tpt.get('ci_type_relations') or [])
self._import_ci_type_relations(tpt.get('ci_type_relations') or [], ci_type_id_map, relation_type_id_map)
current_app.logger.info('import ci_type_relations cost: {}'.format(time.time() - s))
s = time.time()
self._import_type_attributes(tpt.get('type2attributes') or {})
self._import_type_attributes(tpt.get('type2attributes') or {}, ci_type_id_map, attr_id_map)
current_app.logger.info('import type2attributes cost: {}'.format(time.time() - s))
s = time.time()
self._import_attribute_group(tpt.get('type2attribute_group') or {})
self._import_attribute_group(tpt.get('type2attribute_group') or {}, ci_type_id_map, attr_id_map)
current_app.logger.info('import type2attribute_group cost: {}'.format(time.time() - s))
s = time.time()
self._import_auto_discovery_rules(tpt.get('ci_type_auto_discovery_rules') or [])
current_app.logger.info('import ci_type_auto_discovery_rules cost: {}'.format(time.time() - s))
s = time.time()
self._import_icons(tpt.get('icons') or {})
current_app.logger.info('import icons cost: {}'.format(time.time() - s))
@staticmethod
def export_template():
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD
from api.lib.common_setting.upload_file import CommonFileCRUD
tpt = dict(
ci_types=CITypeManager.get_ci_types(),
ci_type_groups=CITypeGroupManager.get(),
relation_types=[i.to_dict() for i in RelationTypeManager.get_all()],
ci_type_relations=CITypeRelationManager.get(),
ci_type_auto_discovery_rules=list(),
type2attributes=dict(),
type2attribute_group=dict(),
icons=dict()
)
def get_icon_value(icon):
try:
return CommonFileCRUD().get_file_binary_str(icon)
except:
return ""
ad_rules = AutoDiscoveryCITypeCRUD.get_all()
rules = []
@@ -1116,23 +1425,91 @@ class CITypeTemplateManager(object):
if r.get('adr_id'):
adr = AutoDiscoveryRuleCRUD.get_by_id(r.pop('adr_id'))
r['adr_name'] = adr and adr.name
r['adr'] = adr and adr.to_dict() or {}
icon_url = r['adr'].get('option', {}).get('icon', {}).get('url')
if icon_url and icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
rules.append(r)
tpt = dict(
ci_types=CITypeManager.get_ci_types(),
ci_type_groups=CITypeGroupManager.get(),
relation_types=[i.to_dict() for i in RelationTypeManager.get_all()],
ci_type_relations=CITypeRelationManager.get(),
ci_type_auto_discovery_rules=rules,
type2attributes=dict(),
type2attribute_group=dict()
)
tpt['ci_type_auto_discovery_rules'] = rules
for ci_type in tpt['ci_types']:
if ci_type['icon'] and len(ci_type['icon'].split('$$')) > 3:
icon_url = ci_type['icon'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attributes'][ci_type['id']] = CITypeAttributeManager.get_attributes_by_type_id(
ci_type['id'], choice_web_hook_parse=False, choice_other_parse=False)
for attr in tpt['type2attributes'][ci_type['id']]:
for i in (attr.get('choice_value') or []):
if (i[1] or {}).get('icon', {}).get('url') and len(i[1]['icon']['url'].split('$$')) > 3:
icon_url = i[1]['icon']['url'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attribute_group'][ci_type['id']] = CITypeAttributeGroupManager.get_by_type_id(ci_type['id'])
return tpt
@staticmethod
def export_template_by_type(type_id):
ci_type = CITypeCache.get(type_id) or abort(404, ErrFormat.ci_type_not_found2.format("id={}".format(type_id)))
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryCITypeCRUD
from api.lib.cmdb.auto_discovery.auto_discovery import AutoDiscoveryRuleCRUD
from api.lib.common_setting.upload_file import CommonFileCRUD
tpt = dict(
ci_types=CITypeManager.get_ci_types(type_name=ci_type.name, like=False),
ci_type_auto_discovery_rules=list(),
type2attributes=dict(),
type2attribute_group=dict(),
icons=dict()
)
def get_icon_value(icon):
try:
return CommonFileCRUD().get_file_binary_str(icon)
except:
return ""
ad_rules = AutoDiscoveryCITypeCRUD.get_by_type_id(ci_type.id)
rules = []
for r in ad_rules:
r = r.to_dict()
r['type_name'] = ci_type and ci_type.name
if r.get('adr_id'):
adr = AutoDiscoveryRuleCRUD.get_by_id(r.pop('adr_id'))
r['adr_name'] = adr and adr.name
r['adr'] = adr and adr.to_dict() or {}
icon_url = r['adr'].get('option', {}).get('icon', {}).get('url')
if icon_url and icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
rules.append(r)
tpt['ci_type_auto_discovery_rules'] = rules
for ci_type in tpt['ci_types']:
if ci_type['icon'] and len(ci_type['icon'].split('$$')) > 3:
icon_url = ci_type['icon'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attributes'][ci_type['id']] = CITypeAttributeManager.get_attributes_by_type_id(
ci_type['id'], choice_web_hook_parse=False, choice_other_parse=False)
for attr in tpt['type2attributes'][ci_type['id']]:
for i in (attr.get('choice_value') or []):
if (i[1] or {}).get('icon', {}).get('url') and len(i[1]['icon']['url'].split('$$')) > 3:
icon_url = i[1]['icon']['url'].split('$$')[3]
if icon_url not in tpt['icons']:
tpt['icons'][icon_url] = get_icon_value(icon_url)
tpt['type2attribute_group'][ci_type['id']] = CITypeAttributeGroupManager.get_by_type_id(ci_type['id'])
return tpt

View File

@@ -69,6 +69,7 @@ class ResourceTypeEnum(BaseEnum):
CI_TYPE_RELATION = "CITypeRelation" # create/delete/grant
RELATION_VIEW = "RelationView" # read/update/delete/grant
CI_FILTER = "CIFilter" # read
PAGE = "page" # read
class PermEnum(BaseEnum):

View File

@@ -114,6 +114,8 @@ class CIFilterPermsCRUD(DBMixin):
obj.soft_delete()
return obj
else:
if not kwargs.get('ci_filter') and not kwargs.get('attr_filter'):
return
@@ -143,11 +145,14 @@ class CIFilterPermsCRUD(DBMixin):
first=True, to_dict=False)
if obj is not None:
resource = None
if current_app.config.get('USE_ACL'):
ACLManager().del_resource(str(obj.id), ResourceTypeEnum.CI_FILTER)
resource = ACLManager().del_resource(str(obj.id), ResourceTypeEnum.CI_FILTER)
obj.soft_delete()
return resource
def has_perm_for_ci(arg_name, resource_type, perm, callback=None, app=None):
def decorator_has_perm(func):

View File

@@ -14,6 +14,8 @@ from api.lib.cmdb.attribute import AttributeManager
from api.lib.cmdb.cache import AttributeCache
from api.lib.cmdb.cache import CITypeAttributesCache
from api.lib.cmdb.cache import CITypeCache
from api.lib.cmdb.cache import CMDBCounterCache
from api.lib.cmdb.ci_type import CITypeAttributeManager
from api.lib.cmdb.const import ConstraintEnum
from api.lib.cmdb.const import PermEnum
from api.lib.cmdb.const import ResourceTypeEnum
@@ -24,6 +26,7 @@ from api.lib.exception import AbortException
from api.lib.perm.acl.acl import ACLManager
from api.models.cmdb import CITypeAttribute
from api.models.cmdb import CITypeRelation
from api.models.cmdb import PreferenceCITypeOrder
from api.models.cmdb import PreferenceRelationView
from api.models.cmdb import PreferenceSearchOption
from api.models.cmdb import PreferenceShowAttributes
@@ -38,13 +41,22 @@ class PreferenceManager(object):
@staticmethod
def get_types(instance=False, tree=False):
ci_type_order = sorted(PreferenceCITypeOrder.get_by(uid=current_user.uid, to_dict=False), key=lambda x: x.order)
types = db.session.query(PreferenceShowAttributes.type_id).filter(
PreferenceShowAttributes.uid == current_user.uid).filter(
PreferenceShowAttributes.deleted.is_(False)).group_by(
PreferenceShowAttributes.type_id).all() if instance else []
types = sorted(types, key=lambda x: {i.type_id: idx for idx, i in enumerate(
ci_type_order) if not i.is_tree}.get(x.type_id, 1))
tree_types = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=False) if tree else []
type_ids = set([i.type_id for i in types + tree_types])
tree_types = sorted(tree_types, key=lambda x: {i.type_id: idx for idx, i in enumerate(
ci_type_order) if i.is_tree}.get(x.type_id, 1))
type_ids = [i.type_id for i in types + tree_types]
if types and tree_types:
type_ids = set(type_ids)
return [CITypeCache.get(type_id).to_dict() for type_id in type_ids]
@@ -59,32 +71,36 @@ class PreferenceManager(object):
:param tree:
:return:
"""
result = dict(self=dict(instance=[], tree=[], type_id2subs_time=dict()),
type_id2users=dict())
result = dict(self=dict(instance=[], tree=[], type_id2subs_time=dict()))
result.update(CMDBCounterCache.get_sub_counter())
ci_type_order = sorted(PreferenceCITypeOrder.get_by(uid=current_user.uid, to_dict=False), key=lambda x: x.order)
if instance:
types = db.session.query(PreferenceShowAttributes.type_id,
PreferenceShowAttributes.uid, PreferenceShowAttributes.created_at).filter(
PreferenceShowAttributes.deleted.is_(False)).group_by(
PreferenceShowAttributes.deleted.is_(False)).filter(
PreferenceShowAttributes.uid == current_user.uid).group_by(
PreferenceShowAttributes.uid, PreferenceShowAttributes.type_id)
for i in types:
if i.uid == current_user.uid:
result['self']['instance'].append(i.type_id)
if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")):
result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['self']['instance'].append(i.type_id)
if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")):
result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['type_id2users'].setdefault(i.type_id, []).append(i.uid)
instance_order = [i.type_id for i in ci_type_order if not i.is_tree]
if len(instance_order) == len(result['self']['instance']):
result['self']['instance'] = instance_order
if tree:
types = PreferenceTreeView.get_by(to_dict=False)
types = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=False)
for i in types:
if i.uid == current_user.uid:
result['self']['tree'].append(i.type_id)
if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")):
result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['self']['tree'].append(i.type_id)
if str(i.created_at) > str(result['self']['type_id2subs_time'].get(i.type_id, "")):
result['self']['type_id2subs_time'][i.type_id] = i.created_at
result['type_id2users'].setdefault(i.type_id, [])
if i.uid not in result['type_id2users'][i.type_id]:
result['type_id2users'][i.type_id].append(i.uid)
tree_order = [i.type_id for i in ci_type_order if i.is_tree]
if len(tree_order) == len(result['self']['tree']):
result['self']['tree'] = tree_order
return result
@@ -98,8 +114,8 @@ class PreferenceManager(object):
CITypeAttribute, CITypeAttribute.attr_id == PreferenceShowAttributes.attr_id).filter(
PreferenceShowAttributes.uid == current_user.uid).filter(
PreferenceShowAttributes.type_id == type_id).filter(
PreferenceShowAttributes.deleted.is_(False)).filter(CITypeAttribute.deleted.is_(False)).filter(
CITypeAttribute.type_id == type_id).all()
PreferenceShowAttributes.deleted.is_(False)).filter(CITypeAttribute.deleted.is_(False)).group_by(
CITypeAttribute.attr_id).all()
result = []
for i in sorted(attrs, key=lambda x: x.PreferenceShowAttributes.order):
@@ -109,17 +125,16 @@ class PreferenceManager(object):
is_subscribed = True
if not attrs:
attrs = db.session.query(CITypeAttribute).filter(
CITypeAttribute.type_id == type_id).filter(
CITypeAttribute.deleted.is_(False)).filter(
CITypeAttribute.default_show.is_(True)).order_by(CITypeAttribute.order)
result = [i.attr.to_dict() for i in attrs]
result = CITypeAttributeManager.get_attributes_by_type_id(type_id,
choice_web_hook_parse=False,
choice_other_parse=False)
result = [i for i in result if i['default_show']]
is_subscribed = False
for i in result:
if i["is_choice"]:
i.update(dict(choice_value=AttributeManager.get_choice_values(
i["id"], i["value_type"], i["choice_web_hook"], i.get("choice_other"))))
i["id"], i["value_type"], i.get("choice_web_hook"), i.get("choice_other"))))
return is_subscribed, result
@@ -151,9 +166,22 @@ class PreferenceManager(object):
if i.attr_id not in attr_dict:
i.soft_delete()
if not existed_all and attr_order:
cls.add_ci_type_order_item(type_id, is_tree=False)
elif not PreferenceShowAttributes.get_by(type_id=type_id, uid=current_user.uid, to_dict=False):
cls.delete_ci_type_order_item(type_id, is_tree=False)
@staticmethod
def get_tree_view():
ci_type_order = sorted(PreferenceCITypeOrder.get_by(uid=current_user.uid, is_tree=True, to_dict=False),
key=lambda x: x.order)
res = PreferenceTreeView.get_by(uid=current_user.uid, to_dict=True)
if ci_type_order:
res = sorted(res, key=lambda x: {ii.type_id: idx for idx, ii in enumerate(
ci_type_order)}.get(x['type_id'], 1))
for item in res:
if item["levels"]:
ci_type = CITypeCache.get(item['type_id']).to_dict()
@@ -172,8 +200,8 @@ class PreferenceManager(object):
return res
@staticmethod
def create_or_update_tree_view(type_id, levels):
@classmethod
def create_or_update_tree_view(cls, type_id, levels):
attrs = CITypeAttributesCache.get(type_id)
for idx, i in enumerate(levels):
for attr in attrs:
@@ -185,9 +213,12 @@ class PreferenceManager(object):
if existed is not None:
if not levels:
existed.soft_delete()
cls.delete_ci_type_order_item(type_id, is_tree=True)
return existed
return existed.update(levels=levels)
elif levels:
cls.add_ci_type_order_item(type_id, is_tree=True)
return PreferenceTreeView.create(levels=levels, type_id=type_id, uid=current_user.uid)
@staticmethod
@@ -356,6 +387,9 @@ class PreferenceManager(object):
for i in PreferenceTreeView.get_by(type_id=type_id, uid=uid, to_dict=False):
i.soft_delete()
for i in PreferenceCITypeOrder.get_by(type_id=type_id, uid=uid, to_dict=False):
i.soft_delete()
@staticmethod
def can_edit_relation(parent_id, child_id):
views = PreferenceRelationView.get_by(to_dict=False)
@@ -381,3 +415,36 @@ class PreferenceManager(object):
return False
return True
@staticmethod
def add_ci_type_order_item(type_id, is_tree=False):
max_order = PreferenceCITypeOrder.get_by(
uid=current_user.uid, is_tree=is_tree, only_query=True).order_by(PreferenceCITypeOrder.order.desc()).first()
order = (max_order and max_order.order + 1) or 1
PreferenceCITypeOrder.create(type_id=type_id, is_tree=is_tree, uid=current_user.uid, order=order)
@staticmethod
def delete_ci_type_order_item(type_id, is_tree=False):
existed = PreferenceCITypeOrder.get_by(uid=current_user.uid, type_id=type_id, is_tree=is_tree,
first=True, to_dict=False)
existed and existed.soft_delete()
@staticmethod
def upsert_ci_type_order(type_ids, is_tree=False):
for idx, type_id in enumerate(type_ids):
order = idx + 1
existed = PreferenceCITypeOrder.get_by(uid=current_user.uid, type_id=type_id, is_tree=is_tree,
to_dict=False, first=True)
if existed is not None:
existed.update(order=order, flush=True)
else:
PreferenceCITypeOrder.create(uid=current_user.uid, type_id=type_id, is_tree=is_tree, order=order,
flush=True)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
current_app.logger.error("upsert citype order failed: {}".format(e))
return abort(400, ErrFormat.unknown_error)

View File

@@ -1,101 +1,140 @@
# -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
from api.lib.resp_format import CommonErrFormat
class ErrFormat(CommonErrFormat):
invalid_relation_type = "无效的关系类型: {}"
ci_type_not_found = "模型不存在!"
argument_attributes_must_be_list = "参数 attributes 类型必须是列表"
argument_file_not_found = "文件似乎并未上传"
ci_type_config = _l("CI Model") # 模型配置
attribute_not_found = "属性 {} 不存在!"
attribute_is_unique_id = "该属性是模型的唯一标识,不能被删除!"
attribute_is_ref_by_type = "该属性被模型 {} 引用, 不能删除!"
attribute_value_type_cannot_change = "属性的值类型不允许修改!"
attribute_list_value_cannot_change = "多值不被允许修改!"
attribute_index_cannot_change = "修改索引 非管理员不被允许!"
attribute_index_change_failed = "索引切换失败!"
invalid_choice_values = "预定义值的类型不对!"
attribute_name_duplicate = "重复的属性名 {}"
add_attribute_failed = "创建属性 {} 失败!"
update_attribute_failed = "修改属性 {} 失败!"
cannot_edit_attribute = "您没有权限修改该属性!"
cannot_delete_attribute = "目前只允许 属性创建人、管理员 删除属性!"
attribute_name_cannot_be_builtin = "属性字段名不能是内置字段: id, _id, ci_id, type, _type, ci_type"
attribute_choice_other_invalid = "预定义值: 其他模型请求参数不合法!"
invalid_relation_type = _l("Invalid relation type: {}") # 无效的关系类型: {}
ci_type_not_found = _l("CIType is not found") # 模型不存在!
ci_not_found = "CI {} 不存在"
unique_constraint = "多属性联合唯一校验不通过: {}"
unique_value_not_found = "模型的主键 {} 不存在!"
unique_key_required = "主键字段 {} 缺失"
ci_is_already_existed = "CI 已经存在!"
relation_constraint = "关系约束: {}, 校验失败 "
m2m_relation_constraint = "多对多关系 限制: 模型 {} <-> {} 已经存在多对多关系!"
relation_not_found = "CI关系: {} 不存在"
ci_search_Parentheses_invalid = "搜索表达式里小括号前不支持: 或、非"
# 参数 attributes 类型必须是列表
argument_attributes_must_be_list = _l("The type of parameter attributes must be a list")
argument_file_not_found = _l("The file doesn't seem to be uploaded") # 文件似乎并未上传
ci_type_not_found2 = "模型 {} 不存在"
ci_type_is_already_existed = "模型 {} 已经存在"
unique_key_not_define = "主键未定义或者已被删除"
only_owner_can_delete = "只有创建人才能删除它!"
ci_exists_and_cannot_delete_type = "因为CI已经存在不能删除模型"
ci_relation_view_exists_and_cannot_delete_type = "因为关系视图 {} 引用了该模型,不能删除模型"
ci_type_group_not_found = "模型分组 {} 不存在"
ci_type_group_exists = "模型分组 {} 已经存在"
ci_type_relation_not_found = "模型关系 {} 不存在"
ci_type_attribute_group_duplicate = "属性分组 {} 已存在"
ci_type_attribute_group_not_found = "属性分组 {} 不存在"
ci_type_group_attribute_not_found = "属性组<{0}> - 属性<{1}> 不存在"
unique_constraint_duplicate = "唯一约束已经存在!"
unique_constraint_invalid = "唯一约束的属性不能是 JSON 和 多值"
ci_type_trigger_duplicate = "重复的触发器"
ci_type_trigger_not_found = "触发器 {} 不存在"
attribute_not_found = _l("Attribute {} does not exist!") # 属性 {} 不存在!
attribute_is_unique_id = _l(
"This attribute is the unique identifier of the model and cannot be deleted!") # 该属性是模型的唯一标识,不能被删除!
attribute_is_ref_by_type = _l(
"This attribute is referenced by model {} and cannot be deleted!") # 该属性被模型 {} 引用, 不能删除!
attribute_value_type_cannot_change = _l(
"The value type of the attribute is not allowed to be modified!") # 属性的值类型不允许修改!
attribute_list_value_cannot_change = _l("Multiple values are not allowed to be modified!") # 多值不被允许修改!
# 修改索引 非管理员不被允许!
attribute_index_cannot_change = _l("Modifying the index is not allowed for non-administrators!")
attribute_index_change_failed = _l("Index switching failed!") # 索引切换失败!
invalid_choice_values = _l("The predefined value is of the wrong type!") # 预定义值的类型不对!
attribute_name_duplicate = _l("Duplicate attribute name {}") # 重复的属性名 {}
add_attribute_failed = _l("Failed to create attribute {}!") # 创建属性 {} 失败!
update_attribute_failed = _l("Modify attribute {} failed!") # 修改属性 {} 失败!
cannot_edit_attribute = _l("You do not have permission to modify this attribute!") # 您没有权限修改该属性!
cannot_delete_attribute = _l(
"Only creators and administrators are allowed to delete attributes!") # 目前只允许 属性创建人、管理员 删除属性!
# 属性字段名不能是内置字段: id, _id, ci_id, type, _type, ci_type
attribute_name_cannot_be_builtin = _l(
"Attribute field names cannot be built-in fields: id, _id, ci_id, type, _type, ci_type")
attribute_choice_other_invalid = _l(
"Predefined value: Other model request parameters are illegal!") # 预定义值: 其他模型请求参数不合法!
record_not_found = "操作记录 {} 不存在"
cannot_delete_unique = "不能删除唯一标识"
cannot_delete_default_order_attr = "不能删除默认排序的属性"
ci_not_found = _l("CI {} does not exist") # CI {} 不存在
unique_constraint = _l("Multiple attribute joint unique verification failed: {}") # 多属性联合唯一校验不通过: {}
unique_value_not_found = _l("The model's primary key {} does not exist!") # 模型的主键 {} 不存在!
unique_key_required = _l("Primary key {} is missing") # 主键字段 {} 缺失
ci_is_already_existed = _l("CI already exists!") # CI 已经存在!
relation_constraint = _l("Relationship constraint: {}, verification failed") # 关系约束: {}, 校验失败
# 多对多关系 限制: 模型 {} <-> {} 已经存在多对多关系!
m2m_relation_constraint = _l(
"Many-to-many relationship constraint: Model {} <-> {} already has a many-to-many relationship!")
preference_relation_view_node_required = "没有选择节点"
preference_search_option_not_found = "该搜索选项不存在!"
preference_search_option_exists = "该搜索选项命名重复!"
relation_not_found = _l("CI relationship: {} does not exist") # CI关系: {} 不存在
relation_type_exists = "关系类型 {} 已经存在"
relation_type_not_found = "关系类型 {} 不存在"
# 搜索表达式里小括号前不支持: 或、非
ci_search_Parentheses_invalid = _l("In search expressions, not supported before parentheses: or, not")
attribute_value_invalid = "无效的属性值: {}"
attribute_value_invalid2 = "{} 无效的值: {}"
not_in_choice_values = "{} 不在预定义值里"
attribute_value_unique_required = "属性 {} 的值必须是唯一的, 当前值 {} 已存在"
attribute_value_required = "属性 {} 值必须存在"
attribute_value_unknown_error = "新增或者修改属性值未知错误: {}"
ci_type_not_found2 = _l("Model {} does not exist") # 模型 {} 不存在
ci_type_is_already_existed = _l("Model {} already exists") # 模型 {} 已经存在
unique_key_not_define = _l("The primary key is undefined or has been deleted") # 主键未定义或者已被删除
only_owner_can_delete = _l("Only the creator can delete it!") # 只有创建人才能删除它!
ci_exists_and_cannot_delete_type = _l(
"The model cannot be deleted because the CI already exists") # 因为CI已经存在不能删除模型
ci_exists_and_cannot_delete_inheritance = _l(
"The inheritance cannot be deleted because the CI already exists") # 因为CI已经存在不能删除继承关系
custom_name_duplicate = "订制名重复"
# 因为关系视图 {} 引用了该模型,不能删除模型
ci_relation_view_exists_and_cannot_delete_type = _l(
"The model cannot be deleted because the model is referenced by the relational view {}")
ci_type_group_not_found = _l("Model group {} does not exist") # 模型分组 {} 不存在
ci_type_group_exists = _l("Model group {} already exists") # 模型分组 {} 已经存在
ci_type_relation_not_found = _l("Model relationship {} does not exist") # 模型关系 {} 不存在
ci_type_attribute_group_duplicate = _l("Attribute group {} already exists") # 属性分组 {} 已存在
ci_type_attribute_group_not_found = _l("Attribute group {} does not exist") # 属性分组 {} 不存在
# 属性组<{0}> - 属性<{1}> 不存在
ci_type_group_attribute_not_found = _l("Attribute group <{0}> - attribute <{1}> does not exist")
unique_constraint_duplicate = _l("The unique constraint already exists!") # 唯一约束已经存在!
# 唯一约束的属性不能是 JSON 和 多值
unique_constraint_invalid = _l("Uniquely constrained attributes cannot be JSON and multi-valued")
ci_type_trigger_duplicate = _l("Duplicated trigger") # 重复的触发器
ci_type_trigger_not_found = _l("Trigger {} does not exist") # 触发器 {} 不存在
limit_ci_type = "模型数超过限制: {}"
limit_ci = "CI数超过限制: {}"
record_not_found = _l("Operation record {} does not exist") # 操作记录 {} 不存在
cannot_delete_unique = _l("Unique identifier cannot be deleted") # 不能删除唯一标识
cannot_delete_default_order_attr = _l("Cannot delete default sorted attributes") # 不能删除默认排序的属性
adr_duplicate = "自动发现规则: {} 已经存在!"
adr_not_found = "自动发现规则: {} 不存在!"
adr_referenced = "该自动发现规则被模型引用, 不能删除!"
ad_duplicate = "自动发现规则的应用不能重复定义!"
ad_not_found = "您要修改的自动发现: {} 不存在!"
ad_not_unique_key = "属性字段没有包括唯一标识: {}"
adc_not_found = "自动发现的实例不存在!"
adt_not_found = "模型并未关联该自动发现!"
adt_secret_no_permission = "只有创建人才能修改Secret!"
cannot_delete_adt = "该规则已经有自动发现的实例, 不能被删除!"
adr_default_ref_once = "该默认的自动发现规则 已经被模型 {} 引用!"
adr_unique_key_required = "unique_key方法必须返回非空字符串!"
adr_plugin_attributes_list_required = "attributes方法必须返回的是list"
adr_plugin_attributes_list_no_empty = "attributes方法返回的list不能为空!"
adt_target_all_no_permission = "只有管理员才可以定义执行机器为: 所有节点!"
adt_target_expr_no_permission = "执行机器权限检查不通过: {}"
preference_relation_view_node_required = _l("No node selected") # 没有选择节点
preference_search_option_not_found = _l("This search option does not exist!") # 该搜索选项不存在!
preference_search_option_exists = _l("This search option has a duplicate name!") # 该搜索选项命名重复!
ci_filter_name_cannot_be_empty = "CI过滤授权 必须命名!"
ci_filter_perm_cannot_or_query = "CI过滤授权 暂时不支持 或 查询"
ci_filter_perm_attr_no_permission = "您没有属性 {} 的操作权限!"
ci_filter_perm_ci_no_permission = "您没有该CI的操作权限!"
relation_type_exists = _l("Relationship type {} already exists") # 关系类型 {} 已经存在
relation_type_not_found = _l("Relationship type {} does not exist") # 关系类型 {} 不存在
password_save_failed = "保存密码失败: {}"
password_load_failed = "获取密码失败: {}"
attribute_value_invalid = _l("Invalid attribute value: {}") # 无效的属性值: {}
attribute_value_invalid2 = _l("{} Invalid value: {}") # {} 无效的值: {}
not_in_choice_values = _l("{} is not in the predefined values") # {} 不在预定义值里
# 属性 {} 的值必须是唯一的, 当前值 {} 已存在
attribute_value_unique_required = _l("The value of attribute {} must be unique, {} already exists")
attribute_value_required = _l("Attribute {} value must exist") # 属性 {} 值必须存在
# 新增或者修改属性值未知错误: {}
attribute_value_unknown_error = _l("Unknown error when adding or modifying attribute value: {}")
custom_name_duplicate = _l("Duplicate custom name") # 订制名重复
limit_ci_type = _l("Number of models exceeds limit: {}") # 模型数超过限制: {}
limit_ci = _l("The number of CIs exceeds the limit: {}") # CI数超过限制: {}
adr_duplicate = _l("Auto-discovery rule: {} already exists!") # 自动发现规则: {} 已经存在!
adr_not_found = _l("Auto-discovery rule: {} does not exist!") # 自动发现规则: {} 不存在!
# 该自动发现规则被模型引用, 不能删除!
adr_referenced = _l("This auto-discovery rule is referenced by the model and cannot be deleted!")
# 自动发现规则的应用不能重复定义!
ad_duplicate = _l("The application of auto-discovery rules cannot be defined repeatedly!")
ad_not_found = _l("The auto-discovery you want to modify: {} does not exist!") # 您要修改的自动发现: {} 不存在!
ad_not_unique_key = _l("Attribute does not include unique identifier: {}") # 属性字段没有包括唯一标识: {}
adc_not_found = _l("The auto-discovery instance does not exist!") # 自动发现的实例不存在!
adt_not_found = _l("The model is not associated with this auto-discovery!") # 模型并未关联该自动发现!
adt_secret_no_permission = _l("Only the creator can modify the Secret!") # 只有创建人才能修改Secret!
# 该规则已经有自动发现的实例, 不能被删除!
cannot_delete_adt = _l("This rule already has auto-discovery instances and cannot be deleted!")
# 该默认的自动发现规则 已经被模型 {} 引用!
adr_default_ref_once = _l("The default auto-discovery rule is already referenced by model {}!")
# unique_key方法必须返回非空字符串!
adr_unique_key_required = _l("The unique_key method must return a non-empty string!")
adr_plugin_attributes_list_required = _l("The attributes method must return a list") # attributes方法必须返回的是list
# attributes方法返回的list不能为空!
adr_plugin_attributes_list_no_empty = _l("The list returned by the attributes method cannot be empty!")
# 只有管理员才可以定义执行机器为: 所有节点!
adt_target_all_no_permission = _l("Only administrators can define execution targets as: all nodes!")
adt_target_expr_no_permission = _l("Execute targets permission check failed: {}") # 执行机器权限检查不通过: {}
ci_filter_name_cannot_be_empty = _l("CI filter authorization must be named!") # CI过滤授权 必须命名!
ci_filter_perm_cannot_or_query = _l(
"CI filter authorization is currently not supported or query") # CI过滤授权 暂时不支持 或 查询
# 您没有属性 {} 的操作权限!
ci_filter_perm_attr_no_permission = _l("You do not have permission to operate attribute {}!")
ci_filter_perm_ci_no_permission = _l("You do not have permission to operate this CI!") # 您没有该CI的操作权限!
password_save_failed = _l("Failed to save password: {}") # 保存密码失败: {}
password_load_failed = _l("Failed to get password: {}") # 获取密码失败: {}

View File

@@ -28,7 +28,8 @@ class Search(object):
count=None,
sort=None,
reverse=False,
ancestor_ids=None):
ancestor_ids=None,
has_m2m=None):
self.orig_query = query
self.fl = fl
self.facet_field = facet_field
@@ -45,14 +46,15 @@ class Search(object):
level[0] if isinstance(level, list) and level else level)
self.ancestor_ids = ancestor_ids
self.has_m2m = False
if self.ancestor_ids:
self.has_m2m = True
else:
level = level[0] if isinstance(level, list) and level else level
for _l, c in self.level2constraint.items():
if _l < int(level) and c == ConstraintEnum.Many2Many:
self.has_m2m = True
self.has_m2m = has_m2m or False
if not self.has_m2m:
if self.ancestor_ids:
self.has_m2m = True
else:
level = level[0] if isinstance(level, list) and level else level
for _l, c in self.level2constraint.items():
if _l < int(level) and c == ConstraintEnum.Many2Many:
self.has_m2m = True
def _get_ids(self, ids):
if self.level[-1] == 1 and len(ids) == 1:
@@ -90,12 +92,12 @@ class Search(object):
key = list(set(["{},{}".format(i, j) for idx, i in enumerate(key) for j in _tmp[idx]]))
prefix = REDIS_PREFIX_CI_RELATION2
_tmp = list(map(lambda x: json.loads(x).keys() if x else [], rd.get(key, prefix) or []))
ids = [j for i in _tmp for j in i]
if not key:
return []
_tmp = list(map(lambda x: json.loads(x).keys() if x else [], rd.get(key, prefix) or []))
ids = [j for i in _tmp for j in i]
if level in self.level:
merge_ids.extend(ids)

View File

@@ -5,10 +5,10 @@ from __future__ import unicode_literals
import copy
import imp
import os
import tempfile
import jinja2
import os
import re
import tempfile
from flask import abort
from flask import current_app
from jinja2schema import infer
@@ -94,8 +94,13 @@ class AttributeValueManager(object):
@staticmethod
def _check_is_choice(attr, value_type, value):
choice_values = AttributeManager.get_choice_values(attr.id, value_type, attr.choice_web_hook, attr.choice_other)
if str(value) not in list(map(str, [i[0] for i in choice_values])):
return abort(400, ErrFormat.not_in_choice_values.format(value))
if value_type == ValueTypeEnum.FLOAT:
if float(value) not in list(map(float, [i[0] for i in choice_values])):
return abort(400, ErrFormat.not_in_choice_values.format(value))
else:
if str(value) not in list(map(str, [i[0] for i in choice_values])):
return abort(400, ErrFormat.not_in_choice_values.format(value))
@staticmethod
def _check_is_unique(value_table, attr, ci_id, type_id, value):
@@ -112,6 +117,11 @@ class AttributeValueManager(object):
if type_attr and type_attr.is_required and not value and value != 0:
return abort(400, ErrFormat.attribute_value_required.format(attr.alias))
@staticmethod
def check_re(expr, value):
if not re.compile(expr).match(str(value)):
return abort(400, ErrFormat.attribute_value_invalid.format(value))
def _validate(self, attr, value, value_table, ci=None, type_id=None, ci_id=None, type_attr=None):
ci = ci or {}
v = self._deserialize_value(attr.value_type, value)
@@ -125,6 +135,9 @@ class AttributeValueManager(object):
if v == "" and attr.value_type not in (ValueTypeEnum.TEXT,):
v = None
if attr.re_check and value:
self.check_re(attr.re_check, value)
return v
@staticmethod

View File

@@ -24,7 +24,15 @@ def get_all_department_list(to_dict=True):
*criterion
).order_by(Department.department_id.asc())
results = query.all()
return [r.to_dict() for r in results] if to_dict else results
if to_dict:
datas = []
for r in results:
d = r.to_dict()
if r.department_id == 0:
d['department_name'] = ErrFormat.company_wide
datas.append(d)
return datas
return results
def get_all_employee_list(block=0, to_dict=True):
@@ -101,6 +109,7 @@ class DepartmentTree(object):
employees = self.get_employees_by_d_id(department_id)
top_d['employees'] = employees
top_d['department_name'] = ErrFormat.company_wide
if len(sub_deps) == 0:
top_d[sub_departments_column_name] = []
d_list.append(top_d)
@@ -246,7 +255,7 @@ class DepartmentCRUD(object):
return abort(400, ErrFormat.acl_update_role_failed.format(str(e)))
try:
existed.update(**kwargs)
return existed.update(**kwargs)
except Exception as e:
return abort(400, str(e))
@@ -313,6 +322,7 @@ class DepartmentCRUD(object):
tree_list = []
for top_d in top_deps:
top_d['department_name'] = ErrFormat.company_wide
tree = Tree()
identifier_root = top_d['department_id']
tree.create_node(
@@ -383,6 +393,9 @@ class DepartmentCRUD(object):
d['employee_count'] = len(list(filter(lambda e: e['department_id'] in d_ids, all_employee_list)))
if int(department_parent_id) == -1:
d['department_name'] = ErrFormat.company_wide
return all_departments, department_id_list
@staticmethod

View File

@@ -15,10 +15,13 @@ from wtforms import validators
from api.extensions import db
from api.lib.common_setting.acl import ACLManager
from api.lib.common_setting.const import COMMON_SETTING_QUEUE, OperatorType
from api.lib.common_setting.const import OperatorType
from api.lib.perm.acl.const import ACL_QUEUE
from api.lib.common_setting.resp_format import ErrFormat
from api.models.common_setting import Employee, Department
from api.tasks.common_setting import refresh_employee_acl_info, edit_employee_department_in_acl
acl_user_columns = [
'email',
'mobile',
@@ -137,7 +140,9 @@ class EmployeeCRUD(object):
@staticmethod
def add(**kwargs):
try:
return CreateEmployee().create_single(**kwargs)
res = CreateEmployee().create_single(**kwargs)
refresh_employee_acl_info.apply_async(args=(res.employee_id,), queue=ACL_QUEUE)
return res
except Exception as e:
abort(400, str(e))
@@ -164,10 +169,9 @@ class EmployeeCRUD(object):
existed.update(**kwargs)
if len(e_list) > 0:
from api.tasks.common_setting import edit_employee_department_in_acl
edit_employee_department_in_acl.apply_async(
args=(e_list, new_department_id, current_user.uid),
queue=COMMON_SETTING_QUEUE
queue=ACL_QUEUE
)
return existed
@@ -291,7 +295,9 @@ class EmployeeCRUD(object):
employees = []
for r in pagination.items:
d = r.Employee.to_dict()
d['department_name'] = r.Department.department_name
d['department_name'] = r.Department.department_name if r.Department else ''
if r.Employee.department_id == 0:
d['department_name'] = ErrFormat.company_wide
employees.append(d)
return {
@@ -437,7 +443,7 @@ class EmployeeCRUD(object):
employees = []
for r in pagination.items:
d = r.Employee.to_dict()
d['department_name'] = r.Department.department_name
d['department_name'] = r.Department.department_name if r.Department else ''
employees.append(d)
return {
@@ -687,6 +693,27 @@ class EmployeeCRUD(object):
else:
abort(400, ErrFormat.column_name_not_support)
@staticmethod
def update_last_login_by_uid(uid, last_login=None):
employee = Employee.get_by(acl_uid=uid, first=True, to_dict=False)
if not employee:
return
if last_login:
try:
last_login = datetime.strptime(last_login, '%Y-%m-%d %H:%M:%S')
except Exception as e:
last_login = datetime.now()
else:
last_login = datetime.now()
try:
employee.update(
last_login=last_login
)
return last_login
except Exception as e:
return
def get_user_map(key='uid', acl=None):
"""
@@ -760,9 +787,11 @@ class CreateEmployee(object):
if existed:
return existed
return Employee.create(
res = Employee.create(
**kwargs
)
refresh_employee_acl_info.apply_async(args=(res.employee_id,), queue=ACL_QUEUE)
return res
@staticmethod
def get_department_by_name(d_name):
@@ -869,3 +898,75 @@ class EmployeeUpdateByUidForm(Form):
avatar = StringField(validators=[])
sex = StringField(validators=[])
mobile = StringField(validators=[])
class GrantEmployeeACLPerm(object):
"""
Grant ACL Permission After Create New Employee
"""
def __init__(self, acl=None):
self.perms_by_create_resources_type = ['read', 'grant', 'delete', 'update']
self.perms_by_common_grant = ['read']
self.resource_name_list = ['公司信息', '公司架构', '通知设置']
self.acl = acl if acl else self.check_app('backend')
self.resources_types = self.acl.get_all_resources_types()
self.resources_type = self.get_resources_type()
self.resource_list = self.acl.get_resource_by_type(None, None, self.resources_type['id'])
@staticmethod
def check_app(app_name):
acl = ACLManager(app_name)
payload = dict(
name=app_name,
description=app_name
)
app = acl.validate_app()
if not app:
acl.create_app(payload)
return acl
def get_resources_type(self):
results = list(filter(lambda t: t['name'] == '操作权限', self.resources_types['groups']))
if len(results) == 0:
payload = dict(
app_id=self.acl.app_name,
name='操作权限',
description='',
perms=self.perms_by_create_resources_type
)
resource_type = self.acl.create_resources_type(payload)
else:
resource_type = results[0]
resource_type_id = resource_type['id']
existed_perms = self.resources_types.get('id2perms', {}).get(resource_type_id, [])
existed_perms = [p['name'] for p in existed_perms]
new_perms = []
for perm in self.perms_by_create_resources_type:
if perm not in existed_perms:
new_perms.append(perm)
if len(new_perms) > 0:
resource_type['perms'] = existed_perms + new_perms
self.acl.update_resources_type(resource_type_id, resource_type)
return resource_type
def grant(self, rid_list):
[self.grant_by_rid(rid) for rid in rid_list if rid > 0]
def grant_by_rid(self, rid, is_admin=False):
for name in self.resource_name_list:
resource = list(filter(lambda r: r['name'] == name, self.resource_list))
if len(resource) == 0:
payload = dict(
type_id=self.resources_type['id'],
app_id=self.acl.app_name,
name=name,
)
resource = self.acl.create_resource(payload)
else:
resource = resource[0]
perms = self.perms_by_create_resources_type if is_admin else self.perms_by_common_grant
self.acl.grant_resource(rid, resource['id'], perms)

View File

@@ -1,77 +1,82 @@
# -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
from api.lib.resp_format import CommonErrFormat
class ErrFormat(CommonErrFormat):
company_info_is_already_existed = "公司信息已存在!无法创建"
company_info_is_already_existed = _l("Company info already existed") # 公司信息已存在!无法创建
no_file_part = "没有文件部分"
file_is_required = "文件是必须的"
file_not_found = "文件不存在"
file_type_not_allowed = "文件类型不允许"
upload_failed = "上传失败: {}"
no_file_part = _l("No file part") # 没有文件部分
file_is_required = _l("File is required") # 文件是必须的
file_not_found = _l("File not found") # 文件不存在
file_type_not_allowed = _l("File type not allowed") # 文件类型不允许
upload_failed = _l("Upload failed: {}") # 上传失败: {}
direct_supervisor_is_not_self = "直属上级不能是自己"
parent_department_is_not_self = "上级部门不能是自己"
employee_list_is_empty = "员工列表为空"
direct_supervisor_is_not_self = _l("Direct supervisor is not self") # 直属上级不能是自己
parent_department_is_not_self = _l("Parent department is not self") # 上级部门不能是自己
employee_list_is_empty = _l("Employee list is empty") # 员工列表为空
column_name_not_support = "不支持的列名"
password_is_required = "密码不能为空"
employee_acl_rid_is_zero = "员工ACL角色ID不能为0"
column_name_not_support = _l("Column name not support") # 不支持的列名
password_is_required = _l("Password is required") # 密码是必须的
employee_acl_rid_is_zero = _l("Employee acl rid is zero") # 员工ACL角色ID不能为0
generate_excel_failed = "生成excel失败: {}"
rename_columns_failed = "字段转换为中文失败: {}"
cannot_block_this_employee_is_other_direct_supervisor = "该员工是其他员工的直属上级, 不能禁用"
cannot_block_this_employee_is_department_manager = "该员工是部门负责人, 不能禁用"
employee_id_not_found = "员工ID [{}] 不存在"
value_is_required = "值是必须的"
email_already_exists = "邮箱 [{}] 已存在"
query_column_none_keep_value_empty = "查询 {} 空值时请保持value为空"
not_support_operator = "不支持的操作符: {}"
not_support_relation = "不支持的关系: {}"
conditions_field_missing = "conditions内元素字段缺失请检查"
datetime_format_error = "{} 格式错误,应该为:%Y-%m-%d %H:%M:%S"
department_level_relation_error = "部门层级关系不正确"
delete_reserved_department_name = "保留部门,无法删除!"
department_id_is_required = "部门ID是必须的"
department_list_is_required = "部门列表是必须的"
cannot_to_be_parent_department = "{} 不能设置为上级部门"
department_id_not_found = "部门ID [{}] 不存在"
parent_department_id_must_more_than_zero = "上级部门ID必须大于0"
department_name_already_exists = "部门名称 [{}] 已存在"
new_department_is_none = "新部门是空的"
generate_excel_failed = _l("Generate excel failed: {}") # 生成excel失败: {}
rename_columns_failed = _l("Rename columns failed: {}") # 重命名字段失败: {}
cannot_block_this_employee_is_other_direct_supervisor = _l(
"Cannot block this employee is other direct supervisor") # 该员工是其他员工的直属上级, 不能禁用
cannot_block_this_employee_is_department_manager = _l(
"Cannot block this employee is department manager") # 该员工是部门负责人, 不能禁用
employee_id_not_found = _l("Employee id [{}] not found") # 员工ID [{}] 不存在
value_is_required = _l("Value is required") # 值是必须的
email_already_exists = _l("Email already exists") # 邮箱已存在
query_column_none_keep_value_empty = _l("Query {} none keep value empty") # 查询 {} 空值时请保持value为空"
not_support_operator = _l("Not support operator: {}") # 不支持的操作符: {}
not_support_relation = _l("Not support relation: {}") # 不支持的关系: {}
conditions_field_missing = _l("Conditions field missing") # conditions内元素字段缺失请检查
datetime_format_error = _l("Datetime format error: {}") # {} 格式错误,应该为:%Y-%m-%d %H:%M:%S
department_level_relation_error = _l("Department level relation error") # 部门层级关系不正确
delete_reserved_department_name = _l("Delete reserved department name") # 保留部门,无法删除!
department_id_is_required = _l("Department id is required") # 部门ID是必须的
department_list_is_required = _l("Department list is required") # 部门列表是必须的
cannot_to_be_parent_department = _l("{} Cannot to be parent department") # 不能设置为上级部门
department_id_not_found = _l("Department id [{}] not found") # 部门ID [{}] 不存在
parent_department_id_must_more_than_zero = _l("Parent department id must more than zero") # 上级部门ID必须大于0
department_name_already_exists = _l("Department name [{}] already exists") # 部门名称 [{}] 已存在
new_department_is_none = _l("New department is none") # 新部门是空的
acl_edit_user_failed = "ACL 修改用户失败: {}"
acl_uid_not_found = "ACL 用户UID [{}] 不存在"
acl_add_user_failed = "ACL 添加用户失败: {}"
acl_add_role_failed = "ACL 添加角色失败: {}"
acl_update_role_failed = "ACL 更新角色失败: {}"
acl_get_all_users_failed = "ACL 获取所有用户失败: {}"
acl_remove_user_from_role_failed = "ACL 从角色中移除用户失败: {}"
acl_add_user_to_role_failed = "ACL 添加用户到角色失败: {}"
acl_import_user_failed = "ACL 导入用户[{}]失败: {}"
acl_edit_user_failed = _l("ACL edit user failed: {}") # ACL 修改用户失败: {}
acl_uid_not_found = _l("ACL uid not found: {}") # ACL 用户UID [{}] 不存在
acl_add_user_failed = _l("ACL add user failed: {}") # ACL 添加用户失败: {}
acl_add_role_failed = _l("ACL add role failed: {}") # ACL 添加角色失败: {}
acl_update_role_failed = _l("ACL update role failed: {}") # ACL 更新角色失败: {}
acl_get_all_users_failed = _l("ACL get all users failed: {}") # ACL 获取所有用户失败: {}
acl_remove_user_from_role_failed = _l("ACL remove user from role failed: {}") # ACL 从角色中移除用户失败: {}
acl_add_user_to_role_failed = _l("ACL add user to role failed: {}") # ACL 添加用户到角色失败: {}
acl_import_user_failed = _l("ACL import user failed: {}") # ACL 导入用户失败: {}
nickname_is_required = "用户名不能为空"
username_is_required = "username不能为空"
email_is_required = "邮箱不能为空"
email_format_error = "邮箱格式错误"
email_send_timeout = "邮件发送超时"
nickname_is_required = _l("Nickname is required") # 昵称不能为空
username_is_required = _l("Username is required") # 用户名不能为空
email_is_required = _l("Email is required") # 邮箱不能为空
email_format_error = _l("Email format error") # 邮箱格式错误
email_send_timeout = _l("Email send timeout") # 邮件发送超时
common_data_not_found = "ID {} 找不到记录"
common_data_already_existed = "{} 已存在"
notice_platform_existed = "{} 已存在"
notice_not_existed = "{} 配置项不存在"
notice_please_config_messenger_first = "请先配置 messenger"
notice_bind_err_with_empty_mobile = "绑定失败,手机号为空"
notice_bind_failed = "绑定失败: {}"
notice_bind_success = "绑定成功"
notice_remove_bind_success = "解绑成功"
common_data_not_found = _l("Common data not found {} ") # ID {} 找不到记录
common_data_already_existed = _l("Common data {} already existed") # {} 已存在
notice_platform_existed = _l("Notice platform {} existed") # {} 已存在
notice_not_existed = _l("Notice {} not existed") # {} 配置项不存在
notice_please_config_messenger_first = _l("Notice please config messenger first") # 请先配置messenger URL
notice_bind_err_with_empty_mobile = _l("Notice bind err with empty mobile") # 绑定错误,手机号为空
notice_bind_failed = _l("Notice bind failed: {}") # 绑定失败: {}
notice_bind_success = _l("Notice bind success") # 绑定成功
notice_remove_bind_success = _l("Notice remove bind success") # 解绑成功
not_support_test = "不支持的测试类型: {}"
not_support_auth_type = "不支持的认证类型: {}"
ldap_server_connect_timeout = "LDAP服务器连接超时"
ldap_server_connect_not_available = "LDAP服务器连接不可用"
ldap_test_unknown_error = "LDAP测试未知错误: {}"
common_data_not_support_auth_type = "通用数据不支持auth类型: {}"
ldap_test_username_required = "LDAP测试用户名必填"
not_support_test = _l("Not support test type: {}") # 不支持的测试类型: {}
not_support_auth_type = _l("Not support auth type: {}") # 不支持的认证类型: {}
ldap_server_connect_timeout = _l("LDAP server connect timeout") # LDAP服务器连接超时
ldap_server_connect_not_available = _l("LDAP server connect not available") # LDAP服务器连接不可用
ldap_test_unknown_error = _l("LDAP test unknown error: {}") # LDAP测试未知错误: {}
common_data_not_support_auth_type = _l("Common data not support auth type: {}") # 通用数据不支持auth类型: {}
ldap_test_username_required = _l("LDAP test username required") # LDAP测试用户名必填
company_wide = _l("Company wide") # 全公司

View File

@@ -1,3 +1,4 @@
import base64
import uuid
import os
from io import BytesIO
@@ -29,14 +30,14 @@ class CommonFileCRUD:
return CommonFile.create(**kwargs)
@staticmethod
def get_file(file_name):
def get_file(file_name, to_str=False):
existed = CommonFile.get_by(file_name=file_name, first=True, to_dict=False)
if not existed:
abort(400, ErrFormat.file_not_found)
uncompressed_data = lz4.frame.decompress(existed.binary)
return BytesIO(uncompressed_data)
return base64.b64encode(uncompressed_data).decode('utf-8') if to_str else BytesIO(uncompressed_data)
@staticmethod
def sync_file_to_db():
@@ -66,3 +67,28 @@ class CommonFileCRUD:
current_app.logger.info(f'sync file {file} to db')
except Exception as e:
current_app.logger.error(f'sync file {file} to db error: {e}')
def get_file_binary_str(self, file_name):
return self.get_file(file_name, True)
def save_str_to_file(self, file_name, str_data):
try:
self.get_file(file_name)
current_app.logger.info(f'file {file_name} already exists')
return
except Exception as e:
# file not found
pass
bytes_data = base64.b64decode(str_data)
compressed_data = lz4.frame.compress(bytes_data)
try:
self.add_file(
origin_name=file_name,
file_name=file_name,
binary=compressed_data
)
current_app.logger.info(f'save_str_to_file {file_name} success')
except Exception as e:
current_app.logger.error(f"save_str_to_file error: {e}")

View File

@@ -117,15 +117,15 @@ class ACLManager(object):
if group:
PermissionCRUD.grant(role.id, permissions, group_id=group.id)
def grant_resource_to_role_by_rid(self, name, rid, resource_type_name=None, permissions=None):
def grant_resource_to_role_by_rid(self, name, rid, resource_type_name=None, permissions=None, rebuild=True):
resource = self._get_resource(name, resource_type_name)
if resource:
PermissionCRUD.grant(rid, permissions, resource_id=resource.id)
PermissionCRUD.grant(rid, permissions, resource_id=resource.id, rebuild=rebuild)
else:
group = self._get_resource_group(name)
if group:
PermissionCRUD.grant(rid, permissions, group_id=group.id)
PermissionCRUD.grant(rid, permissions, group_id=group.id, rebuild=rebuild)
def revoke_resource_from_role(self, name, role, resource_type_name=None, permissions=None):
resource = self._get_resource(name, resource_type_name)
@@ -138,20 +138,20 @@ class ACLManager(object):
if group:
PermissionCRUD.revoke(role.id, permissions, group_id=group.id)
def revoke_resource_from_role_by_rid(self, name, rid, resource_type_name=None, permissions=None):
def revoke_resource_from_role_by_rid(self, name, rid, resource_type_name=None, permissions=None, rebuild=True):
resource = self._get_resource(name, resource_type_name)
if resource:
PermissionCRUD.revoke(rid, permissions, resource_id=resource.id)
PermissionCRUD.revoke(rid, permissions, resource_id=resource.id, rebuild=rebuild)
else:
group = self._get_resource_group(name)
if group:
PermissionCRUD.revoke(rid, permissions, group_id=group.id)
PermissionCRUD.revoke(rid, permissions, group_id=group.id, rebuild=rebuild)
def del_resource(self, name, resource_type_name=None):
resource = self._get_resource(name, resource_type_name)
if resource:
ResourceCRUD.delete(resource.id)
return ResourceCRUD.delete(resource.id)
def has_permission(self, resource_name, resource_type, perm, resource_id=None):
if is_app_admin(self.app_id):

View File

@@ -389,9 +389,16 @@ class AuditCRUD(object):
logout_at=logout_at,
ip=request.headers.get('X-Real-IP') or request.remote_addr,
browser=request.headers.get('User-Agent'),
channel=request.values.get('channel', 'web'),
)
if logout_at is None:
payload['login_at'] = datetime.datetime.now()
try:
from api.lib.common_setting.employee import EmployeeCRUD
EmployeeCRUD.update_last_login_by_uid(current_user.uid)
except:
pass
return AuditLoginLog.create(**payload).id

View File

@@ -328,6 +328,8 @@ class ResourceCRUD(object):
AuditCRUD.add_resource_log(resource.app_id, AuditOperateType.delete,
AuditScope.resource, resource.id, origin, {}, {})
return rebuilds
@classmethod
def delete_by_name(cls, name, type_id, app_id):
resource = Resource.get_by(name=name, resource_type_id=type_id, app_id=app_id) or abort(

View File

@@ -1,46 +1,50 @@
# -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
from api.lib.resp_format import CommonErrFormat
class ErrFormat(CommonErrFormat):
login_succeed = "登录成功"
ldap_connection_failed = "连接LDAP服务失败"
invalid_password = "密码验证失败"
auth_only_with_app_token_failed = "应用 Token验证失败"
session_invalid = "您不是应用管理员 或者 session失效(尝试一下退出重新登录)"
login_succeed = _l("login successful") # 登录成功
ldap_connection_failed = _l("Failed to connect to LDAP service") # 连接LDAP服务失败
invalid_password = _l("Password verification failed") # 密码验证失败
auth_only_with_app_token_failed = _l("Application Token verification failed") # 应用 Token验证失败
# 您不是应用管理员 或者 session失效(尝试一下退出重新登录)
session_invalid = _l(
"You are not the application administrator or the session has expired (try logging out and logging in again)")
resource_type_not_found = "资源类型 {} 不存在!"
resource_type_exists = "资源类型 {} 已经存在!"
resource_type_cannot_delete = "因为该类型下有资源的存在, 不能删除!"
resource_type_not_found = _l("Resource type {} does not exist!") # 资源类型 {} 不存在!
resource_type_exists = _l("Resource type {} already exists!") # 资源类型 {} 已经存在!
# 因为该类型下有资源的存在, 不能删除!
resource_type_cannot_delete = _l("Because there are resources under this type, they cannot be deleted!")
user_not_found = "用户 {} 不存在!"
user_exists = "用户 {} 已经存在!"
role_not_found = "角色 {} 不存在!"
role_exists = "角色 {} 已经存在!"
global_role_not_found = "全局角色 {} 不存在!"
global_role_exists = "全局角色 {} 已经存在!"
user_not_found = _l("User {} does not exist!") # 用户 {} 不存在!
user_exists = _l("User {} already exists!") # 用户 {} 已经存在!
role_not_found = _l("Role {} does not exist!") # 角色 {} 不存在!
role_exists = _l("Role {} already exists!") # 角色 {} 已经存在!
global_role_not_found = _l("Global role {} does not exist!") # 全局角色 {} 不存在!
global_role_exists = _l("Global role {} already exists!") # 全局角色 {} 已经存在!
resource_no_permission = "您没有资源: {}{} 权限"
admin_required = "需要管理员权限"
role_required = "需要角色: {}"
user_role_delete_invalid = "删除用户角色, 请在 用户管理 页面操作!"
resource_no_permission = _l("You do not have {} permission on resource: {}") # 您没有资源: {} 的 {} 权限
admin_required = _l("Requires administrator permissions") # 需要管理员权限
role_required = _l("Requires role: {}") # 需要角色: {}
# 删除用户角色, 请在 用户管理 页面操作!
user_role_delete_invalid = _l("To delete a user role, please operate on the User Management page!")
app_is_ready_existed = "应用 {} 已经存在"
app_not_found = "应用 {} 不存在!"
app_secret_invalid = "应用的Secret无效"
app_is_ready_existed = _l("Application {} already exists") # 应用 {} 已经存在
app_not_found = _l("Application {} does not exist!") # 应用 {} 不存在!
app_secret_invalid = _l("The Secret is invalid") # 应用的Secret无效
resource_not_found = "资源 {} 不存在!"
resource_exists = "资源 {} 已经存在!"
resource_not_found = _l("Resource {} does not exist!") # 资源 {} 不存在!
resource_exists = _l("Resource {} already exists!") # 资源 {} 已经存在!
resource_group_not_found = "资源组 {} 不存在!"
resource_group_exists = "资源组 {} 已经存在!"
resource_group_not_found = _l("Resource group {} does not exist!") # 资源组 {} 不存在!
resource_group_exists = _l("Resource group {} already exists!") # 资源组 {} 已经存在!
inheritance_dead_loop = "继承检测到了死循环"
role_relation_not_found = "角色关系 {} 不存在!"
inheritance_dead_loop = _l("Inheritance detected infinite loop") # 继承检测到了死循环
role_relation_not_found = _l("Role relationship {} does not exist!") # 角色关系 {} 不存在!
trigger_not_found = "触发器 {} 不存在!"
trigger_exists = "触发器 {} 已经存在!"
trigger_disabled = "触发器 {} 已经被禁用!"
invalid_password = "密码不正确!"
trigger_not_found = _l("Trigger {} does not exist!") # 触发器 {} 不存在!
trigger_exists = _l("Trigger {} already exists!") # 触发器 {} 已经存在!
trigger_disabled = _l("Trigger {} has been disabled!") # Trigger {} has been disabled!

View File

@@ -63,6 +63,7 @@ class UserCRUD(object):
AuditCRUD.add_role_log(None, AuditOperateType.create,
AuditScope.user, user.uid, {}, user.to_dict(), {}, {}
)
if add_from != 'common':
from api.lib.common_setting.employee import EmployeeCRUD
payload = {column: getattr(user, column) for column in ['uid', 'username', 'nickname', 'email', 'block']}

View File

@@ -23,13 +23,13 @@ from api.models.acl import User
def authenticate_with_ldap(username, password):
config = AuthenticateDataCRUD(AuthenticateType.LDAP).get()
server = Server(config.get('LDAP').get('ldap_server'), get_info=ALL, connect_timeout=3)
server = Server(config.get('ldap_server'), get_info=ALL, connect_timeout=3)
if '@' in username:
email = username
who = config['LDAP'].get('ldap_user_dn').format(username.split('@')[0])
who = config.get('ldap_user_dn').format(username.split('@')[0])
else:
who = config['LDAP'].get('ldap_user_dn').format(username)
email = "{}@{}".format(who, config['LDAP'].get('ldap_domain'))
who = config.get('ldap_user_dn').format(username)
email = "{}@{}".format(who, config.get('ldap_domain'))
username = username.split('@')[0]
user = User.query.get_by_username(username)
@@ -41,7 +41,7 @@ def authenticate_with_ldap(username, password):
conn = Connection(server, user=who, password=password, auto_bind=AUTO_BIND_NO_TLS)
except LDAPBindError:
conn = Connection(server,
user=f"{username}@{config['LDAP'].get('ldap_domain')}",
user=f"{username}@{config.get('ldap_domain')}",
password=password,
auto_bind=AUTO_BIND_NO_TLS)

View File

@@ -1,29 +1,34 @@
# -*- coding:utf-8 -*-
from flask_babel import lazy_gettext as _l
class CommonErrFormat(object):
unauthorized = "未认证"
unknown_error = "未知错误"
unauthorized = _l("unauthorized") # 未认证
unknown_error = _l("unknown error") # 未知错误
invalid_request = "不合法的请求"
invalid_operation = "无效的操作"
invalid_request = _l("Illegal request") # 不合法的请求
invalid_operation = _l("Invalid operation") # 无效的操作
not_found = "不存在"
not_found = _l("does not exist") # 不存在
circular_dependency_error = "存在循环依赖!"
circular_dependency_error = _l("There is a circular dependency!") # 存在循环依赖!
unknown_search_error = "未知搜索错误"
unknown_search_error = _l("Unknown search error") # 未知搜索错误
invalid_json = "json格式似乎不正确了, 请仔细确认一下!"
# json格式似乎不正确了, 请仔细确认一下!
invalid_json = _l("The json format seems to be incorrect, please confirm carefully!")
datetime_argument_invalid = "参数 {} 格式不正确, 格式必须是: yyyy-mm-dd HH:MM:SS"
# 参数 {} 格式不正确, 格式必须是: yyyy-mm-dd HH:MM:SS
datetime_argument_invalid = _l("The format of parameter {} is incorrect, the format must be: yyyy-mm-dd HH:MM:SS")
argument_value_required = "参数 {} 的值不能为空!"
argument_required = "请求缺少参数 {}"
argument_invalid = "参数 {} 的值无效"
argument_str_length_limit = "参数 {} 的长度必须 <= {}"
argument_value_required = _l("The value of parameter {} cannot be empty!") # 参数 {} 的值不能为空!
argument_required = _l("The request is missing parameters {}") # 请求缺少参数 {}
argument_invalid = _l("Invalid value for parameter {}") # 参数 {} 的值无效
argument_str_length_limit = _l("The length of parameter {} must be <= {}") # 参数 {} 的长度必须 <= {}
role_required = "角色 {} 才能操作!"
user_not_found = "用户 {} 不存在"
no_permission = "您没有资源: {}{}权限!"
no_permission2 = "您没有操作权限!"
no_permission_only_owner = "只有创建人或者管理员才有权限!"
role_required = _l("Role {} can only operate!") # 角色 {} 才能操作!
user_not_found = _l("User {} does not exist") # 用户 {} 不存在
no_permission = _l("You do not have {} permission for resource: {}!") # 您没有资源: {} 的{}权限!
no_permission2 = _l("You do not have permission to operate!") # 您没有操作权限!
no_permission_only_owner = _l("Only the creator or administrator has permission!") # 只有创建人或者管理员才有权限!

View File

@@ -145,7 +145,7 @@ class User(CRUDModel, SoftDeleteMixin):
class RoleQuery(BaseQuery):
def authenticate(self, login, password):
role = self.filter(Role.name == login).first()
role = self.filter(Role.name == login).filter(Role.deleted.is_(False)).first()
if role:
authenticated = role.check_password(password)
@@ -356,7 +356,7 @@ class AuditLoginLog(Model2):
__tablename__ = "acl_audit_login_logs"
username = db.Column(db.String(64), index=True)
channel = db.Column(db.Enum('web', 'api'), default="web")
channel = db.Column(db.Enum('web', 'api', 'ssh'), default="web")
ip = db.Column(db.String(15))
browser = db.Column(db.String(256))
description = db.Column(db.String(128))

View File

@@ -57,6 +57,16 @@ class CIType(Model):
uid = db.Column(db.Integer, index=True)
class CITypeInheritance(Model):
__tablename__ = "c_ci_type_inheritance"
parent_id = db.Column(db.Integer, db.ForeignKey("c_ci_types.id"), nullable=False)
child_id = db.Column(db.Integer, db.ForeignKey("c_ci_types.id"), nullable=False)
parent = db.relationship("CIType", primaryjoin="CIType.id==CITypeInheritance.parent_id")
child = db.relationship("CIType", primaryjoin="CIType.id==CITypeInheritance.child_id")
class CITypeRelation(Model):
__tablename__ = "c_ci_type_relations"
@@ -94,6 +104,8 @@ class Attribute(Model):
_choice_web_hook = db.Column('choice_web_hook', db.JSON)
choice_other = db.Column(db.JSON)
re_check = db.Column(db.Text)
uid = db.Column(db.Integer, index=True)
option = db.Column(db.JSON)
@@ -464,6 +476,15 @@ class PreferenceSearchOption(Model):
option = db.Column(db.JSON)
class PreferenceCITypeOrder(Model):
__tablename__ = "c_pcto"
uid = db.Column(db.Integer, index=True, nullable=False)
type_id = db.Column(db.Integer, db.ForeignKey('c_ci_types.id'))
order = db.Column(db.SmallInteger, default=0)
is_tree = db.Column(db.Boolean, default=False) # True is tree view, False is resource view
# custom
class CustomDashboard(Model):
__tablename__ = "c_c_d"

View File

@@ -25,10 +25,9 @@ from api.models.acl import Role
from api.models.acl import Trigger
@celery.task(base=QueueOnce,
name="acl.role_rebuild",
queue=ACL_QUEUE,
once={"graceful": True, "unlock_before_run": True})
@celery.task(name="acl.role_rebuild",
queue=ACL_QUEUE,)
@flush_db
@reconnect_db
def role_rebuild(rids, app_id):
rids = rids if isinstance(rids, list) else [rids]
@@ -190,18 +189,18 @@ def cancel_trigger(_id, resource_id=None, operator_uid=None):
@celery.task(name="acl.op_record", queue=ACL_QUEUE)
@reconnect_db
def op_record(app, rolename, operate_type, obj):
def op_record(app, role_name, operate_type, obj):
if isinstance(app, int):
app = AppCache.get(app)
app = app and app.name
if isinstance(rolename, int):
u = UserCache.get(rolename)
if isinstance(role_name, int):
u = UserCache.get(role_name)
if u:
rolename = u.username
role_name = u.username
if not u:
r = RoleCache.get(rolename)
r = RoleCache.get(role_name)
if r:
rolename = r.name
role_name = r.name
OperateRecordCRUD.add(app, rolename, operate_type, obj)
OperateRecordCRUD.add(app, role_name, operate_type, obj)

View File

@@ -1,24 +1,24 @@
# -*- coding:utf-8 -*-
import requests
from flask import current_app
from api.extensions import celery
from api.extensions import db
from api.lib.common_setting.acl import ACLManager
from api.lib.common_setting.const import COMMON_SETTING_QUEUE
from api.lib.perm.acl.const import ACL_QUEUE
from api.lib.common_setting.resp_format import ErrFormat
from api.models.common_setting import Department
from api.models.common_setting import Department, Employee
from api.lib.decorator import flush_db
from api.lib.decorator import reconnect_db
@celery.task(name="common_setting.edit_employee_department_in_acl", queue=COMMON_SETTING_QUEUE)
@celery.task(name="common_setting.edit_employee_department_in_acl", queue=ACL_QUEUE)
@flush_db
@reconnect_db
def edit_employee_department_in_acl(e_list, new_d_id, op_uid):
"""
:param e_list:{acl_rid: 11, department_id: 22}
:param new_d_id
:param op_uid
"""
db.session.remove()
result = []
new_department = Department.get_by(
first=True, department_id=new_d_id, to_dict=False)
@@ -75,3 +75,57 @@ def edit_employee_department_in_acl(e_list, new_d_id, op_uid):
result.append(ErrFormat.acl_add_user_to_role_failed.format(str(e)))
return result
@celery.task(name="common_setting.refresh_employee_acl_info", queue=ACL_QUEUE)
@flush_db
@reconnect_db
def refresh_employee_acl_info(current_employee_id=None):
acl = ACLManager('acl')
role_map = {role['name']: role for role in acl.get_all_roles()}
criterion = [
Employee.deleted == 0
]
query = Employee.query.filter(*criterion).order_by(
Employee.created_at.desc()
)
current_employee_rid = 0
for em in query.all():
if current_employee_id and em.employee_id == current_employee_id:
current_employee_rid = em.acl_rid if em.acl_rid else 0
if em.acl_uid and em.acl_rid:
continue
role = role_map.get(em.username, None)
if not role:
continue
params = dict()
if not em.acl_uid:
params['acl_uid'] = role.get('uid', 0)
if not em.acl_rid:
params['acl_rid'] = role.get('id', 0)
if current_employee_id and em.employee_id == current_employee_id:
current_employee_rid = params['acl_rid'] if params.get('acl_rid', 0) else 0
try:
em.update(**params)
current_app.logger.info(
f"refresh_employee_acl_info success, employee_id: {em.employee_id}, uid: {em.acl_uid}, "
f"rid: {em.acl_rid}")
except Exception as e:
current_app.logger.error(str(e))
continue
if current_employee_rid and current_employee_rid > 0:
try:
from api.lib.common_setting.employee import GrantEmployeeACLPerm
GrantEmployeeACLPerm().grant_by_rid(current_employee_rid, False)
current_app.logger.info(f"GrantEmployeeACLPerm success, current_employee_rid: {current_employee_rid}")
except Exception as e:
current_app.logger.error(str(e))

Binary file not shown.

View File

@@ -0,0 +1,823 @@
# Chinese translations for PROJECT.
# Copyright (C) 2023 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2023.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2024-03-01 13:49+0800\n"
"PO-Revision-Date: 2023-12-25 20:21+0800\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: zh\n"
"Language-Team: zh <LL@li.org>\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.14.0\n"
#: api/lib/resp_format.py:7
msgid "unauthorized"
msgstr "未认证"
#: api/lib/resp_format.py:8
msgid "unknown error"
msgstr "未知错误"
#: api/lib/resp_format.py:10
msgid "Illegal request"
msgstr "不合法的请求"
#: api/lib/resp_format.py:11
msgid "Invalid operation"
msgstr "无效的操作"
#: api/lib/resp_format.py:13
msgid "does not exist"
msgstr "不存在"
#: api/lib/resp_format.py:15
msgid "There is a circular dependency!"
msgstr "存在循环依赖!"
#: api/lib/resp_format.py:17
msgid "Unknown search error"
msgstr "未知搜索错误"
#: api/lib/resp_format.py:20
msgid "The json format seems to be incorrect, please confirm carefully!"
msgstr "# json格式似乎不正确了, 请仔细确认一下!"
#: api/lib/resp_format.py:23
msgid ""
"The format of parameter {} is incorrect, the format must be: yyyy-mm-dd "
"HH:MM:SS"
msgstr "参数 {} 格式不正确, 格式必须是: yyyy-mm-dd HH:MM:SS"
#: api/lib/resp_format.py:25
msgid "The value of parameter {} cannot be empty!"
msgstr "参数 {} 的值不能为空!"
#: api/lib/resp_format.py:26
msgid "The request is missing parameters {}"
msgstr "请求缺少参数 {}"
#: api/lib/resp_format.py:27
msgid "Invalid value for parameter {}"
msgstr "参数 {} 的值无效"
#: api/lib/resp_format.py:28
msgid "The length of parameter {} must be <= {}"
msgstr "参数 {} 的长度必须 <= {}"
#: api/lib/resp_format.py:30
msgid "Role {} can only operate!"
msgstr "角色 {} 才能操作!"
#: api/lib/resp_format.py:31
msgid "User {} does not exist"
msgstr "用户 {} 不存在"
#: api/lib/resp_format.py:32
msgid "You do not have {} permission for resource: {}!"
msgstr "您没有资源: {} 的{}权限!"
#: api/lib/resp_format.py:33
msgid "You do not have permission to operate!"
msgstr "您没有操作权限!"
#: api/lib/resp_format.py:34
msgid "Only the creator or administrator has permission!"
msgstr "只有创建人或者管理员才有权限!"
#: api/lib/cmdb/resp_format.py:9
msgid "CI Model"
msgstr "模型配置"
#: api/lib/cmdb/resp_format.py:11
msgid "Invalid relation type: {}"
msgstr "无效的关系类型: {}"
#: api/lib/cmdb/resp_format.py:12
msgid "CIType is not found"
msgstr "模型不存在!"
#: api/lib/cmdb/resp_format.py:15
msgid "The type of parameter attributes must be a list"
msgstr "参数 attributes 类型必须是列表"
#: api/lib/cmdb/resp_format.py:16
msgid "The file doesn't seem to be uploaded"
msgstr "文件似乎并未上传"
#: api/lib/cmdb/resp_format.py:18
msgid "Attribute {} does not exist!"
msgstr "属性 {} 不存在!"
#: api/lib/cmdb/resp_format.py:19
msgid ""
"This attribute is the unique identifier of the model and cannot be "
"deleted!"
msgstr "该属性是模型的唯一标识,不能被删除!"
#: api/lib/cmdb/resp_format.py:21
msgid "This attribute is referenced by model {} and cannot be deleted!"
msgstr "该属性被模型 {} 引用, 不能删除!"
#: api/lib/cmdb/resp_format.py:23
msgid "The value type of the attribute is not allowed to be modified!"
msgstr "属性的值类型不允许修改!"
#: api/lib/cmdb/resp_format.py:25
msgid "Multiple values are not allowed to be modified!"
msgstr "多值不被允许修改!"
#: api/lib/cmdb/resp_format.py:27
msgid "Modifying the index is not allowed for non-administrators!"
msgstr "修改索引 非管理员不被允许!"
#: api/lib/cmdb/resp_format.py:28
msgid "Index switching failed!"
msgstr "索引切换失败!"
#: api/lib/cmdb/resp_format.py:29
msgid "The predefined value is of the wrong type!"
msgstr "预定义值的类型不对!"
#: api/lib/cmdb/resp_format.py:30
msgid "Duplicate attribute name {}"
msgstr "重复的属性名 {}"
#: api/lib/cmdb/resp_format.py:31
msgid "Failed to create attribute {}!"
msgstr "创建属性 {} 失败!"
#: api/lib/cmdb/resp_format.py:32
msgid "Modify attribute {} failed!"
msgstr "修改属性 {} 失败!"
#: api/lib/cmdb/resp_format.py:33
msgid "You do not have permission to modify this attribute!"
msgstr "您没有权限修改该属性!"
#: api/lib/cmdb/resp_format.py:34
msgid "Only creators and administrators are allowed to delete attributes!"
msgstr "目前只允许 属性创建人、管理员 删除属性!"
#: api/lib/cmdb/resp_format.py:37
msgid ""
"Attribute field names cannot be built-in fields: id, _id, ci_id, type, "
"_type, ci_type"
msgstr "属性字段名不能是内置字段: id, _id, ci_id, type, _type, ci_type"
#: api/lib/cmdb/resp_format.py:39
msgid "Predefined value: Other model request parameters are illegal!"
msgstr "预定义值: 其他模型请求参数不合法!"
#: api/lib/cmdb/resp_format.py:42
msgid "CI {} does not exist"
msgstr "CI {} 不存在"
#: api/lib/cmdb/resp_format.py:43
msgid "Multiple attribute joint unique verification failed: {}"
msgstr "多属性联合唯一校验不通过: {}"
#: api/lib/cmdb/resp_format.py:44
msgid "The model's primary key {} does not exist!"
msgstr "模型的主键 {} 不存在!"
#: api/lib/cmdb/resp_format.py:45
msgid "Primary key {} is missing"
msgstr "主键字段 {} 缺失"
#: api/lib/cmdb/resp_format.py:46
msgid "CI already exists!"
msgstr "CI 已经存在!"
#: api/lib/cmdb/resp_format.py:47
msgid "Relationship constraint: {}, verification failed"
msgstr "关系约束: {}, 校验失败"
#: api/lib/cmdb/resp_format.py:49
msgid ""
"Many-to-many relationship constraint: Model {} <-> {} already has a many-"
"to-many relationship!"
msgstr "多对多关系 限制: 模型 {} <-> {} 已经存在多对多关系!"
#: api/lib/cmdb/resp_format.py:52
msgid "CI relationship: {} does not exist"
msgstr "CI关系: {} 不存在"
#: api/lib/cmdb/resp_format.py:55
msgid "In search expressions, not supported before parentheses: or, not"
msgstr "搜索表达式里小括号前不支持: 或、非"
#: api/lib/cmdb/resp_format.py:57
msgid "Model {} does not exist"
msgstr "模型 {} 不存在"
#: api/lib/cmdb/resp_format.py:58
msgid "Model {} already exists"
msgstr "模型 {} 已经存在"
#: api/lib/cmdb/resp_format.py:59
msgid "The primary key is undefined or has been deleted"
msgstr "主键未定义或者已被删除"
#: api/lib/cmdb/resp_format.py:60
msgid "Only the creator can delete it!"
msgstr "只有创建人才能删除它!"
#: api/lib/cmdb/resp_format.py:61
msgid "The model cannot be deleted because the CI already exists"
msgstr "因为CI已经存在不能删除模型"
#: api/lib/cmdb/resp_format.py:63
msgid "The inheritance cannot be deleted because the CI already exists"
msgstr "因为CI已经存在不能删除继承关系"
#: api/lib/cmdb/resp_format.py:67
msgid ""
"The model cannot be deleted because the model is referenced by the "
"relational view {}"
msgstr "因为关系视图 {} 引用了该模型,不能删除模型"
#: api/lib/cmdb/resp_format.py:69
msgid "Model group {} does not exist"
msgstr "模型分组 {} 不存在"
#: api/lib/cmdb/resp_format.py:70
msgid "Model group {} already exists"
msgstr "模型分组 {} 已经存在"
#: api/lib/cmdb/resp_format.py:71
msgid "Model relationship {} does not exist"
msgstr "模型关系 {} 不存在"
#: api/lib/cmdb/resp_format.py:72
msgid "Attribute group {} already exists"
msgstr "属性分组 {} 已存在"
#: api/lib/cmdb/resp_format.py:73
msgid "Attribute group {} does not exist"
msgstr "属性分组 {} 不存在"
#: api/lib/cmdb/resp_format.py:75
msgid "Attribute group <{0}> - attribute <{1}> does not exist"
msgstr "属性组<{0}> - 属性<{1}> 不存在"
#: api/lib/cmdb/resp_format.py:76
msgid "The unique constraint already exists!"
msgstr "唯一约束已经存在!"
#: api/lib/cmdb/resp_format.py:78
msgid "Uniquely constrained attributes cannot be JSON and multi-valued"
msgstr "唯一约束的属性不能是 JSON 和 多值"
#: api/lib/cmdb/resp_format.py:79
msgid "Duplicated trigger"
msgstr "重复的触发器"
#: api/lib/cmdb/resp_format.py:80
msgid "Trigger {} does not exist"
msgstr "触发器 {} 不存在"
#: api/lib/cmdb/resp_format.py:82
msgid "Operation record {} does not exist"
msgstr "操作记录 {} 不存在"
#: api/lib/cmdb/resp_format.py:83
msgid "Unique identifier cannot be deleted"
msgstr "不能删除唯一标识"
#: api/lib/cmdb/resp_format.py:84
msgid "Cannot delete default sorted attributes"
msgstr "不能删除默认排序的属性"
#: api/lib/cmdb/resp_format.py:86
msgid "No node selected"
msgstr "没有选择节点"
#: api/lib/cmdb/resp_format.py:87
msgid "This search option does not exist!"
msgstr "该搜索选项不存在!"
#: api/lib/cmdb/resp_format.py:88
msgid "This search option has a duplicate name!"
msgstr "该搜索选项命名重复!"
#: api/lib/cmdb/resp_format.py:90
msgid "Relationship type {} already exists"
msgstr "关系类型 {} 已经存在"
#: api/lib/cmdb/resp_format.py:91
msgid "Relationship type {} does not exist"
msgstr "关系类型 {} 不存在"
#: api/lib/cmdb/resp_format.py:93
msgid "Invalid attribute value: {}"
msgstr "无效的属性值: {}"
#: api/lib/cmdb/resp_format.py:94
msgid "{} Invalid value: {}"
msgstr "无效的值: {}"
#: api/lib/cmdb/resp_format.py:95
msgid "{} is not in the predefined values"
msgstr "{} 不在预定义值里"
#: api/lib/cmdb/resp_format.py:97
msgid "The value of attribute {} must be unique, {} already exists"
msgstr "属性 {} 的值必须是唯一的, 当前值 {} 已存在"
#: api/lib/cmdb/resp_format.py:98
msgid "Attribute {} value must exist"
msgstr "属性 {} 值必须存在"
#: api/lib/cmdb/resp_format.py:101
msgid "Unknown error when adding or modifying attribute value: {}"
msgstr "新增或者修改属性值未知错误: {}"
#: api/lib/cmdb/resp_format.py:103
msgid "Duplicate custom name"
msgstr "订制名重复"
#: api/lib/cmdb/resp_format.py:105
msgid "Number of models exceeds limit: {}"
msgstr "模型数超过限制: {}"
#: api/lib/cmdb/resp_format.py:106
msgid "The number of CIs exceeds the limit: {}"
msgstr "CI数超过限制: {}"
#: api/lib/cmdb/resp_format.py:108
msgid "Auto-discovery rule: {} already exists!"
msgstr "自动发现规则: {} 已经存在!"
#: api/lib/cmdb/resp_format.py:109
msgid "Auto-discovery rule: {} does not exist!"
msgstr "自动发现规则: {} 不存在!"
#: api/lib/cmdb/resp_format.py:111
msgid "This auto-discovery rule is referenced by the model and cannot be deleted!"
msgstr "该自动发现规则被模型引用, 不能删除!"
#: api/lib/cmdb/resp_format.py:113
msgid "The application of auto-discovery rules cannot be defined repeatedly!"
msgstr "自动发现规则的应用不能重复定义!"
#: api/lib/cmdb/resp_format.py:114
msgid "The auto-discovery you want to modify: {} does not exist!"
msgstr "您要修改的自动发现: {} 不存在!"
#: api/lib/cmdb/resp_format.py:115
msgid "Attribute does not include unique identifier: {}"
msgstr "属性字段没有包括唯一标识: {}"
#: api/lib/cmdb/resp_format.py:116
msgid "The auto-discovery instance does not exist!"
msgstr "自动发现的实例不存在!"
#: api/lib/cmdb/resp_format.py:117
msgid "The model is not associated with this auto-discovery!"
msgstr "模型并未关联该自动发现!"
#: api/lib/cmdb/resp_format.py:118
msgid "Only the creator can modify the Secret!"
msgstr "只有创建人才能修改Secret!"
#: api/lib/cmdb/resp_format.py:120
msgid "This rule already has auto-discovery instances and cannot be deleted!"
msgstr "该规则已经有自动发现的实例, 不能被删除!"
#: api/lib/cmdb/resp_format.py:122
msgid "The default auto-discovery rule is already referenced by model {}!"
msgstr "该默认的自动发现规则 已经被模型 {} 引用!"
#: api/lib/cmdb/resp_format.py:124
msgid "The unique_key method must return a non-empty string!"
msgstr "unique_key方法必须返回非空字符串!"
#: api/lib/cmdb/resp_format.py:125
msgid "The attributes method must return a list"
msgstr "attributes方法必须返回的是list"
#: api/lib/cmdb/resp_format.py:127
msgid "The list returned by the attributes method cannot be empty!"
msgstr "attributes方法返回的list不能为空!"
#: api/lib/cmdb/resp_format.py:129
msgid "Only administrators can define execution targets as: all nodes!"
msgstr "只有管理员才可以定义执行机器为: 所有节点!"
#: api/lib/cmdb/resp_format.py:130
msgid "Execute targets permission check failed: {}"
msgstr "执行机器权限检查不通过: {}"
#: api/lib/cmdb/resp_format.py:132
msgid "CI filter authorization must be named!"
msgstr "CI过滤授权 必须命名!"
#: api/lib/cmdb/resp_format.py:133
msgid "CI filter authorization is currently not supported or query"
msgstr "CI过滤授权 暂时不支持 或 查询"
#: api/lib/cmdb/resp_format.py:136
msgid "You do not have permission to operate attribute {}!"
msgstr "您没有属性 {} 的操作权限!"
#: api/lib/cmdb/resp_format.py:137
msgid "You do not have permission to operate this CI!"
msgstr "您没有该CI的操作权限!"
#: api/lib/cmdb/resp_format.py:139
msgid "Failed to save password: {}"
msgstr "保存密码失败: {}"
#: api/lib/cmdb/resp_format.py:140
msgid "Failed to get password: {}"
msgstr "获取密码失败: {}"
#: api/lib/common_setting/resp_format.py:8
msgid "Company info already existed"
msgstr "公司信息已存在,无法创建!"
#: api/lib/common_setting/resp_format.py:10
msgid "No file part"
msgstr "没有文件部分"
#: api/lib/common_setting/resp_format.py:11
msgid "File is required"
msgstr "文件是必须的"
#: api/lib/common_setting/resp_format.py:12
msgid "File not found"
msgstr "文件不存在!"
#: api/lib/common_setting/resp_format.py:13
msgid "File type not allowed"
msgstr "文件类型不允许!"
#: api/lib/common_setting/resp_format.py:14
msgid "Upload failed: {}"
msgstr "上传失败: {}"
#: api/lib/common_setting/resp_format.py:16
msgid "Direct supervisor is not self"
msgstr "直属上级不能是自己"
#: api/lib/common_setting/resp_format.py:17
msgid "Parent department is not self"
msgstr "上级部门不能是自己"
#: api/lib/common_setting/resp_format.py:18
msgid "Employee list is empty"
msgstr "员工列表为空"
#: api/lib/common_setting/resp_format.py:20
msgid "Column name not support"
msgstr "不支持的列名"
#: api/lib/common_setting/resp_format.py:21
msgid "Password is required"
msgstr "密码是必须的"
#: api/lib/common_setting/resp_format.py:22
msgid "Employee acl rid is zero"
msgstr "员工ACL角色ID不能为0"
#: api/lib/common_setting/resp_format.py:24
msgid "Generate excel failed: {}"
msgstr "生成excel失败: {}"
#: api/lib/common_setting/resp_format.py:25
msgid "Rename columns failed: {}"
msgstr "重命名字段失败: {}"
#: api/lib/common_setting/resp_format.py:26
msgid "Cannot block this employee is other direct supervisor"
msgstr "该员工是其他员工的直属上级, 不能禁用"
#: api/lib/common_setting/resp_format.py:28
msgid "Cannot block this employee is department manager"
msgstr "该员工是部门负责人, 不能禁用"
#: api/lib/common_setting/resp_format.py:30
msgid "Employee id [{}] not found"
msgstr "员工ID [{}] 不存在!"
#: api/lib/common_setting/resp_format.py:31
msgid "Value is required"
msgstr "值是必须的"
#: api/lib/common_setting/resp_format.py:32
msgid "Email already exists"
msgstr "邮箱已存在!"
#: api/lib/common_setting/resp_format.py:33
msgid "Query {} none keep value empty"
msgstr "查询 {} 空值时请保持value为空"
#: api/lib/common_setting/resp_format.py:34
msgid "Not support operator: {}"
msgstr "不支持的操作符: {}"
#: api/lib/common_setting/resp_format.py:35
msgid "Not support relation: {}"
msgstr "不支持的关系: {}"
#: api/lib/common_setting/resp_format.py:36
msgid "Conditions field missing"
msgstr " conditions内元素字段缺失请检查"
#: api/lib/common_setting/resp_format.py:37
msgid "Datetime format error: {}"
msgstr "{}格式错误,应该为:%Y-%m-%d %H:%M:%S"
#: api/lib/common_setting/resp_format.py:38
msgid "Department level relation error"
msgstr "部门层级关系不正确"
#: api/lib/common_setting/resp_format.py:39
msgid "Delete reserved department name"
msgstr "保留部门,无法删除!"
#: api/lib/common_setting/resp_format.py:40
msgid "Department id is required"
msgstr "部门ID是必须的"
#: api/lib/common_setting/resp_format.py:41
msgid "Department list is required"
msgstr "部门列表是必须的"
#: api/lib/common_setting/resp_format.py:42
msgid "{} Cannot to be parent department"
msgstr "{} 不能设置为上级部门"
#: api/lib/common_setting/resp_format.py:43
msgid "Department id [{}] not found"
msgstr "部门ID [{}] 不存在"
#: api/lib/common_setting/resp_format.py:44
msgid "Parent department id must more than zero"
msgstr "上级部门ID必须大于0"
#: api/lib/common_setting/resp_format.py:45
msgid "Department name [{}] already exists"
msgstr "部门名称 [{}] 已存在"
#: api/lib/common_setting/resp_format.py:46
msgid "New department is none"
msgstr "新部门是空的"
#: api/lib/common_setting/resp_format.py:48
msgid "ACL edit user failed: {}"
msgstr "ACL 修改用户失败: {}"
#: api/lib/common_setting/resp_format.py:49
msgid "ACL uid not found: {}"
msgstr "ACL 用户UID [{}] 不存在"
#: api/lib/common_setting/resp_format.py:50
msgid "ACL add user failed: {}"
msgstr "ACL 添加用户失败: {}"
#: api/lib/common_setting/resp_format.py:51
msgid "ACL add role failed: {}"
msgstr "ACL 添加角色失败: {}"
#: api/lib/common_setting/resp_format.py:52
msgid "ACL update role failed: {}"
msgstr "ACL 更新角色失败: {}"
#: api/lib/common_setting/resp_format.py:53
msgid "ACL get all users failed: {}"
msgstr "ACL 获取所有用户失败: {}"
#: api/lib/common_setting/resp_format.py:54
msgid "ACL remove user from role failed: {}"
msgstr "ACL 从角色中移除用户失败: {}"
#: api/lib/common_setting/resp_format.py:55
msgid "ACL add user to role failed: {}"
msgstr "ACL 添加用户到角色失败: {}"
#: api/lib/common_setting/resp_format.py:56
msgid "ACL import user failed: {}"
msgstr "ACL 导入用户失败: {}"
#: api/lib/common_setting/resp_format.py:58
msgid "Nickname is required"
msgstr "昵称不能为空"
#: api/lib/common_setting/resp_format.py:59
msgid "Username is required"
msgstr "用户名不能为空"
#: api/lib/common_setting/resp_format.py:60
msgid "Email is required"
msgstr "邮箱不能为空"
#: api/lib/common_setting/resp_format.py:61
msgid "Email format error"
msgstr "邮箱格式错误"
#: api/lib/common_setting/resp_format.py:62
msgid "Email send timeout"
msgstr "邮件发送超时"
#: api/lib/common_setting/resp_format.py:64
msgid "Common data not found {} "
msgstr "ID {} 找不到记录"
#: api/lib/common_setting/resp_format.py:65
msgid "Common data {} already existed"
msgstr "{} 已经存在"
#: api/lib/common_setting/resp_format.py:66
msgid "Notice platform {} existed"
msgstr "{} 已经存在"
#: api/lib/common_setting/resp_format.py:67
msgid "Notice {} not existed"
msgstr "{} 配置项不存在"
#: api/lib/common_setting/resp_format.py:68
msgid "Notice please config messenger first"
msgstr "请先配置messenger URL"
#: api/lib/common_setting/resp_format.py:69
msgid "Notice bind err with empty mobile"
msgstr "绑定错误,手机号为空"
#: api/lib/common_setting/resp_format.py:70
msgid "Notice bind failed: {}"
msgstr "绑定失败: {}"
#: api/lib/common_setting/resp_format.py:71
msgid "Notice bind success"
msgstr "绑定成功"
#: api/lib/common_setting/resp_format.py:72
msgid "Notice remove bind success"
msgstr "解绑成功"
#: api/lib/common_setting/resp_format.py:74
msgid "Not support test type: {}"
msgstr "不支持的测试类型: {}"
#: api/lib/common_setting/resp_format.py:75
msgid "Not support auth type: {}"
msgstr "不支持的认证类型: {}"
#: api/lib/common_setting/resp_format.py:76
msgid "LDAP server connect timeout"
msgstr "LDAP服务器连接超时"
#: api/lib/common_setting/resp_format.py:77
msgid "LDAP server connect not available"
msgstr "LDAP服务器连接不可用"
#: api/lib/common_setting/resp_format.py:78
msgid "LDAP test unknown error: {}"
msgstr "LDAP测试未知错误: {}"
#: api/lib/common_setting/resp_format.py:79
msgid "Common data not support auth type: {}"
msgstr "通用数据不支持auth类型: {}"
#: api/lib/common_setting/resp_format.py:80
msgid "LDAP test username required"
msgstr "LDAP测试用户名必填"
#: api/lib/common_setting/resp_format.py:82
msgid "Company wide"
msgstr "全公司"
#: api/lib/perm/acl/resp_format.py:9
msgid "login successful"
msgstr "登录成功"
#: api/lib/perm/acl/resp_format.py:10
msgid "Failed to connect to LDAP service"
msgstr "连接LDAP服务失败"
#: api/lib/perm/acl/resp_format.py:11
msgid "Password verification failed"
msgstr "密码验证失败"
#: api/lib/perm/acl/resp_format.py:12
msgid "Application Token verification failed"
msgstr "应用 Token验证失败"
#: api/lib/perm/acl/resp_format.py:14
msgid ""
"You are not the application administrator or the session has expired (try"
" logging out and logging in again)"
msgstr "您不是应用管理员 或者 session失效(尝试一下退出重新登录)"
#: api/lib/perm/acl/resp_format.py:17
msgid "Resource type {} does not exist!"
msgstr "资源类型 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:18
msgid "Resource type {} already exists!"
msgstr "资源类型 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:20
msgid "Because there are resources under this type, they cannot be deleted!"
msgstr "因为该类型下有资源的存在, 不能删除!"
#: api/lib/perm/acl/resp_format.py:22
msgid "User {} does not exist!"
msgstr "用户 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:23
msgid "User {} already exists!"
msgstr "用户 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:24
msgid "Role {} does not exist!"
msgstr "角色 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:25
msgid "Role {} already exists!"
msgstr "角色 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:26
msgid "Global role {} does not exist!"
msgstr "全局角色 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:27
msgid "Global role {} already exists!"
msgstr "全局角色 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:29
msgid "You do not have {} permission on resource: {}"
msgstr "您没有资源: {} 的 {} 权限"
#: api/lib/perm/acl/resp_format.py:30
msgid "Requires administrator permissions"
msgstr "需要管理员权限"
#: api/lib/perm/acl/resp_format.py:31
msgid "Requires role: {}"
msgstr "需要角色: {}"
#: api/lib/perm/acl/resp_format.py:33
msgid "To delete a user role, please operate on the User Management page!"
msgstr "删除用户角色, 请在 用户管理 页面操作!"
#: api/lib/perm/acl/resp_format.py:35
msgid "Application {} already exists"
msgstr "应用 {} 已经存在"
#: api/lib/perm/acl/resp_format.py:36
msgid "Application {} does not exist!"
msgstr "应用 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:37
msgid "The Secret is invalid"
msgstr "应用的Secret无效"
#: api/lib/perm/acl/resp_format.py:39
msgid "Resource {} does not exist!"
msgstr "资源 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:40
msgid "Resource {} already exists!"
msgstr "资源 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:42
msgid "Resource group {} does not exist!"
msgstr "资源组 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:43
msgid "Resource group {} already exists!"
msgstr "资源组 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:45
msgid "Inheritance detected infinite loop"
msgstr "继承检测到了死循环"
#: api/lib/perm/acl/resp_format.py:46
msgid "Role relationship {} does not exist!"
msgstr "角色关系 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:48
msgid "Trigger {} does not exist!"
msgstr "触发器 {} 不存在!"
#: api/lib/perm/acl/resp_format.py:49
msgid "Trigger {} already exists!"
msgstr "触发器 {} 已经存在!"
#: api/lib/perm/acl/resp_format.py:50
msgid "Trigger {} has been disabled!"
msgstr "Trigger {} has been disabled!"
#~ msgid "Not a valid date value."
#~ msgstr ""

View File

@@ -39,7 +39,7 @@ class LoginView(APIView):
password = request.values.get("password")
_role = None
config = AuthenticateDataCRUD(AuthenticateType.LDAP).get()
if config.get('LDAP', {}).get('enabled') or config.get('LDAP', {}).get('enable'):
if config.get('enabled') or config.get('enable'):
from api.lib.perm.authentication.ldap import authenticate_with_ldap
user, authenticated = authenticate_with_ldap(username, password)
else:

View File

@@ -43,9 +43,11 @@ class CIRelationSearchView(APIView):
facet = handle_arg_list(request.values.get("facet", ""))
sort = request.values.get("sort")
reverse = request.values.get("reverse") in current_app.config.get('BOOL_TRUE')
has_m2m = request.values.get("has_m2m") in current_app.config.get('BOOL_TRUE')
start = time.time()
s = Search(root_id, level, query, fl, facet, page, count, sort, reverse, ancestor_ids=ancestor_ids)
s = Search(root_id, level, query, fl, facet, page, count, sort, reverse,
ancestor_ids=ancestor_ids, has_m2m=has_m2m)
try:
response, counter, total, page, numfound, facet = s.search()
except SearchError as e:
@@ -69,9 +71,10 @@ class CIRelationStatisticsView(APIView):
level = request.values.get('level', 1)
type_ids = set(map(int, handle_arg_list(request.values.get('type_ids', []))))
ancestor_ids = request.values.get('ancestor_ids') or None # only for many to many
has_m2m = request.values.get("has_m2m") in current_app.config.get('BOOL_TRUE')
start = time.time()
s = Search(root_ids, level, ancestor_ids=ancestor_ids)
s = Search(root_ids, level, ancestor_ids=ancestor_ids, has_m2m=has_m2m)
try:
result = s.statistics(type_ids)
except SearchError as e:

View File

@@ -14,6 +14,7 @@ from api.lib.cmdb.cache import CITypeCache
from api.lib.cmdb.ci_type import CITypeAttributeGroupManager
from api.lib.cmdb.ci_type import CITypeAttributeManager
from api.lib.cmdb.ci_type import CITypeGroupManager
from api.lib.cmdb.ci_type import CITypeInheritanceManager
from api.lib.cmdb.ci_type import CITypeManager
from api.lib.cmdb.ci_type import CITypeTemplateManager
from api.lib.cmdb.ci_type import CITypeTriggerManager
@@ -43,9 +44,13 @@ class CITypeView(APIView):
q = request.args.get("type_name")
if type_id is not None:
ci_types = [CITypeCache.get(type_id).to_dict()]
ci_type = CITypeCache.get(type_id).to_dict()
ci_type['parent_ids'] = CITypeInheritanceManager.get_parents(type_id)
ci_types = [ci_type]
elif type_name is not None:
ci_types = [CITypeCache.get(type_name).to_dict()]
ci_type = CITypeCache.get(type_name).to_dict()
ci_type['parent_ids'] = CITypeInheritanceManager.get_parents(ci_type['id'])
ci_types = [ci_type]
else:
ci_types = CITypeManager().get_ci_types(q)
count = len(ci_types)
@@ -53,7 +58,7 @@ class CITypeView(APIView):
return self.jsonify(numfound=count, ci_types=ci_types)
@args_required("name")
@args_validate(CITypeManager.cls)
@args_validate(CITypeManager.cls, exclude_args=['parent_ids'])
def post(self):
params = request.values
@@ -84,6 +89,26 @@ class CITypeView(APIView):
return self.jsonify(type_id=type_id)
class CITypeInheritanceView(APIView):
url_prefix = ("/ci_types/inheritance",)
@args_required("parent_ids")
@args_required("child_id")
@has_perm_from_args("child_id", ResourceTypeEnum.CI, PermEnum.CONFIG, CITypeManager.get_name_by_id)
def post(self):
CITypeInheritanceManager.add(request.values['parent_ids'], request.values['child_id'])
return self.jsonify(**request.values)
@args_required("parent_id")
@args_required("child_id")
@has_perm_from_args("child_id", ResourceTypeEnum.CI, PermEnum.CONFIG, CITypeManager.get_name_by_id)
def delete(self):
CITypeInheritanceManager.delete(request.values['parent_id'], request.values['child_id'])
return self.jsonify(**request.values)
class CITypeGroupView(APIView):
url_prefix = ("/ci_types/groups",
"/ci_types/groups/config",
@@ -105,7 +130,6 @@ class CITypeGroupView(APIView):
return self.jsonify(group.to_dict())
@role_required(RoleEnum.CONFIG)
@args_validate(CITypeGroupManager.cls)
def put(self, gid=None):
if "/order" in request.url:
@@ -167,7 +191,8 @@ class CITypeAttributeView(APIView):
t = CITypeCache.get(type_id) or CITypeCache.get(type_name) or abort(404, ErrFormat.ci_type_not_found)
type_id = t.id
unique_id = t.unique_id
unique = AttributeCache.get(unique_id).name
unique = AttributeCache.get(unique_id)
unique = unique and unique.name
attr_filter = CIFilterPermsCRUD.get_attr_filter(type_id)
attributes = CITypeAttributeManager.get_attributes_by_type_id(type_id)
@@ -248,8 +273,8 @@ class CITypeAttributeTransferView(APIView):
@args_required('from')
@args_required('to')
def post(self, type_id):
_from = request.values.get('from') # {'attr_id': xx, 'group_id': xx}
_to = request.values.get('to') # {'group_id': xx, 'order': xxx}
_from = request.values.get('from') # {'attr_id': xx, 'group_id': xx, 'group_name': xx}
_to = request.values.get('to') # {'group_id': xx, 'group_name': xx, 'order': xxx}
CITypeAttributeManager.transfer(type_id, _from, _to)
@@ -262,8 +287,8 @@ class CITypeAttributeGroupTransferView(APIView):
@args_required('from')
@args_required('to')
def post(self, type_id):
_from = request.values.get('from') # group_id
_to = request.values.get('to') # group_id
_from = request.values.get('from') # group_id or group_name
_to = request.values.get('to') # group_id or group_name
CITypeAttributeGroupManager.transfer(type_id, _from, _to)
@@ -296,7 +321,7 @@ class CITypeAttributeGroupView(APIView):
attr_order = list(zip(attrs, orders))
group = CITypeAttributeGroupManager.create_or_update(type_id, name, attr_order, order)
current_app.logger.warning(group.id)
return self.jsonify(group_id=group.id)
@has_perm_from_args("type_id", ResourceTypeEnum.CI, PermEnum.CONFIG, CITypeManager.get_name_by_id)
@@ -310,21 +335,25 @@ class CITypeAttributeGroupView(APIView):
attr_order = list(zip(attrs, orders))
CITypeAttributeGroupManager.update(group_id, name, attr_order, order)
return self.jsonify(group_id=group_id)
@has_perm_from_args("type_id", ResourceTypeEnum.CI, PermEnum.CONFIG, CITypeManager.get_name_by_id)
def delete(self, group_id):
CITypeAttributeGroupManager.delete(group_id)
return self.jsonify(group_id=group_id)
class CITypeTemplateView(APIView):
url_prefix = ("/ci_types/template/import", "/ci_types/template/export")
url_prefix = ("/ci_types/template/import", "/ci_types/template/export", "/ci_types/<int:type_id>/template/export")
@role_required(RoleEnum.CONFIG)
def get(self): # export
return self.jsonify(
dict(ci_type_template=CITypeTemplateManager.export_template()))
def get(self, type_id=None): # export
if type_id is not None:
return self.jsonify(dict(ci_type_template=CITypeTemplateManager.export_template_by_type(type_id)))
return self.jsonify(dict(ci_type_template=CITypeTemplateManager.export_template()))
@role_required(RoleEnum.CONFIG)
def post(self): # import
@@ -458,13 +487,21 @@ class CITypeGrantView(APIView):
_type = CITypeCache.get(type_id)
type_name = _type and _type.name or abort(404, ErrFormat.ci_type_not_found)
acl = ACLManager('cmdb')
if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and \
not is_app_admin('cmdb'):
if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and not is_app_admin('cmdb'):
return abort(403, ErrFormat.no_permission.format(type_name, PermEnum.GRANT))
acl.grant_resource_to_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms)
acl.grant_resource_to_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms, rebuild=False)
CIFilterPermsCRUD().add(type_id=type_id, rid=rid, **request.values)
resource = None
if 'ci_filter' in request.values or 'attr_filter' in request.values:
resource = CIFilterPermsCRUD().add(type_id=type_id, rid=rid, **request.values)
if not resource:
from api.tasks.acl import role_rebuild
from api.lib.perm.acl.const import ACL_QUEUE
app_id = AppCache.get('cmdb').id
role_rebuild.apply_async(args=(rid, app_id), queue=ACL_QUEUE)
return self.jsonify(code=200)
@@ -482,21 +519,27 @@ class CITypeRevokeView(APIView):
_type = CITypeCache.get(type_id)
type_name = _type and _type.name or abort(404, ErrFormat.ci_type_not_found)
acl = ACLManager('cmdb')
if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and \
not is_app_admin('cmdb'):
if not acl.has_permission(type_name, ResourceTypeEnum.CI_TYPE, PermEnum.GRANT) and not is_app_admin('cmdb'):
return abort(403, ErrFormat.no_permission.format(type_name, PermEnum.GRANT))
acl.revoke_resource_from_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms)
acl.revoke_resource_from_role_by_rid(type_name, rid, ResourceTypeEnum.CI_TYPE, perms, rebuild=False)
if PermEnum.READ in perms:
CIFilterPermsCRUD().delete(type_id=type_id, rid=rid)
app_id = AppCache.get('cmdb').id
resource = None
if PermEnum.READ in perms or not perms:
resource = CIFilterPermsCRUD().delete(type_id=type_id, rid=rid)
app_id = AppCache.get('cmdb').id
users = RoleRelationCRUD.get_users_by_rid(rid, app_id)
for i in (users or []):
if i.get('role', {}).get('id') and not RoleCRUD.has_permission(
i.get('role').get('id'), type_name, ResourceTypeEnum.CI_TYPE, app_id, PermEnum.READ):
PreferenceManager.delete_by_type_id(type_id, i.get('uid'))
if not resource:
from api.tasks.acl import role_rebuild
from api.lib.perm.acl.const import ACL_QUEUE
role_rebuild.apply_async(args=(rid, app_id), queue=ACL_QUEUE)
users = RoleRelationCRUD.get_users_by_rid(rid, app_id)
for i in (users or []):
if i.get('role', {}).get('id') and not RoleCRUD.has_permission(
i.get('role').get('id'), type_name, ResourceTypeEnum.CI_TYPE, app_id, PermEnum.READ):
PreferenceManager.delete_by_type_id(type_id, i.get('uid'))
return self.jsonify(type_id=type_id, rid=rid)
@@ -507,4 +550,3 @@ class CITypeFilterPermissionView(APIView):
@auth_with_app_token
def get(self, type_id):
return self.jsonify(CIFilterPermsCRUD().get(type_id))

View File

@@ -2,6 +2,7 @@
from flask import abort
from flask import current_app
from flask import request
from api.lib.cmdb.ci_type import CITypeManager
@@ -187,3 +188,15 @@ class PreferenceRelationRevokeView(APIView):
acl.revoke_resource_from_role_by_rid(name, rid, ResourceTypeEnum.RELATION_VIEW, perms)
return self.jsonify(code=200)
class PreferenceCITypeOrderView(APIView):
url_prefix = ("/preference/ci_types/order",)
def post(self):
type_ids = request.values.get("type_ids")
is_tree = request.values.get("is_tree") in current_app.config.get('BOOL_TRUE')
PreferenceManager.upsert_ci_type_order(type_ids, is_tree)
return self.jsonify(type_ids=type_ids, is_tree=is_tree)

View File

@@ -62,7 +62,7 @@ class DepartmentView(APIView):
class DepartmentIDView(APIView):
url_prefix = (f'{prefix}/<int:_id>',)
def get(self, _id):
def put(self, _id):
form = DepartmentForm(MultiDict(request.json))
if not form.validate():
abort(400, ','.join(['{}: {}'.format(filed, ','.join(msg))

View File

@@ -46,6 +46,8 @@ class PostFileView(APIView):
if not file:
abort(400, ErrFormat.file_is_required)
extension = file.mimetype.split('/')[-1]
if '+' in extension:
extension = file.filename.split('.')[-1]
if file.filename == '':
filename = f'.{extension}'
else:

1
cmdb-api/babel.cfg Normal file
View File

@@ -0,0 +1 @@
[python: api/**.py]

View File

@@ -8,8 +8,9 @@ elasticsearch==7.17.9
email-validator==1.3.1
environs==4.2.0
flasgger==0.9.5
Flask==2.3.2
Flask==2.2.5
Flask-Bcrypt==1.0.1
flask-babel==4.0.0
Flask-Caching==2.0.2
Flask-Cors==4.0.0
Flask-Login>=0.6.2
@@ -45,7 +46,7 @@ supervisor==4.0.3
timeout-decorator==0.5.0
toposort==1.10
treelib==1.6.1
Werkzeug>=2.3.6
Werkzeug==2.2.3
WTForms==3.0.0
shamir~=17.12.0
pycryptodomex>=3.19.0

View File

@@ -13,7 +13,7 @@ const getAntdSerials = (color) => {
const themePluginOption = {
fileName: 'css/theme-colors-[contenthash:8].css',
matchColors: getAntdSerials('#1890ff'), // 主色系列
matchColors: getAntdSerials('#2f54eb'), // 主色系列
// 改变样式选择器,解决样式覆盖问题
changeSelector (selector) {
switch (selector) {

View File

@@ -27,7 +27,8 @@
"core-js": "^3.31.0",
"echarts": "^5.3.2",
"element-ui": "^2.15.10",
"exceljs": "^4.3.0",
"exceljs": "^4.4.0",
"file-saver": "^2.0.5",
"html2canvas": "^1.0.0-rc.5",
"is-buffer": "^2.0.5",
"jquery": "^3.6.0",
@@ -47,6 +48,7 @@
"vue-codemirror": "^4.0.6",
"vue-cropper": "^0.6.2",
"vue-grid-layout": "2.3.12",
"vue-i18n": "8.28.2",
"vue-infinite-scroll": "^2.0.2",
"vue-json-editor": "^1.4.3",
"vue-ls": "^3.2.1",

View File

@@ -1,5 +1,5 @@
<template>
<a-config-provider :locale="locale">
<a-config-provider :locale="antdLocale">
<div id="app" :class="{ 'ops-fullscreen': isOpsFullScreen, 'ops-only-topmenu': isOpsOnlyTopMenu }">
<router-view v-if="alive" />
</div>
@@ -7,8 +7,9 @@
</template>
<script>
import { mapActions } from 'vuex'
import { mapState, mapActions, mapMutations } from 'vuex'
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import enUS from 'ant-design-vue/lib/locale-provider/en_US'
import { AppDeviceEnquire } from '@/utils/mixin'
import { debounce } from './utils/util'
@@ -24,20 +25,28 @@ export default {
},
data() {
return {
locale: zhCN,
alive: true,
timer: null,
}
},
computed: {
...mapState(['locale']),
antdLocale() {
if (this.locale === 'zh') {
return zhCN
}
return enUS
},
isOpsFullScreen() {
return this.$route.name === 'cmdb_screen'
return ['cmdb_screen'].includes(this.$route.name)
},
isOpsOnlyTopMenu() {
return ['fullscreen_index', 'setting_person'].includes(this.$route.name)
return ['fullscreen_index', 'setting_person', 'notice_center'].includes(this.$route.name)
},
},
created() {
this.SET_LOCALE(localStorage.getItem('ops_locale') || 'zh')
this.$i18n.locale = localStorage.getItem('ops_locale') || 'zh'
this.timer = setInterval(() => {
this.setTime(new Date().getTime())
}, 1000)
@@ -184,6 +193,7 @@ export default {
},
methods: {
...mapActions(['setTime']),
...mapMutations(['SET_LOCALE']),
reload() {
this.alive = false
this.$nextTick(() => {

View File

@@ -1,29 +1,37 @@
export const ruleTypeList = [
{ value: 'and', label: '与' },
{ value: 'or', label: '或' },
// { value: 'not', label: '非' },
]
import i18n from '@/lang'
export const expList = [
{ value: 'is', label: '等于' },
{ value: '~is', label: '不等于' },
{ value: 'contain', label: '包含' },
{ value: '~contain', label: '不包含' },
{ value: 'start_with', label: '以...开始' },
{ value: '~start_with', label: '不以...开始' },
{ value: 'end_with', label: '以...结束' },
{ value: '~end_with', label: '不以...结束' },
{ value: '~value', label: '为空' }, // 为空的定义有点绕
{ value: 'value', label: '不为空' },
]
export const ruleTypeList = () => {
return [
{ value: 'and', label: i18n.t('cmdbFilterComp.and') },
{ value: 'or', label: i18n.t('cmdbFilterComp.or') },
// { value: 'not', label: '非' },
]
}
export const advancedExpList = [
{ value: 'in', label: 'in查询' },
{ value: '~in', label: '非in查询' },
{ value: 'range', label: '范围' },
{ value: '~range', label: '范围外' },
{ value: 'compare', label: '比较' },
]
export const expList = () => {
return [
{ value: 'is', label: i18n.t('cmdbFilterComp.is') },
{ value: '~is', label: i18n.t('cmdbFilterComp.~is') },
{ value: 'contain', label: i18n.t('cmdbFilterComp.contain') },
{ value: '~contain', label: i18n.t('cmdbFilterComp.~contain') },
{ value: 'start_with', label: i18n.t('cmdbFilterComp.start_with') },
{ value: '~start_with', label: i18n.t('cmdbFilterComp.~start_with') },
{ value: 'end_with', label: i18n.t('cmdbFilterComp.end_with') },
{ value: '~end_with', label: i18n.t('cmdbFilterComp.~end_with') },
{ value: '~value', label: i18n.t('cmdbFilterComp.~value') }, // 为空的定义有点绕
{ value: 'value', label: i18n.t('cmdbFilterComp.value') },
]
}
export const advancedExpList = () => {
return [
{ value: 'in', label: i18n.t('cmdbFilterComp.in') },
{ value: '~in', label: i18n.t('cmdbFilterComp.~in') },
{ value: 'range', label: i18n.t('cmdbFilterComp.range') },
{ value: '~range', label: i18n.t('cmdbFilterComp.~range') },
{ value: 'compare', label: i18n.t('cmdbFilterComp.compare') },
]
}
export const compareTypeList = [
{ value: '1', label: '>' },

View File

@@ -1,293 +1,332 @@
<template>
<div>
<a-space :style="{ display: 'flex', marginBottom: '10px' }" v-for="(item, index) in ruleList" :key="item.id">
<div :style="{ width: '50px', height: '24px', position: 'relative' }">
<treeselect
v-if="index"
class="custom-treeselect"
:style="{ width: '50px', '--custom-height': '24px', position: 'absolute', top: '-17px', left: 0 }"
v-model="item.type"
:multiple="false"
:clearable="false"
searchable
:options="ruleTypeList"
:normalizer="
(node) => {
return {
id: node.value,
label: node.label,
children: node.children,
}
}
"
>
</treeselect>
</div>
<treeselect
class="custom-treeselect"
:style="{ width: '130px', '--custom-height': '24px' }"
v-model="item.property"
:multiple="false"
:clearable="false"
searchable
:options="canSearchPreferenceAttrList"
:normalizer="
(node) => {
return {
id: node.name,
label: node.alias || node.name,
children: node.children,
}
}
"
appendToBody
:zIndex="1050"
>
<div
:title="node.label"
slot="option-label"
slot-scope="{ node }"
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
>
<ValueTypeMapIcon :attr="node.raw" />
{{ node.label }}
</div>
<div
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
slot="value-label"
slot-scope="{ node }"
>
<ValueTypeMapIcon :attr="node.raw" /> {{ node.label }}
</div>
</treeselect>
<treeselect
class="custom-treeselect"
:style="{ width: '100px', '--custom-height': '24px' }"
v-model="item.exp"
:multiple="false"
:clearable="false"
searchable
:options="[...getExpListByProperty(item.property), ...advancedExpList]"
:normalizer="
(node) => {
return {
id: node.value,
label: node.label,
children: node.children,
}
}
"
@select="(value) => handleChangeExp(value, item, index)"
appendToBody
:zIndex="1050"
>
</treeselect>
<treeselect
class="custom-treeselect"
:style="{ width: '175px', '--custom-height': '24px' }"
v-model="item.value"
:multiple="false"
:clearable="false"
searchable
v-if="isChoiceByProperty(item.property) && (item.exp === 'is' || item.exp === '~is')"
:options="getChoiceValueByProperty(item.property)"
placeholder="请选择"
:normalizer="
(node) => {
return {
id: node[0],
label: node[0],
children: node.children,
}
}
"
appendToBody
:zIndex="1050"
>
<div
:title="node.label"
slot="option-label"
slot-scope="{ node }"
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
>
{{ node.label }}
</div>
</treeselect>
<a-input-group
size="small"
compact
v-else-if="item.exp === 'range' || item.exp === '~range'"
:style="{ width: '175px' }"
>
<a-input class="ops-input" size="small" v-model="item.min" :style="{ width: '78px' }" placeholder="最小值" />
~
<a-input class="ops-input" size="small" v-model="item.max" :style="{ width: '78px' }" placeholder="最大值" />
</a-input-group>
<a-input-group size="small" compact v-else-if="item.exp === 'compare'" :style="{ width: '175px' }">
<treeselect
class="custom-treeselect"
:style="{ width: '60px', '--custom-height': '24px' }"
v-model="item.compareType"
:multiple="false"
:clearable="false"
searchable
:options="compareTypeList"
:normalizer="
(node) => {
return {
id: node.value,
label: node.label,
children: node.children,
}
}
"
appendToBody
:zIndex="1050"
>
</treeselect>
<a-input class="ops-input" v-model="item.value" size="small" style="width: 113px" />
</a-input-group>
<a-input
v-else-if="item.exp !== 'value' && item.exp !== '~value'"
size="small"
v-model="item.value"
:placeholder="item.exp === 'in' || item.exp === '~in' ? '以 ; 分隔' : ''"
class="ops-input"
></a-input>
<div v-else :style="{ width: '175px' }"></div>
<a-tooltip title="复制">
<a class="operation" @click="handleCopyRule(item)"><ops-icon type="icon-xianxing-copy"/></a>
</a-tooltip>
<a-tooltip title="删除">
<a class="operation" @click="handleDeleteRule(item)"><ops-icon type="icon-xianxing-delete"/></a>
</a-tooltip>
</a-space>
<div class="table-filter-add">
<a @click="handleAddRule">+ 新增</a>
</div>
</div>
</template>
<script>
import _ from 'lodash'
import { v4 as uuidv4 } from 'uuid'
import { ruleTypeList, expList, advancedExpList, compareTypeList } from './constants'
import ValueTypeMapIcon from '../CMDBValueTypeMapIcon'
export default {
name: 'Expression',
components: { ValueTypeMapIcon },
model: {
prop: 'value',
event: 'change',
},
props: {
value: {
type: Array,
default: () => [],
},
canSearchPreferenceAttrList: {
type: Array,
required: true,
default: () => [],
},
},
data() {
return {
ruleTypeList,
expList,
advancedExpList,
compareTypeList,
}
},
computed: {
ruleList: {
get() {
return this.value
},
set(val) {
this.$emit('change', val)
return val
},
},
},
methods: {
getExpListByProperty(property) {
if (property) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
if (_find && ['0', '1', '3', '4', '5'].includes(_find.value_type)) {
return [
{ value: 'is', label: '等于' },
{ value: '~is', label: '不等于' },
{ value: '~value', label: '为空' }, // 为空的定义有点绕
{ value: 'value', label: '不为空' },
]
}
return this.expList
}
return this.expList
},
isChoiceByProperty(property) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
if (_find) {
return _find.is_choice
}
return false
},
handleAddRule() {
this.ruleList.push({
id: uuidv4(),
type: 'and',
property: this.canSearchPreferenceAttrList[0]?.name,
exp: 'is',
value: null,
})
this.$emit('change', this.ruleList)
},
handleCopyRule(item) {
this.ruleList.push({ ...item, id: uuidv4() })
this.$emit('change', this.ruleList)
},
handleDeleteRule(item) {
const idx = this.ruleList.findIndex((r) => r.id === item.id)
if (idx > -1) {
this.ruleList.splice(idx, 1)
}
this.$emit('change', this.ruleList)
},
getChoiceValueByProperty(property) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
if (_find) {
return _find.choice_value
}
return []
},
handleChangeExp({ value }, item, index) {
const _ruleList = _.cloneDeep(this.ruleList)
if (value === 'range') {
_ruleList[index] = {
..._ruleList[index],
min: '',
max: '',
exp: value,
}
} else if (value === 'compare') {
_ruleList[index] = {
..._ruleList[index],
compareType: '1',
exp: value,
}
} else {
_ruleList[index] = {
..._ruleList[index],
exp: value,
}
}
this.ruleList = _ruleList
this.$emit('change', this.ruleList)
},
},
}
</script>
<style></style>
<template>
<div>
<a-space :style="{ display: 'flex', marginBottom: '10px' }" v-for="(item, index) in ruleList" :key="item.id">
<div :style="{ width: '70px', height: '24px', position: 'relative' }">
<treeselect
v-if="index"
class="custom-treeselect"
:style="{ width: '70px', '--custom-height': '24px', position: 'absolute', top: '-17px', left: 0 }"
v-model="item.type"
:multiple="false"
:clearable="false"
searchable
:options="ruleTypeList"
:normalizer="
(node) => {
return {
id: node.value,
label: node.label,
children: node.children,
}
}
"
>
</treeselect>
</div>
<treeselect
class="custom-treeselect"
:style="{ width: '130px', '--custom-height': '24px' }"
v-model="item.property"
:multiple="false"
:clearable="false"
searchable
:options="canSearchPreferenceAttrList"
:normalizer="
(node) => {
return {
id: node.name,
label: node.alias || node.name,
children: node.children,
}
}
"
appendToBody
:zIndex="1050"
>
<div
:title="node.label"
slot="option-label"
slot-scope="{ node }"
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
>
<ValueTypeMapIcon :attr="node.raw" />
{{ node.label }}
</div>
<div
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
slot="value-label"
slot-scope="{ node }"
>
<ValueTypeMapIcon :attr="node.raw" /> {{ node.label }}
</div>
</treeselect>
<treeselect
class="custom-treeselect"
:style="{ width: '100px', '--custom-height': '24px' }"
v-model="item.exp"
:multiple="false"
:clearable="false"
searchable
:options="[...getExpListByProperty(item.property), ...advancedExpList]"
:normalizer="
(node) => {
return {
id: node.value,
label: node.label,
children: node.children,
}
}
"
@select="(value) => handleChangeExp(value, item, index)"
appendToBody
:zIndex="1050"
>
</treeselect>
<treeselect
class="custom-treeselect"
:style="{ width: '175px', '--custom-height': '24px' }"
v-model="item.value"
:multiple="false"
:clearable="false"
searchable
v-if="isChoiceByProperty(item.property) && (item.exp === 'is' || item.exp === '~is')"
:options="getChoiceValueByProperty(item.property)"
:placeholder="$t('placeholder2')"
:normalizer="
(node) => {
return {
id: node[0],
label: node[0],
children: node.children,
}
}
"
appendToBody
:zIndex="1050"
>
<div
:title="node.label"
slot="option-label"
slot-scope="{ node }"
:style="{ width: '100%', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }"
>
{{ node.label }}
</div>
</treeselect>
<a-input-group
size="small"
compact
v-else-if="item.exp === 'range' || item.exp === '~range'"
:style="{ width: '175px' }"
>
<a-input
class="ops-input"
size="small"
v-model="item.min"
:style="{ width: '78px' }"
:placeholder="$t('min')"
/>
~
<a-input
class="ops-input"
size="small"
v-model="item.max"
:style="{ width: '78px' }"
:placeholder="$t('max')"
/>
</a-input-group>
<a-input-group size="small" compact v-else-if="item.exp === 'compare'" :style="{ width: '175px' }">
<treeselect
class="custom-treeselect"
:style="{ width: '60px', '--custom-height': '24px' }"
v-model="item.compareType"
:multiple="false"
:clearable="false"
searchable
:options="compareTypeList"
:normalizer="
(node) => {
return {
id: node.value,
label: node.label,
children: node.children,
}
}
"
appendToBody
:zIndex="1050"
>
</treeselect>
<a-input class="ops-input" v-model="item.value" size="small" style="width: 113px" />
</a-input-group>
<a-input
v-else-if="item.exp !== 'value' && item.exp !== '~value'"
size="small"
v-model="item.value"
:placeholder="item.exp === 'in' || item.exp === '~in' ? $t('cmdbFilterComp.split', { separator: ';' }) : ''"
class="ops-input"
:style="{ width: '175px' }"
></a-input>
<div v-else :style="{ width: '175px' }"></div>
<a-tooltip :title="$t('copy')">
<a class="operation" @click="handleCopyRule(item)"><ops-icon type="icon-xianxing-copy"/></a>
</a-tooltip>
<a-tooltip :title="$t('delete')">
<a class="operation" @click="handleDeleteRule(item)"><ops-icon type="icon-xianxing-delete"/></a>
</a-tooltip>
<a-tooltip :title="$t('cmdbFilterComp.addHere')" v-if="needAddHere">
<a class="operation" @click="handleAddRuleAt(item)"><a-icon type="plus-circle"/></a>
</a-tooltip>
</a-space>
<div class="table-filter-add">
<a @click="handleAddRule">+ {{ $t('new') }}</a>
</div>
</div>
</template>
<script>
import _ from 'lodash'
import { v4 as uuidv4 } from 'uuid'
import { ruleTypeList, expList, advancedExpList, compareTypeList } from './constants'
import ValueTypeMapIcon from '../CMDBValueTypeMapIcon'
export default {
name: 'Expression',
components: { ValueTypeMapIcon },
model: {
prop: 'value',
event: 'change',
},
props: {
value: {
type: Array,
default: () => [],
},
canSearchPreferenceAttrList: {
type: Array,
required: true,
default: () => [],
},
needAddHere: {
type: Boolean,
default: false,
},
},
data() {
return {
compareTypeList,
}
},
computed: {
ruleList: {
get() {
return this.value
},
set(val) {
this.$emit('change', val)
return val
},
},
ruleTypeList() {
return ruleTypeList()
},
expList() {
return expList()
},
advancedExpList() {
return advancedExpList()
},
},
methods: {
getExpListByProperty(property) {
if (property) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
if (_find && ['0', '1', '3', '4', '5'].includes(_find.value_type)) {
return [
{ value: 'is', label: this.$t('cmdbFilterComp.is') },
{ value: '~is', label: this.$t('cmdbFilterComp.~is') },
{ value: '~value', label: this.$t('cmdbFilterComp.~value') }, // 为空的定义有点绕
{ value: 'value', label: this.$t('cmdbFilterComp.value') },
]
}
return this.expList
}
return this.expList
},
isChoiceByProperty(property) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
if (_find) {
return _find.is_choice
}
return false
},
handleAddRule() {
this.ruleList.push({
id: uuidv4(),
type: 'and',
property: this.canSearchPreferenceAttrList[0]?.name,
exp: 'is',
value: null,
})
this.$emit('change', this.ruleList)
},
handleCopyRule(item) {
this.ruleList.push({ ...item, id: uuidv4() })
this.$emit('change', this.ruleList)
},
handleDeleteRule(item) {
const idx = this.ruleList.findIndex((r) => r.id === item.id)
if (idx > -1) {
this.ruleList.splice(idx, 1)
}
this.$emit('change', this.ruleList)
},
handleAddRuleAt(item) {
const idx = this.ruleList.findIndex((r) => r.id === item.id)
if (idx > -1) {
this.ruleList.splice(idx, 0, {
id: uuidv4(),
type: 'and',
property: this.canSearchPreferenceAttrList[0]?.name,
exp: 'is',
value: null,
})
}
this.$emit('change', this.ruleList)
},
getChoiceValueByProperty(property) {
const _find = this.canSearchPreferenceAttrList.find((item) => item.name === property)
if (_find) {
return _find.choice_value
}
return []
},
handleChangeExp({ value }, item, index) {
const _ruleList = _.cloneDeep(this.ruleList)
if (value === 'range') {
_ruleList[index] = {
..._ruleList[index],
min: '',
max: '',
exp: value,
}
} else if (value === 'compare') {
_ruleList[index] = {
..._ruleList[index],
compareType: '1',
exp: value,
}
} else {
_ruleList[index] = {
..._ruleList[index],
exp: value,
}
}
this.ruleList = _ruleList
this.$emit('change', this.ruleList)
},
},
}
</script>
<style></style>

View File

@@ -1,290 +1,296 @@
<template>
<div>
<a-popover
v-if="isDropdown"
v-model="visible"
trigger="click"
:placement="placement"
overlayClassName="table-filter"
@visibleChange="visibleChange"
>
<slot name="popover_item">
<a-button type="primary" ghost>条件过滤<a-icon type="filter"/></a-button>
</slot>
<template slot="content">
<Expression
v-model="ruleList"
:canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)"
/>
<a-divider :style="{ margin: '10px 0' }" />
<div style="width:534px">
<a-space :style="{ display: 'flex', justifyContent: 'flex-end' }">
<a-button type="primary" size="small" @click="handleSubmit">确定</a-button>
<a-button size="small" @click="handleClear">清空</a-button>
</a-space>
</div>
</template>
</a-popover>
<Expression
v-else
v-model="ruleList"
:canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)"
/>
</div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid'
import Expression from './expression.vue'
import { advancedExpList, compareTypeList } from './constants'
export default {
name: 'FilterComp',
components: { Expression },
props: {
canSearchPreferenceAttrList: {
type: Array,
required: true,
default: () => [],
},
expression: {
type: String,
default: '',
},
regQ: {
type: String,
default: '(?<=q=).+(?=&)|(?<=q=).+$',
},
placement: {
type: String,
default: 'bottomRight',
},
isDropdown: {
type: Boolean,
default: true,
},
},
data() {
return {
advancedExpList,
compareTypeList,
visible: false,
ruleList: [],
filterExp: '',
}
},
methods: {
visibleChange(open, isInitOne = true) {
// isInitOne 初始化exp为空时ruleList是否默认给一条
// const regQ = /(?<=q=).+(?=&)|(?<=q=).+$/g
const exp = this.expression.match(new RegExp(this.regQ, 'g'))
? this.expression.match(new RegExp(this.regQ, 'g'))[0]
: null
if (open && exp) {
const expArray = exp.split(',').map((item) => {
let has_not = ''
const key = item.split(':')[0]
const val = item
.split(':')
.slice(1)
.join(':')
let type, property, exp, value, min, max, compareType
if (key.includes('-')) {
type = 'or'
if (key.includes('~')) {
property = key.substring(2)
has_not = '~'
} else {
property = key.substring(1)
}
} else {
type = 'and'
if (key.includes('~')) {
property = key.substring(1)
has_not = '~'
} else {
property = key
}
}
const in_reg = /(?<=\().+(?=\))/g
const range_reg = /(?<=\[).+(?=\])/g
const compare_reg = /(?<=>=|<=|>(?!=)|<(?!=)).+/
if (val === '*') {
exp = has_not + 'value'
value = ''
} else if (in_reg.test(val)) {
exp = has_not + 'in'
value = val.match(in_reg)[0]
} else if (range_reg.test(val)) {
exp = has_not + 'range'
value = val.match(range_reg)[0]
min = value.split('_TO_')[0]
max = value.split('_TO_')[1]
} else if (compare_reg.test(val)) {
exp = has_not + 'compare'
value = val.match(compare_reg)[0]
const _compareType = val.substring(0, val.match(compare_reg)['index'])
const idx = compareTypeList.findIndex((item) => item.label === _compareType)
compareType = compareTypeList[idx].value
} else if (!val.includes('*')) {
exp = has_not + 'is'
value = val
} else {
const resList = [
['contain', /(?<=\*).*(?=\*)/g],
['end_with', /(?<=\*).+/g],
['start_with', /.+(?=\*)/g],
]
for (let i = 0; i < 3; i++) {
const reg = resList[i]
if (reg[1].test(val)) {
exp = has_not + reg[0]
value = val.match(reg[1])[0]
break
}
}
}
return {
id: uuidv4(),
type,
property,
exp,
value,
min,
max,
compareType,
}
})
this.ruleList = [...expArray]
} else if (open) {
const _canSearchPreferenceAttrList = this.canSearchPreferenceAttrList.filter((attr) => !attr.is_password)
this.ruleList = isInitOne
? [
{
id: uuidv4(),
type: 'and',
property:
_canSearchPreferenceAttrList && _canSearchPreferenceAttrList.length
? _canSearchPreferenceAttrList[0].name
: undefined,
exp: 'is',
value: null,
},
]
: []
}
},
handleClear() {
this.ruleList = [
{
id: uuidv4(),
type: 'and',
property: this.canSearchPreferenceAttrList[0].name,
exp: 'is',
value: null,
},
]
this.filterExp = ''
this.visible = false
this.$emit('setExpFromFilter', this.filterExp)
},
handleSubmit() {
if (this.ruleList && this.ruleList.length) {
this.ruleList[0].type = 'and' // 增删后以防万一第一个不是and
this.filterExp = ''
const expList = this.ruleList.map((rule) => {
let singleRuleExp = ''
let _exp = rule.exp
if (rule.type === 'or') {
singleRuleExp += '-'
}
if (rule.exp.includes('~')) {
singleRuleExp += '~'
_exp = rule.exp.split('~')[1]
}
singleRuleExp += `${rule.property}:`
if (_exp === 'is') {
singleRuleExp += `${rule.value ?? ''}`
}
if (_exp === 'contain') {
singleRuleExp += `*${rule.value ?? ''}*`
}
if (_exp === 'start_with') {
singleRuleExp += `${rule.value ?? ''}*`
}
if (_exp === 'end_with') {
singleRuleExp += `*${rule.value ?? ''}`
}
if (_exp === 'value') {
singleRuleExp += `*`
}
if (_exp === 'in') {
singleRuleExp += `(${rule.value ?? ''})`
}
if (_exp === 'range') {
singleRuleExp += `[${rule.min}_TO_${rule.max}]`
}
if (_exp === 'compare') {
const idx = compareTypeList.findIndex((item) => item.value === rule.compareType)
singleRuleExp += `${compareTypeList[idx].label}${rule.value ?? ''}`
}
return singleRuleExp
})
this.filterExp = expList.join(',')
this.$emit('setExpFromFilter', this.filterExp)
} else {
this.$emit('setExpFromFilter', '')
}
this.visible = false
},
},
}
</script>
<style lang="less" scoped>
.table-filter {
.table-filter-add {
margin-top: 10px;
& > a {
padding: 2px 8px;
&:hover {
background-color: #f0faff;
border-radius: 5px;
}
}
}
.table-filter-extra-icon {
padding: 0px 2px;
&:hover {
display: inline-block;
border-radius: 5px;
background-color: #f0faff;
}
}
}
</style>
<style lang="less">
.table-filter-extra-operation {
.ant-popover-inner-content {
padding: 3px 4px;
.operation {
cursor: pointer;
width: 90px;
height: 30px;
line-height: 30px;
padding: 3px 4px;
border-radius: 5px;
transition: all 0.3s;
&:hover {
background-color: #f0faff;
}
> .anticon {
margin-right: 10px;
}
}
}
}
</style>
<template>
<div>
<a-popover
v-if="isDropdown"
v-model="visible"
trigger="click"
:placement="placement"
overlayClassName="table-filter"
@visibleChange="visibleChange"
>
<slot name="popover_item">
<a-button type="primary" ghost>{{ $t('cmdbFilterComp.conditionFilter') }}<a-icon type="filter"/></a-button>
</slot>
<template slot="content">
<Expression
:needAddHere="needAddHere"
v-model="ruleList"
:canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)"
/>
<a-divider :style="{ margin: '10px 0' }" />
<div style="width:554px">
<a-space :style="{ display: 'flex', justifyContent: 'flex-end' }">
<a-button type="primary" size="small" @click="handleSubmit">{{ $t('confirm') }}</a-button>
<a-button size="small" @click="handleClear">{{ $t('clear') }}</a-button>
</a-space>
</div>
</template>
</a-popover>
<Expression
:needAddHere="needAddHere"
v-else
v-model="ruleList"
:canSearchPreferenceAttrList="canSearchPreferenceAttrList.filter((attr) => !attr.is_password)"
/>
</div>
</template>
<script>
import { v4 as uuidv4 } from 'uuid'
import Expression from './expression.vue'
import { advancedExpList, compareTypeList } from './constants'
export default {
name: 'FilterComp',
components: { Expression },
props: {
canSearchPreferenceAttrList: {
type: Array,
required: true,
default: () => [],
},
expression: {
type: String,
default: '',
},
regQ: {
type: String,
default: '(?<=q=).+(?=&)|(?<=q=).+$',
},
placement: {
type: String,
default: 'bottomRight',
},
isDropdown: {
type: Boolean,
default: true,
},
needAddHere: {
type: Boolean,
default: false,
},
},
data() {
return {
advancedExpList,
compareTypeList,
visible: false,
ruleList: [],
filterExp: '',
}
},
methods: {
visibleChange(open, isInitOne = true) {
// isInitOne 初始化exp为空时ruleList是否默认给一条
// const regQ = /(?<=q=).+(?=&)|(?<=q=).+$/g
const exp = this.expression.match(new RegExp(this.regQ, 'g'))
? this.expression.match(new RegExp(this.regQ, 'g'))[0]
: null
if (open && exp) {
const expArray = exp.split(',').map((item) => {
let has_not = ''
const key = item.split(':')[0]
const val = item
.split(':')
.slice(1)
.join(':')
let type, property, exp, value, min, max, compareType
if (key.includes('-')) {
type = 'or'
if (key.includes('~')) {
property = key.substring(2)
has_not = '~'
} else {
property = key.substring(1)
}
} else {
type = 'and'
if (key.includes('~')) {
property = key.substring(1)
has_not = '~'
} else {
property = key
}
}
const in_reg = /(?<=\().+(?=\))/g
const range_reg = /(?<=\[).+(?=\])/g
const compare_reg = /(?<=>=|<=|>(?!=)|<(?!=)).+/
if (val === '*') {
exp = has_not + 'value'
value = ''
} else if (in_reg.test(val)) {
exp = has_not + 'in'
value = val.match(in_reg)[0]
} else if (range_reg.test(val)) {
exp = has_not + 'range'
value = val.match(range_reg)[0]
min = value.split('_TO_')[0]
max = value.split('_TO_')[1]
} else if (compare_reg.test(val)) {
exp = has_not + 'compare'
value = val.match(compare_reg)[0]
const _compareType = val.substring(0, val.match(compare_reg)['index'])
const idx = compareTypeList.findIndex((item) => item.label === _compareType)
compareType = compareTypeList[idx].value
} else if (!val.includes('*')) {
exp = has_not + 'is'
value = val
} else {
const resList = [
['contain', /(?<=\*).*(?=\*)/g],
['end_with', /(?<=\*).+/g],
['start_with', /.+(?=\*)/g],
]
for (let i = 0; i < 3; i++) {
const reg = resList[i]
if (reg[1].test(val)) {
exp = has_not + reg[0]
value = val.match(reg[1])[0]
break
}
}
}
return {
id: uuidv4(),
type,
property,
exp,
value,
min,
max,
compareType,
}
})
this.ruleList = [...expArray]
} else if (open) {
const _canSearchPreferenceAttrList = this.canSearchPreferenceAttrList.filter((attr) => !attr.is_password)
this.ruleList = isInitOne
? [
{
id: uuidv4(),
type: 'and',
property:
_canSearchPreferenceAttrList && _canSearchPreferenceAttrList.length
? _canSearchPreferenceAttrList[0].name
: undefined,
exp: 'is',
value: null,
},
]
: []
}
},
handleClear() {
this.ruleList = [
{
id: uuidv4(),
type: 'and',
property: this.canSearchPreferenceAttrList[0].name,
exp: 'is',
value: null,
},
]
this.filterExp = ''
this.visible = false
this.$emit('setExpFromFilter', this.filterExp)
},
handleSubmit() {
if (this.ruleList && this.ruleList.length) {
this.ruleList[0].type = 'and' // 增删后以防万一第一个不是and
this.filterExp = ''
const expList = this.ruleList.map((rule) => {
let singleRuleExp = ''
let _exp = rule.exp
if (rule.type === 'or') {
singleRuleExp += '-'
}
if (rule.exp.includes('~')) {
singleRuleExp += '~'
_exp = rule.exp.split('~')[1]
}
singleRuleExp += `${rule.property}:`
if (_exp === 'is') {
singleRuleExp += `${rule.value ?? ''}`
}
if (_exp === 'contain') {
singleRuleExp += `*${rule.value ?? ''}*`
}
if (_exp === 'start_with') {
singleRuleExp += `${rule.value ?? ''}*`
}
if (_exp === 'end_with') {
singleRuleExp += `*${rule.value ?? ''}`
}
if (_exp === 'value') {
singleRuleExp += `*`
}
if (_exp === 'in') {
singleRuleExp += `(${rule.value ?? ''})`
}
if (_exp === 'range') {
singleRuleExp += `[${rule.min}_TO_${rule.max}]`
}
if (_exp === 'compare') {
const idx = compareTypeList.findIndex((item) => item.value === rule.compareType)
singleRuleExp += `${compareTypeList[idx].label}${rule.value ?? ''}`
}
return singleRuleExp
})
this.filterExp = expList.join(',')
this.$emit('setExpFromFilter', this.filterExp)
} else {
this.$emit('setExpFromFilter', '')
}
this.visible = false
},
},
}
</script>
<style lang="less" scoped>
.table-filter {
.table-filter-add {
margin-top: 10px;
& > a {
padding: 2px 8px;
&:hover {
background-color: #f0faff;
border-radius: 5px;
}
}
}
.table-filter-extra-icon {
padding: 0px 2px;
&:hover {
display: inline-block;
border-radius: 5px;
background-color: #f0faff;
}
}
}
</style>
<style lang="less">
.table-filter-extra-operation {
.ant-popover-inner-content {
padding: 3px 4px;
.operation {
cursor: pointer;
width: 90px;
height: 30px;
line-height: 30px;
padding: 3px 4px;
border-radius: 5px;
transition: all 0.3s;
&:hover {
background-color: #f0faff;
}
> .anticon {
margin-right: 10px;
}
}
}
}
</style>

View File

@@ -89,20 +89,23 @@ export default {
},
},
data() {
const keyMapList = [
{ value: 'default', label: '默认' },
{ value: 'vim', label: 'vim' },
{ value: 'emacs', label: 'emacs' },
{ value: 'sublime', label: 'sublime' },
]
return {
keyMapList,
coder: null,
fontSize: 14,
keyMap: 'default',
fullscreenExitVisible: false,
}
},
computed: {
keyMapList() {
return [
{ value: 'default', label: this.$t('default') },
{ value: 'vim', label: 'vim' },
{ value: 'emacs', label: 'emacs' },
{ value: 'sublime', label: 'sublime' },
]
},
},
mounted() {},
methods: {
initCodeMirror(codeContent) {

View File

@@ -1,8 +1,10 @@
export const iconTypeList = [
import i18n from '@/lang'
export const iconTypeList = () => [
// { value: '0', label: '常用' },
{ value: '1', label: '线性' },
{ value: '2', label: '实底' },
{ value: '3', label: '多色' }
{ value: '1', label: i18n.t('customIconSelect.outlined') },
{ value: '2', label: i18n.t('customIconSelect.filled') },
{ value: '3', label: i18n.t('customIconSelect.multicolor') }
]
export const commonIconList = ['changyong-ubuntu',

View File

@@ -16,7 +16,7 @@
{{ item.label }}
</div>
<div :class="`${currentIconType === '4' ? 'selected' : ''}`" @click="handleChangeIconType('4')">
自定义
{{ this.$t('customIconSelect.custom') }}
</div>
<a-upload
slot="description"
@@ -26,7 +26,7 @@
accept=".svg,.png,.jpg,.jpeg"
v-if="currentIconType === '4'"
>
<a-button icon="plus" size="small" type="primary">添加</a-button>
<a-button icon="plus" size="small" type="primary">{{ $t('add') }}</a-button>
</a-upload>
</div>
<div class="custom-icon-select-popover-content">
@@ -55,11 +55,11 @@
@click="clickCustomIcon(icon)"
>
<div class="custom-icon-select-popover-content-img-box">
<img :src="`/api/common-setting/v1/file/${icon.data.url}`" />
<img v-if="icon.data && icon.data.url" :src="`/api/common-setting/v1/file/${icon.data.url}`" />
<a-popconfirm
overlayClassName="custom-icon-select-confirm-popover"
:getPopupContainer="(trigger) => trigger.parentNode"
title="确认删除?"
:title="$t('confirmDelete')"
@confirm="(e) => deleteIcon(e, icon)"
@cancel="
(e) => {
@@ -92,7 +92,7 @@
:show-upload-list="false"
accept=".svg,.png,.jpg,.jpeg"
>
<a> 暂无自定义图标点击此处上传 </a>
<a> {{ $t('customIconSelect.nodata') }} </a>
</a-upload>
</a-empty>
</div>
@@ -102,27 +102,27 @@
</template>
<a-form class="custom-icon-select-form" :form="form" v-show="currentIconType === '4' && formVisible">
<a-form-item
label="名称"
:label="$t('name')"
:labelCol="{ span: 4 }"
:wrapperCol="{ span: 16 }"
><a-input
v-decorator="['name', { rules: [{ required: true, message: '请输入名称' }] }]"
v-decorator="['name', { rules: [{ required: true, message: $t('placeholder1') }] }]"
/></a-form-item>
<a-form-item label="预览" :labelCol="{ span: 4 }">
<a-form-item :label="$t('customIconSelect.preview')" :labelCol="{ span: 4 }">
<div class="custom-icon-select-form-img">
<img :src="formImg" />
</div>
</a-form-item>
<a-form-item label=" " :colon="false" :labelCol="{ span: 16 }">
<a-space>
<a-button size="small" @click="handleCancel">取消</a-button>
<a-button size="small" type="primary" @click="handleOk">确定</a-button>
<a-button size="small" @click="handleCancel">{{ $t('cancel') }}</a-button>
<a-button size="small" type="primary" @click="handleOk">{{ $t('confirm') }}</a-button>
</a-space>
</a-form-item>
</a-form>
</div>
<div class="custom-icon-select-block" id="custom-icon-select-block" @click="showSelect">
<div class="custom-icon-select-block" :id="`custom-icon-select-block-${uuid}`" @click="showSelect">
<img v-if="value.id && value.url" :src="`/api/common-setting/v1/file/${value.url}`" />
<ops-icon
v-else
@@ -134,6 +134,7 @@
</template>
<script>
import { v4 as uuidv4 } from 'uuid'
import { ColorPicker } from 'element-ui'
import {
iconTypeList,
@@ -166,7 +167,6 @@ export default {
data() {
return {
form: this.$form.createForm(this),
iconTypeList,
commonIconList,
linearIconList,
fillIconList,
@@ -177,6 +177,7 @@ export default {
formVisible: false,
formImg: null,
file: null,
uuid: uuidv4(),
}
},
computed: {
@@ -200,6 +201,9 @@ export default {
const splitFileName = this.file.name.split('.')
return splitFileName.splice(0, splitFileName.length - 1).join('')
},
iconTypeList() {
return iconTypeList()
},
},
mounted() {
document.addEventListener('click', this.eventListener)
@@ -217,7 +221,7 @@ export default {
eventListener(e) {
if (this.visible) {
const dom = document.getElementById(`custom-icon-select-popover`)
const dom_icon = document.getElementById(`custom-icon-select-block`)
const dom_icon = document.getElementById(`custom-icon-select-block-${this.uuid}`)
e.stopPropagation()
e.preventDefault()
if (dom) {
@@ -249,12 +253,11 @@ export default {
color: '',
})
} else {
this.$emit('change', { name: icon.data.name, id: icon.id, url: icon.data.url })
this.$emit('change', { name: icon.data.name, id: icon.id, url: icon?.data?.url })
}
},
showSelect() {
this.visible = true
console.log(this.value)
if (!this.value.name) {
this.currentIconType = '3'
return
@@ -278,7 +281,7 @@ export default {
beforeUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
this.$message.error('图片大小不可超过2MB!')
this.$message.error(this.$t('customIconSelect.sizeLimit'))
return false
}
@@ -306,7 +309,7 @@ export default {
this.form.validateFields((err, values) => {
if (!err) {
addFileData('ops-custom-icon', { data: { name: values.name, url: res.file_name } }).then(() => {
this.$message.success('上传成功!')
this.$message.success(this.$t('uploadSuccess'))
this.handleCancel()
this.getFileData()
})
@@ -318,7 +321,7 @@ export default {
e.stopPropagation()
e.preventDefault()
deleteFileData('ops-custom-icon', icon.id).then(() => {
this.$message.success('删除成功!')
this.$message.success(this.$t('deleteSuccess'))
this.handleCancel()
this.getFileData()
})

View File

@@ -6,17 +6,17 @@
:flat="true"
:multiple="true"
:options="employeeTreeSelectOption"
placeholder="请输入搜索内容"
:placeholder="$t('placeholderSearch')"
v-model="treeValue"
:max-height="height - 50"
noChildrenText=""
noOptionsText=""
:clearable="false"
:always-open="true"
:default-expand-level="1"
:default-expand-level="showInternship ? 0 : 1"
:class="{ 'employee-transfer': true, 'employee-transfer-has-input': !!inputValue }"
@search-change="changeInputValue"
noResultsText="暂无数据"
:noResultsText="$t('noData')"
openDirection="below"
>
</treeselect>
@@ -85,6 +85,10 @@ export default {
type: Boolean,
default: false,
},
showInternship: {
type: Boolean,
default: false,
},
},
data() {
return {
@@ -99,13 +103,22 @@ export default {
},
computed: {
employeeTreeSelectOption() {
return formatOption(
const formatOptions = formatOption(
this.allTreeDepAndEmp,
2,
this.isDisabledAllCompany,
this.uniqueKey || 'department_id',
this.uniqueKey || 'employee_id'
)
if (this.showInternship) {
formatOptions.push(
...[
{ id: -2, label: '全职' },
{ id: -3, label: '实习生' },
]
)
}
return formatOptions
},
allTreeDepAndEmp() {
if (this.getDataBySelf) {
@@ -148,11 +161,15 @@ export default {
const department = []
const user = []
this.rightData.forEach((item) => {
const _split = item.split('-')
if (_split[0] === 'department') {
department.push(Number(_split[1]))
if (item === -2 || item === -3) {
department.push(item)
} else {
user.push(Number(_split[1]))
const _split = item.split('-')
if (_split[0] === 'department') {
department.push(Number(_split[1]))
} else {
user.push(Number(_split[1]))
}
}
})
const _idx = department.findIndex((item) => item === 0)
@@ -191,6 +208,12 @@ export default {
}
},
getLabel(id) {
if (id === -2) {
return '全职'
}
if (id === -3) {
return '实习生'
}
const _split = id.split('-')
const type = _split[0]
const _id = Number(_split[1])

View File

@@ -81,25 +81,23 @@ export default {
},
inject: ['reload'],
methods: {
// 取消订阅
cancelAttributes(e, menu) {
const that = this
e.preventDefault()
e.stopPropagation()
this.$confirm({
title: '警告',
content: `确认取消订阅 ${menu.meta.title}?`,
title: this.$t('alert'),
content: this.$t('cmdb.preference.confirmcancelSub2', { name: menu.meta.title }),
onOk() {
const citypeId = menu.meta.typeId
const unsubCIType = subscribeCIType(citypeId, '')
const unsubTree = subscribeTreeView(citypeId, '')
Promise.all([unsubCIType, unsubTree]).then(() => {
that.$message.success('取消订阅成功')
that.$message.success(that.$t('cmdb.preference.cancelSubSuccess'))
const lastTypeId = window.localStorage.getItem('ops_ci_typeid') || undefined
if (Number(citypeId) === Number(lastTypeId)) {
localStorage.setItem('ops_ci_typeid', '')
}
// 删除路由
const href = window.location.href
const hrefSplit = href.split('/')
if (Number(hrefSplit[hrefSplit.length - 1]) === Number(citypeId)) {
@@ -119,12 +117,10 @@ export default {
},
// select menu item
onOpenChange(openKeys) {
// 在水平模式下时执行,并且不再执行后续
if (this.mode === 'horizontal') {
this.openKeys = openKeys
return
}
// 非水平模式时
const latestOpenKey = openKeys.find(key => !this.openKeys.includes(key))
if (!this.rootSubmenuKeys.includes(latestOpenKey)) {
this.openKeys = openKeys
@@ -161,6 +157,12 @@ export default {
}
return null
},
renderI18n(title) {
if (Object.prototype.toString.call(this.$t(`${title}`)) === '[object Object]') {
return title
}
return this.$t(`${title}`)
},
renderMenuItem(menu) {
const isShowDot = menu.path.substr(0, 22) === '/cmdb/instances/types/'
const isShowGrant = menu.path.substr(0, 20) === '/cmdb/relationviews/'
@@ -170,9 +172,6 @@ export default {
const attrs = { href: menu.meta.targetHref || menu.path, target: menu.meta.target }
if (menu.children && menu.hideChildrenInMenu) {
// 把有子菜单的 并且 父菜单是要隐藏子菜单的
// 都给子菜单增加一个 hidden 属性
// 用来给刷新页面时, selectedKeys 做控制用
menu.children.forEach(item => {
item.meta = Object.assign(item.meta, { hidden: true })
})
@@ -183,7 +182,7 @@ export default {
<tag {...{ props, attrs }}>
{this.renderIcon({ icon: menu.meta.icon, customIcon: menu.meta.customIcon, name: menu.meta.name, typeId: menu.meta.typeId, routeName: menu.name, selectedIcon: menu.meta.selectedIcon, })}
<span>
<span class={menu.meta.title.length > 10 ? 'scroll' : ''}>{menu.meta.title}</span>
<span class={this.renderI18n(menu.meta.title).length > 10 ? 'scroll' : ''}>{this.renderI18n(menu.meta.title)}</span>
{isShowDot &&
<a-popover
overlayClassName="custom-menu-extra-submenu"
@@ -193,8 +192,8 @@ export default {
getPopupContainer={(trigger) => trigger}
content={() =>
<div>
<div onClick={e => this.handlePerm(e, menu, 'CIType')} class="custom-menu-extra-submenu-item"><a-icon type="user-add" />授权</div>
<div onClick={e => this.cancelAttributes(e, menu)} class="custom-menu-extra-submenu-item"><a-icon type="star" />取消订阅</div>
<div onClick={e => this.handlePerm(e, menu, 'CIType')} class="custom-menu-extra-submenu-item"><a-icon type="user-add" />{ this.renderI18n('grant') }</div>
<div onClick={e => this.cancelAttributes(e, menu)} class="custom-menu-extra-submenu-item"><a-icon type="star" />{ this.renderI18n('cmdb.preference.cancelSub') }</div>
</div>}
>
<a-icon type="menu" ref="extraEllipsis" class="custom-menu-extra-ellipsis"></a-icon>
@@ -217,7 +216,7 @@ export default {
<SubMenu {...{ key: menu.path }}>
<span slot="title">
{this.renderIcon({ icon: menu.meta.icon, selectedIcon: menu.meta.selectedIcon, routeName: menu.name })}
<span>{menu.meta.title}</span>
<span>{this.renderI18n(menu.meta.title)}</span>
</span>
{itemArr}
</SubMenu>
@@ -284,7 +283,7 @@ export default {
this.$refs.cmdbGrantRelationView.open({ name: menu.meta.name, cmdbGrantType: 'relation_view' })
}
} else {
this.$message.error('权限不足!')
this.$message.error(this.$t('noPermission'))
}
})
}

View File

@@ -3,9 +3,9 @@
<slot></slot>
<template #empty>
<slot name="empty">
<div>
<img :style="{ width: '100px' }" :src="require('@/assets/data_empty.png')" />
<div>暂无数据</div>
<div :style="{ paddingTop: '10px' }">
<img :style="{ width: '100px', height: '90px' }" :src="require('@/assets/data_empty.png')" />
<div>{{ $t('noData') }}</div>
</div>
</slot>
</template>

View File

@@ -0,0 +1,2 @@
import Pager from './index.vue'
export default Pager

View File

@@ -0,0 +1,137 @@
<template>
<div>
<a-row class="row" type="flex" justify="end">
<a-col>
<a-space align="end">
<a-button
class="left-button"
size="small"
:disabled="prevIsDisabled"
@click="prevPage"
><a-icon
type="left"
/></a-button>
<a-button class="page-button" size="small">{{ currentPage }}</a-button>
<a-button
class="right-button"
size="small"
:disabled="nextIsDisabled"
@click="nextPage"
><a-icon
type="right"
/></a-button>
<a-dropdown
class="dropdown"
size="small"
placement="topCenter"
:trigger="['click']"
:disabled="dropdownIsDisabled"
>
<a-menu slot="overlay">
<a-menu-item v-for="(size, index) in pageSizes" :key="index" @click="handleItemClick(size)">
{{ `${size}${$t('itemsPerPage')}` }}
</a-menu-item>
</a-menu>
<a-button size="small">{{ `${pageSize}${$t('itemsPerPage')}` }}<a-icon type="down" /> </a-button>
</a-dropdown>
</a-space>
</a-col>
</a-row>
</div>
</template>
<script>
export default {
name: 'Pager',
props: {
currentPage: {
type: Number,
required: true,
},
pageSize: {
type: Number,
required: true,
},
pageSizes: {
type: Array,
required: true,
},
total: {
type: Number,
required: true,
},
isLoading: {
type: Boolean,
required: false,
},
},
data() {
return {
dropdownIsDisabled: false,
prevIsDisabled: true,
}
},
computed: {
nextIsDisabled() {
return this.isLoading || this.total < this.pageSize
},
},
watch: {
isLoading: {
immediate: true,
handler: function(val) {
if (val) {
this.dropdownIsDisabled = true
this.prevIsDisabled = true
} else {
this.dropdownIsDisabled = false
if (this.currentPage === 1) {
this.prevIsDisabled = true
} else {
this.prevIsDisabled = false
}
}
},
},
currentPage: {
immediate: true,
handler: function(val) {
if (val === 1) {
this.prevIsDisabled = true
}
},
},
},
methods: {
handleItemClick(size) {
this.$emit('showSizeChange', size)
},
nextPage() {
const pageNum = this.currentPage + 1
this.$emit('change', pageNum)
},
prevPage() {
const pageNum = this.currentPage - 1
this.$emit('change', pageNum)
},
},
}
</script>
<style lang="less" scoped>
.row {
margin-top: 5px;
.left-button {
padding: 0;
width: 24px;
}
.right-button {
padding: 0;
width: 24px;
}
.page-button {
padding: 0;
width: 24px;
}
}
</style>

View File

@@ -0,0 +1,19 @@
/* eslint-disable no-useless-escape */
import i18n from '@/lang'
export const regList = () => {
return [
{ id: 'letter', label: i18n.t('regexSelect.letter'), value: '^[A-Za-z]+$', message: '请输入字母' },
{ id: 'number', label: i18n.t('regexSelect.number'), value: '^-?(?!0\\d+)\\d+(\\.\\d+)?$', message: '请输入数字' },
{ id: 'letterAndNumber', label: i18n.t('regexSelect.letterAndNumber'), value: '^[A-Za-z0-9.]+$', message: '请输入字母和数字' },
{ id: 'phone', label: i18n.t('regexSelect.phone'), value: '^1[3-9]\\d{9}$', message: '请输入正确手机号码' },
{ id: 'landline', label: i18n.t('regexSelect.landline'), value: '^(?:(?:\\d{3}-)?\\d{8}|^(?:\\d{4}-)?\\d{7,8})(?:-\\d+)?$', message: '请输入正确座机' },
{ id: 'zipCode', label: i18n.t('regexSelect.zipCode'), value: '^(0[1-7]|1[0-356]|2[0-7]|3[0-6]|4[0-7]|5[1-7]|6[1-7]|7[0-5]|8[013-6])\\d{4}$', message: '请输入正确邮政编码' },
{ id: 'IDCard', label: i18n.t('regexSelect.IDCard'), value: '(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)', message: '请输入正确身份证号' },
{ id: 'ip', label: i18n.t('regexSelect.ip'), value: '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', message: '请输入正确IP地址' },
{ id: 'email', label: i18n.t('regexSelect.email'), value: '^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\.\\w+([-.]\\w+)*$', message: '请输入正确邮箱' },
{ id: 'link', label: i18n.t('regexSelect.link'), value: '^(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?$', message: '请输入链接' },
{ id: 'monetaryAmount', label: i18n.t('regexSelect.monetaryAmount'), value: '^-?\\d+(,\\d{3})*(\.\\d{1,2})?$', message: '请输入货币金额' },
{ id: 'custom', label: i18n.t('regexSelect.custom'), value: '', message: '' }
]
}

View File

@@ -0,0 +1,2 @@
import RegexSelect from './regexSelect.vue'
export default RegexSelect

View File

@@ -0,0 +1,208 @@
<template>
<a-popover
trigger="click"
placement="bottom"
ref="regexSelect"
overlayClassName="regex-select-wrapper"
:overlayStyle="{ '--overlay-width': `${width}px` }"
@visibleChange="visibleChange"
>
<div class="regex-select" slot="content">
<div class="regex-select-left">
<div class="regex-select-left-header">{{ $t('regexSelect.limitedFormat') }}</div>
<div
@click="
() => {
current = reg
testInput = ''
showMessage = false
}
"
:class="{
'regex-select-left-reg': true,
'regex-select-left-reg-selected': current && current.label === reg.label,
}"
v-for="(reg, index) in regList"
:key="reg.label"
>
<a-divider :style="{ margin: '2px -12px', width: 'calc(100% + 24px)' }" v-if="index === regList.length - 1" />
{{ reg.label }}
</div>
</div>
<div class="regex-select-right">
<template v-if="current">
<div class="regex-select-right-header">{{ $t('regexSelect.regExp') }}</div>
<div
v-if="current.label !== $t('regexSelect.custom')"
:style="{ color: '#000', fontSize: '12px', margin: '12px 0' }"
>
{{ current.value }}
</div>
<a-input
:style="{ margin: '12px 0' }"
size="small"
v-else
v-model="current.value"
@change="
() => {
this.$emit('change', current)
}
"
/>
<template v-if="isShowErrorMsg">
<div class="regex-select-right-header">{{ $t('regexSelect.errMsg') }}</div>
<a-input :style="{ margin: '12px 0' }" size="small" v-model="current.message" />
</template>
<div class="regex-select-right-header">{{ $t('regexSelect.test') }}</div>
<a-input v-model="testInput" :style="{ margin: '12px 0 4px' }" size="small" @change="validate" />
<span :style="{ color: 'red', fontSize: '12px' }" v-if="showMessage">{{
locale === 'zh' ? current.message || '错误' : $t('regexSelect.error')
}}</span>
</template>
</div>
</div>
<a-input ref="regInput" :placeholder="$t('regexSelect.placeholder')" :value="current.label" @change="changeLabel">
</a-input>
</a-popover>
</template>
<script>
import { mapState } from 'vuex'
import { regList } from './constants'
export default {
name: 'RegexSelect',
model: {
prop: 'value',
event: 'change',
},
props: {
value: {
type: Object,
default: () => {},
},
isShowErrorMsg: {
type: Boolean,
default: true,
},
limitedFormat: {
type: Array,
default: () => [],
},
},
data() {
return {
showMessage: false,
width: 370,
testInput: '',
}
},
computed: {
...mapState(['locale']),
regList() {
if (this.limitedFormat.length) {
return regList().filter((item) => this.limitedFormat.includes(item.id))
}
return regList()
},
current: {
get() {
if (this.value?.value && !this.value?.label) {
const _find = this.regList.find((reg) => reg.value === this.value?.value)
return { ...this.value, label: _find?.label ?? this.$t('regexSelect.custom') }
}
return this.value ?? {}
},
set(val) {
this.showMessage = false
this.$emit('change', val)
return val
},
},
},
mounted() {
this.$nextTick(() => {
const regInput = this.$refs.regInput.$refs.input
this.width = regInput.offsetWidth || 370
})
},
methods: {
validate(e) {
const reg = RegExp(this.current.value, 'g')
this.showMessage = !reg.test(e.target.value)
},
changeLabel(e) {
this.current = {}
},
visibleChange(visible) {
if (visible) {
this.$nextTick(() => {
this.testInput = ''
this.showMessage = false
})
}
},
},
}
</script>
<style lang="less" scoped>
@import '~@/style/static.less';
.regex-select {
width: 100%;
height: 300px;
display: flex;
.regex-select-left {
width: 40%;
height: 100%;
border: 1px solid #cacdd9;
border-radius: 4px;
padding: 12px;
&-reg {
padding-left: 2px;
cursor: pointer;
&-selected,
&:hover {
color: #custom_colors[color_1];
}
}
}
&-right {
flex: 1;
height: 100%;
border: 1px solid #cacdd9;
border-radius: 4px;
margin-left: 8px;
padding: 12px;
}
&-left,
&-right {
&-header {
font-weight: 400;
font-size: 14px;
color: #000000;
border-left: 2px solid #custom_colors[color_1];
padding-left: 6px;
margin-left: -6px;
}
}
}
</style>
<style lang="less">
.regex-select-wrapper {
.ant-popover-arrow {
display: none;
}
.ant-popover-inner-content {
padding: 0;
min-width: 370px;
width: var(--overlay-width);
}
}
.regex-select-wrapper.ant-popover-placement-bottom .ant-popover-content {
margin-top: -8px;
}
.regex-select-wrapper.ant-popover-placement-top .ant-popover-content {
margin-bottom: -8px;
}
</style>

View File

@@ -3,12 +3,12 @@
<a-switch
class="role-transfer-switch"
v-model="isUserRole"
checked-children="用户"
un-checked-children="虚拟"
:checked-children="$t('user')"
:un-checked-children="$t('visual')"
@change="loadRoles"
/>
<div class="role-transfer-left">
<a-input placeholder="请输入搜索内容" v-model="searchValue" />
<a-input :placeholder="$t('placeholderSearch')" v-model="searchValue" />
<div v-for="item in filterAllRoles" :key="item.id" @click="handleSelectedLeft(item.id)">
<a-checkbox :checked="selectedLeft.includes(item.id)" />
<div :title="item.name" class="role-transfer-left-role">{{ item.name }}</div>

View File

@@ -119,7 +119,8 @@ export default {
border-radius: 4px;
color: @layout-header-font-color;
height: @layout-header-height;
line-height: @layout-header-height;
display: inline-flex;
align-items: center;
&:hover {
background: linear-gradient(0deg, rgba(0, 80, 201, 0.2) 0%, rgba(174, 207, 255, 0.06) 86.76%);
color: @layout-header-font-selected-color;

View File

@@ -10,9 +10,10 @@
>
<a-icon type="setting" />
</span>
<span class="locale" @click="changeLang">{{ locale === 'zh' ? 'English' : '中文' }}</span>
<a-popover
trigger="click"
:overlayStyle="{ width: '120px' }"
:overlayStyle="{ width: '150px' }"
placement="bottomRight"
overlayClassName="custom-user"
>
@@ -20,12 +21,12 @@
<router-link :to="{ name: 'setting_person' }" :style="{ color: '#000000a6' }">
<div class="custom-user-item">
<a-icon type="user" :style="{ marginRight: '10px' }" />
<span>个人中心</span>
<span>{{ $t('topMenu.personalCenter') }}</span>
</div>
</router-link>
<div @click="handleLogout" class="custom-user-item">
<a-icon type="logout" :style="{ marginRight: '10px' }" />
<span>退出登录</span>
<span>{{ $t('topMenu.logout') }}</span>
</div>
</template>
<span class="action ant-dropdown-link user-dropdown-menu">
@@ -44,8 +45,9 @@
</template>
<script>
import { mapState, mapActions, mapGetters, mapMutations } from 'vuex'
import DocumentLink from './DocumentLink.vue'
import { mapState, mapActions, mapGetters } from 'vuex'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
export default {
name: 'UserMenu',
@@ -53,20 +55,21 @@ export default {
DocumentLink,
},
computed: {
...mapState(['user']),
...mapState(['user', 'locale']),
hasBackendPermission() {
return this.user?.roles?.permissions.includes('acl_admin', 'backend_admin') || false
return this.user?.detailPermissions?.backend?.length
},
},
methods: {
...mapActions(['Logout']),
...mapGetters(['nickname', 'avatar']),
...mapMutations(['SET_LOCALE']),
handleLogout() {
const that = this
this.$confirm({
title: '提示',
content: '确认注销登录 ?',
title: this.$t('tip'),
content: this.$t('topMenu.confirmLogout'),
onOk() {
return that.Logout()
},
@@ -76,9 +79,22 @@ export default {
handleClick() {
this.$router.push('/setting')
},
changeLang() {
if (this.locale === 'zh') {
this.SET_LOCALE('en')
this.$i18n.locale = 'en'
} else {
this.SET_LOCALE('zh')
this.$i18n.locale = 'zh'
}
this.$nextTick(() => {
setDocumentTitle(`${this.$t(this.$route.meta.title)} - ${domTitle}`)
})
},
},
}
</script>
<style lang="less">
@import '~@/style/static.less';
.color {
@@ -98,4 +114,11 @@ export default {
color: #000000a6;
}
}
.locale {
cursor: pointer;
&:hover {
color: #custom_colors[color_1];
}
}
</style>

View File

@@ -14,7 +14,7 @@
*/
export default {
primaryColor: '#1890ff', // primary color of ant design
primaryColor: '#2f54eb', // primary color of ant design
navTheme: 'dark', // theme for nav menu
layout: 'sidemenu', // nav menu position: sidemenu or topmenu
contentWidth: 'Fixed', // layout of content: Fluid or Fixed, only works when layout is topmenu

View File

@@ -38,11 +38,18 @@ import CardTitle from '@/components/CardTitle'
import ElementUI from 'element-ui'
import Treeselect from '@riophae/vue-treeselect'
import OpsTable from '@/components/OpsTable'
import VueI18n from 'vue-i18n'
import i18n from '@/lang'
Vue.config.productionTip = false
Vue.prototype.$bus = EventBus
VXETable.setup({
i18n: (key, args) => i18n.t(key, args)
})
Vue.use(VXETable)
VXETable.use(VXETablePluginExportXLSX)
Vue.use(VueI18n)
Vue.config.productionTip = false
@@ -75,4 +82,3 @@ Vue.component('CustomRadio', CustomRadio)
Vue.component('CardTitle', CardTitle)
Vue.component('Treeselect', Treeselect)
Vue.component('OpsTable', OpsTable)

View File

@@ -7,6 +7,7 @@ import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from './store/global/mutation-types'
import i18n from '@/lang'
NProgress.configure({ showSpinner: false })
@@ -17,7 +18,7 @@ const whitePath = ['/user/login', '/user/logout', '/user/register', '/api/sso/lo
// 登录页面处理处理 是否使用单点登录
router.beforeEach(async (to, from, next) => {
NProgress.start() // start progress bar
to.meta && (!!to.meta.title && setDocumentTitle(`${to.meta.title} - ${domTitle}`))
to.meta && (!!to.meta.title && setDocumentTitle(`${i18n.t(to.meta.title)} - ${domTitle}`))
const authed = store.state.authed
const auth_type = localStorage.getItem('ops_auth_type')

171
cmdb-ui/src/lang/en.js Normal file
View File

@@ -0,0 +1,171 @@
import cmdb_en from '@/modules/cmdb/lang/en.js'
import cs_en from '../views/setting/lang/en.js'
import acl_en from '@/modules/acl/lang/en.js'
export default {
commonMenu: {
permission: 'Permission',
role: 'Roles',
resource: 'Resources',
resourceType: 'Resource Types',
trigger: 'Triggers',
},
screen: 'Big Screen',
dashboard: 'Dashboard',
admin: 'Admin',
user: 'User',
role: 'Role',
operation: 'Operation',
login: 'Login',
refresh: 'Refresh',
cancel: 'Cancel',
confirm: 'Confirm',
create: 'Create',
edit: 'Edit',
deleting: 'Deleting',
deletingTip: 'Deleting, total of {total}, {successNum} succeeded, {errorNum} failed',
grant: 'Grant',
login_at: 'Login At',
logout_at: 'Logout At',
createSuccess: 'Create Success',
editSuccess: 'edit Success',
warning: 'Warning',
export: 'Export',
placeholderSearch: 'Please Search',
success: 'Success',
fail: 'Fail',
browser: 'Browser',
status: 'Status',
type: 'Type',
description: 'Description',
new: 'New',
add: 'Add',
define: 'Define',
update: 'Update',
clear: 'Clear',
delete: 'Delete',
copy: 'Copy',
created_at: 'Created At',
updated_at: 'Updated At',
placeholder1: 'Please Input',
placeholder2: 'Please Select',
confirmDelete: 'Confirm delete?',
confirmDelete2: 'Confirm delete [{name}]?',
query: 'Query',
search: 'Search',
hide: 'Hide',
expand: 'Expand',
save: 'Save',
submit: 'Submit',
upload: 'Import',
download: 'Export',
name: 'Name',
alias: 'Alias',
desc: 'Description',
other: 'Other',
icon: 'Icon',
addSuccess: 'Added successfully',
uploadSuccess: 'Import successfully',
saveSuccess: 'Save successfully',
copySuccess: 'Copy successfully',
updateSuccess: 'Updated successfully',
deleteSuccess: 'Deleted successfully',
operateSuccess: 'The operation was successful',
noPermission: 'No Permission',
noData: 'No Data',
seconds: 'Seconds',
createdAt: 'Created At',
updatedAt: 'Updated At',
deletedAt: 'Deleted At',
required: 'required',
email: 'Email',
wechat: 'Wechat',
dingding: 'DingTalk',
feishu: 'Feishu',
bot: 'Robot',
checkAll: 'Select All',
loading: 'Loading...',
view: 'View',
reset: 'Reset',
yes: 'Yes',
no: 'No',
all: 'All',
selectRows: 'Selected: {rows} items',
itemsPerPage: '/page',
'星期一': 'Monday',
'星期二': 'Tuesday',
'星期三': 'Wednesday',
'星期四': 'Thursday',
'星期五': 'Friday',
'星期六': 'Saturday',
'星期日': 'Sunday',
hour: 'hour',
'items/page': '{items} items/page',
max: 'Max',
min: 'Min',
visual: 'Visual',
default: 'default',
tip: 'Tip',
pagination: {
total: '{range0}-{range1} of {total} items'
},
topMenu: {
personalCenter: 'My Profile',
logout: 'Logout',
confirmLogout: 'Are you sure to log out?'
},
cmdbFilterComp: {
conditionFilter: 'Conditional filtering',
and: 'and',
or: 'or',
is: 'equal',
'~is': 'not equal',
contain: 'contain',
'~contain': 'not contain',
start_with: 'start_with',
'~start_with': 'not start_with',
end_with: 'end_with',
'~end_with': 'not end_with',
'~value': 'null',
value: 'not null',
in: 'in',
'~in': 'not in',
range: 'range',
'~range': 'out of range',
compare: 'compare',
addHere: 'Add Here',
split: 'split by {separator}'
},
customIconSelect: {
outlined: 'Outlined',
filled: 'Filled',
multicolor: 'Multicolor',
custom: 'Custom',
preview: 'Preview',
sizeLimit: 'The image size cannot exceed 2MB!',
nodata: 'There are currently no custom icons available. Click here to upload'
},
regexSelect: {
limitedFormat: 'Limited Format',
regExp: 'RegExp',
errMsg: 'Error Message',
test: 'Test',
placeholder: 'Please Select RegExp',
error: 'Error',
letter: 'letter',
number: 'number',
letterAndNumber: 'letter&number',
phone: 'phone',
landline: 'landline',
zipCode: 'zip code',
IDCard: 'ID card',
ip: 'IP',
email: 'email',
link: 'link',
monetaryAmount: 'monetary amount',
custom: 'custom',
},
cmdb: cmdb_en,
cs: cs_en,
acl: acl_en,
}

18
cmdb-ui/src/lang/index.js Normal file
View File

@@ -0,0 +1,18 @@
import VueI18n from 'vue-i18n'
import zh from './zh'
import en from './en'
import Vue from 'vue'
import zhCN from 'vxe-table/lib/locale/lang/zh-CN'
import enUS from 'vxe-table/lib/locale/lang/en-US'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'zh', // 初始化中文
messages: {
'zh': { ...zh, ...zhCN },
'en': { ...en, ...enUS },
},
silentTranslationWarn: true
})
export default i18n

171
cmdb-ui/src/lang/zh.js Normal file
View File

@@ -0,0 +1,171 @@
import cmdb_zh from '@/modules/cmdb/lang/zh.js'
import cs_zh from '../views/setting/lang/zh.js'
import acl_zh from '@/modules/acl/lang/zh.js'
export default {
commonMenu: {
permission: '权限管理',
role: '角色管理',
resource: '资源管理',
resourceType: '资源类型',
trigger: '触发器',
},
screen: '大屏',
dashboard: '仪表盘',
admin: '管理员',
user: '用户',
role: '角色',
operation: '操作',
login: '登录',
refresh: '刷新',
cancel: '取消',
confirm: '确定',
create: '创建',
edit: '编辑',
deleting: '正在删除',
deletingTip: '正在删除,共{total}个,成功{successNum}个,失败{errorNum}个',
grant: '授权',
login_at: '登录时间',
logout_at: '登出时间',
createSuccess: '创建成功',
editSuccess: '修改成功',
warning: '警告',
export: '导出',
placeholderSearch: '请查找',
success: '成功',
fail: '失败',
browser: '浏览器',
status: '状态',
type: '类型',
description: '描述',
new: '新增',
add: '添加',
define: '定义',
update: '修改',
clear: '清空',
delete: '删除',
copy: '复制',
created_at: '创建日期',
updated_at: '更新日期',
placeholder1: '请输入',
placeholder2: '请选择',
confirmDelete: '确认删除?',
confirmDelete2: '确认删除【{name}】?',
query: '查询',
search: '搜索',
hide: '隐藏',
expand: '展开',
save: '保存',
submit: '提交',
upload: '导入',
download: '导出',
name: '名称',
alias: '别名',
desc: '描述',
other: '其他',
icon: '图标',
addSuccess: '新增成功',
uploadSuccess: '导入成功',
saveSuccess: '保存成功',
copySuccess: '复制成功',
updateSuccess: '更新成功',
deleteSuccess: '删除成功',
operateSuccess: '操作成功',
noPermission: '权限不足',
noData: '暂无数据',
seconds: '秒',
createdAt: '创建时间',
updatedAt: '更新时间',
deletedAt: '删除时间',
required: '必须',
email: '邮件',
wechat: '企业微信',
dingding: '钉钉',
feishu: '飞书',
bot: '机器人',
checkAll: '全选',
loading: '加载中...',
view: '查看',
reset: '重置',
yes: '是',
no: '否',
all: '全部',
selectRows: '选取:{rows} 项',
itemsPerPage: '/页',
'星期一': '星期一',
'星期二': '星期二',
'星期三': '星期三',
'星期四': '星期四',
'星期五': '星期五',
'星期六': '星期六',
'星期日': '星期日',
hour: '小时',
'items/page': '{items} 条/页',
max: '最大值',
min: '最小值',
visual: '虚拟',
default: '默认',
tip: '提示',
pagination: {
total: '当前展示 {range0}-{range1} 条数据, 共 {total} 条'
},
topMenu: {
personalCenter: '个人中心',
logout: '退出登录',
confirmLogout: '确认退出登录吗?'
},
cmdbFilterComp: {
conditionFilter: '条件过滤',
and: '与',
or: '或',
is: '等于',
'~is': '不等于',
contain: '包含',
'~contain': '不包含',
start_with: '以...开始',
'~start_with': '不以...开始',
end_with: '以...结束',
'~end_with': '不以...结束',
'~value': '为空',
value: '不为空',
in: 'in查询',
'~in': '非in查询',
range: '范围',
'~range': '范围外',
compare: '比较',
addHere: '在此处添加',
split: '以 {separator} 分隔'
},
customIconSelect: {
outlined: '线框',
filled: '实底',
multicolor: '多色',
custom: '自定义',
preview: '预览',
sizeLimit: '图片大小不可超过2MB',
nodata: '暂无自定义图标,点击此处上传'
},
regexSelect: {
limitedFormat: '限定格式',
regExp: '正则表达式',
errMsg: '错误时提示',
test: '测试',
placeholder: '请选择正则表达式',
error: '错误',
letter: '字母',
number: '数字',
letterAndNumber: '字母和数字',
phone: '手机号码',
landline: '座机',
zipCode: '邮政编码',
IDCard: '身份证号',
ip: 'IP地址',
email: '邮箱',
link: '链接',
monetaryAmount: '货币金额',
custom: '自定义',
},
cmdb: cmdb_zh,
cs: cs_zh,
acl: acl_zh,
}

View File

@@ -10,6 +10,7 @@ import './guard' // guard permission control
import './utils/filter' // global filter
import Setting from './config/setting'
import { Icon } from 'ant-design-vue'
import i18n from './lang'
import iconFont from '../public/iconfont/iconfont'
@@ -22,6 +23,7 @@ async function start() {
const _vue = new Vue({
router,
store,
i18n,
created: bootstrap,
render: h => h(App)
}).$mount('#app')

View File

@@ -0,0 +1,125 @@
const acl_en = {
date: 'Date',
operator: 'Operator',
resource: 'Resource',
resourceType: 'Resource Type',
addResourceType: 'Add Resource Type',
app: 'App',
operateTime: 'Operate Time',
permission: 'Permission',
permission_placeholder: 'please select permission',
permissionList: 'Permission List',
summaryPermissions: 'Summary of permissions',
source: 'Source',
username: 'Username',
username_placeholder: 'please input username',
userList: 'User List',
groupUser: 'Group User',
addUser: 'Add User',
subordinateUsers: 'Subordinate Users',
nickname: 'Nickname',
nickname_placeholder: 'please input nickname',
password: 'Password',
password_placeholder: 'please input password',
department: 'Department',
group: 'Group',
email: 'Email',
email_placeholder: 'please input email',
mobile: 'Mobile',
isBlock: 'Is Block',
block: 'Block',
joined_at: 'Joined At',
role: 'Role',
role_placeholder1: 'please input role',
role_placeholder2: 'please select role',
role_placeholder3: 'please select a role name, multiple choices are allowed',
allRole: 'All Roles',
visualRole: 'Virtual Role',
addVisualRole: 'Add Virtual Role',
inheritedFrom: 'Inherited from',
heir: 'Inherit Roles',
permissionChange: 'Permissions',
roleChange: 'Roles',
resourceChange: 'Resources',
resourceTypeChange: 'Resource Type',
trigger: 'Triggers',
triggerNameInput: 'Please enter trigger name',
triggerChange: 'Triggers',
roleManage: 'Roles',
userManage: 'Users',
appManage: 'Applications',
resourceManage: 'Resources',
history: 'Audits',
userSecret: 'Secrets',
none: 'none',
danger: 'Dangerous',
confirmDeleteApp: 'Are you sure you want to delete this app?',
revoke: 'Revoke',
convenient: 'Quick Grant',
group2: 'Group',
groupName: 'Group Name',
resourceName: 'Resource Name',
creator: 'Creator',
member: 'Members',
viewAuth: 'view Auth',
addTypeTips: 'There is no type information yet, please add the resource type first!',
addResource: 'Add Resource',
resourceList: 'Resource List',
confirmResetSecret: 'Are you sure you want to reset the user secrets?',
addTrigger: 'Add Trigger',
deleteTrigger: 'Delete Trigger',
applyTrigger: 'Apply Trigger',
cancelTrigger: 'Cancel Trigger',
enable: 'Enable',
disable: 'Disable',
viewMatchResult: 'View regular matching results',
confirmDeleteTrigger: 'Are you sure you want to delete this trigger?',
ruleApply: 'Apply',
triggerTip1: 'Are you sure you want to apply this trigger?',
triggerTip2: 'Cancel applying this trigger?',
appNameInput: 'Please enter an application name',
descInput: 'Please enter a description',
addApp: 'Add',
updateApp: 'Update',
cancel: 'Cancel',
typeName: 'Name',
typeNameInput: 'Please enter a type name',
resourceNameInput: 'Please enter resource name',
pressEnter: 'Press Enter to confirm filtering',
groupMember: 'Group Members:',
isGroup: 'Group?',
errorTips: 'Error message',
roleList: 'Role List',
virtual: 'Virtual',
resourceBatchTips: 'Please enter the resource name, separated by newlines',
memberManage: 'Members: ',
newResource: 'New Resource: ',
deleteResource: 'Delete Resource: ',
deleteResourceType: 'Delete Resource Type: ',
noChange: 'No change',
batchOperate: 'Batch Operations',
batchGrant: 'Batch Grant',
batchRevoke: 'Batch Revoke',
editPerm: 'Add authorization: ',
permInput: 'Please enter permission name',
resourceTypeName: 'Resource Type Name',
selectedParents: 'Optionally inherit roles',
isAppAdmin: 'is app admin',
addRole: 'Add Role',
roleRelation: 'Role Relation',
roleRelationAdd: 'Add Role Relation',
roleRelationDelete: 'Delete Role Relation',
role2: 'Role',
admin: 'Admin',
involvingRP: 'Involving resources and permissions',
startAt: 'Start Time',
endAt: 'End Time',
triggerTips1: 'Priority regular pattern (secondary wildcard)',
pleaseSelectType: 'Please select resource type',
apply: 'Apply',
mobileTips: 'Please enter the correct phone number',
remove: 'Remove',
deleteUserConfirm: 'Are you sure you want to remove this user?',
copyResource: 'Copy resource name'
}
export default acl_en

View File

@@ -0,0 +1,125 @@
const acl_zh = {
date: '日期',
operator: '操作员',
resource: '资源',
resourceType: '资源类型',
addResourceType: '新增资源类型',
app: '应用',
operateTime: '操作时间',
permission: '权限',
permission_placeholder: '请选择权限',
permissionList: '权限列表',
summaryPermissions: '权限汇总',
source: '来源',
username: '用户名',
username_placeholder: '请输入用户名',
userList: '用户列表',
groupUser: '组用户',
addUser: '新增用户',
subordinateUsers: '下属用户',
nickname: '中文名',
nickname_placeholder: '请输入中文名',
password: '密码',
password_placeholder: '请输入密码',
department: '部门',
group: '小组',
email: '邮箱',
email_placeholder: '请输入邮箱',
mobile: '手机号',
isBlock: '是否锁定',
block: '锁定',
joined_at: '加入时间',
role: '角色名',
role_placeholder1: '请输入角色名',
role_placeholder2: '请选择角色名称',
role_placeholder3: '请选择角色名称,可多选',
allRole: '所有角色',
visualRole: '虚拟角色',
addVisualRole: '新增虚拟角色',
inheritedFrom: '继承自',
heir: '继承者',
permissionChange: '权限变更',
roleChange: '角色变更',
resourceChange: '资源变更',
resourceTypeChange: '资源类型变更',
trigger: '触发器',
triggerNameInput: '请输入触发器名',
triggerChange: '触发器变更',
roleManage: '角色管理',
userManage: '用户管理',
appManage: '应用管理',
resourceManage: '资源管理',
history: '操作审计',
userSecret: '用户密钥',
none: '无',
danger: '危险操作',
confirmDeleteApp: '确定要删除该App吗',
revoke: '权限回收',
convenient: '便捷授权',
group2: '组',
groupName: '资源组名',
resourceName: '资源名',
creator: '创建者',
member: '成员',
viewAuth: '查看授权',
addTypeTips: '暂无类型信息,请先添加资源类型!',
addResource: '新增资源',
resourceList: '资源列表',
confirmResetSecret: '确定重置用户密钥?',
addTrigger: '新增触发器',
deleteTrigger: '删除触发器',
applyTrigger: '应用触发器',
cancelTrigger: '取消触发器',
enable: '启用',
disable: '禁用',
viewMatchResult: '查看正则匹配结果',
confirmDeleteTrigger: '确认删除该触发器吗?',
ruleApply: '规则应用',
triggerTip1: '是否确定应用该触发器?',
triggerTip2: '是否取消应用该触发器?',
appNameInput: '请输入应用名称',
descInput: '请输入描述',
addApp: '创建应用',
updateApp: '更新应用',
cancel: '撤销',
typeName: '类型名',
typeNameInput: '请输入类型名',
resourceNameInput: '请输入资源名',
pressEnter: '按回车确认筛选',
groupMember: '组成员:',
isGroup: '是否组',
errorTips: '错误提示',
roleList: '角色列表',
virtual: '虚拟',
resourceBatchTips: '请输入资源名,换行分隔',
memberManage: '成员管理:',
newResource: '新建资源:',
deleteResource: '删除资源:',
deleteResourceType: '删除资源类型:',
noChange: '没有修改',
batchOperate: '批量操作',
batchGrant: '批量授权',
batchRevoke: '批量权限回收',
editPerm: '添加授权:',
permInput: '请输入权限名',
resourceTypeName: '资源类型名',
selectedParents: '可选择继承角色',
isAppAdmin: '是否应用管理员',
addRole: '新增角色',
roleRelation: '角色关系',
roleRelationAdd: '添加角色关系',
roleRelationDelete: '删除角色关系',
role2: '角色',
admin: '管理员',
involvingRP: '涉及资源及权限',
startAt: '开始时间',
endAt: '结束时间',
triggerTips1: '优先正则模式(次通配符)',
pleaseSelectType: '请选择资源类型',
apply: '应用',
mobileTips: '请输入正确的手机号码',
remove: '移除',
deleteUserConfirm: '是否确定要移除该用户',
copyResource: '复制资源名'
}
export default acl_zh

View File

@@ -12,35 +12,35 @@ const genAppRoute = ({ name }) => {
name: `${name}_roles_acl`,
hideChildrenInMenu: true,
component: () => import('../views/roles'),
meta: { title: '角色管理', icon: 'team', keepAlive: true }
meta: { title: 'acl.roleManage', icon: 'team', keepAlive: true }
},
{
path: `/acl/${name}/resources`,
name: `${name}_resources_acl`,
hideChildrenInMenu: true,
component: () => import('../views/resources'),
meta: { title: '资源管理', icon: 'credit-card', keepAlive: false }
meta: { title: 'acl.resourceManage', icon: 'credit-card', keepAlive: false }
},
{
path: `/acl/${name}/resource_types`,
name: `${name}_resource_types_acl`,
hideChildrenInMenu: true,
component: () => import('../views/resource_types'),
meta: { title: '资源类型', icon: 'file-text', keepAlive: true }
meta: { title: 'acl.resourceType', icon: 'file-text', keepAlive: true }
},
{
path: `/acl/${name}/trigger`,
name: `${name}_trigger_acl`,
hideChildrenInMenu: true,
component: () => import('../views/trigger'),
meta: { title: '触发器', icon: 'clock-circle', keepAlive: true }
meta: { title: 'acl.trigger', icon: 'clock-circle', keepAlive: true }
},
{
path: `/acl/${name}/history`,
name: `${name}_history_acl`,
hideChildrenInMenu: true,
component: () => import('../views/history'),
meta: { title: '操作审计', icon: 'search', keepAlive: false }
meta: { title: 'acl.history', icon: 'search', keepAlive: false }
}
]
}
@@ -59,32 +59,31 @@ const genAclRoutes = async () => {
path: `/acl/secret_key`,
name: 'acl_secret_key',
component: () => import('../views/secretKey'),
meta: { title: '用户密钥', icon: 'key' }
meta: { title: 'acl.userSecret', icon: 'key' }
},
{
path: `/acl/operate_history`,
name: 'acl_operate_history',
component: () => import('../views/operation_history/index.vue'),
// meta: { title: '操作审计', icon: 'search', permission: ['acl_admin'] },
meta: { title: '操作审计', icon: 'search' }
meta: { title: 'acl.history', icon: 'search', permission: ['acl_admin'] }
},
{
path: `/acl/user`,
name: 'acl_user',
component: () => import('../views/users'),
meta: { title: '用户管理', icon: 'user', permission: ['acl_admin'] }
meta: { title: 'acl.userManage', icon: 'user', permission: ['acl_admin'] }
},
{
path: `/acl/roles`,
name: `acl_roles`,
component: () => import('../views/roles'),
meta: { title: '角色管理', icon: 'team', keepAlive: true, permission: ['acl_admin'] }
meta: { title: 'acl.roleManage', icon: 'team', keepAlive: true, permission: ['acl_admin'] }
},
{
path: `/acl/apps`,
name: 'acl_apps',
component: () => import('../views/apps'),
meta: { title: '应用管理', icon: 'appstore', permission: ['acl_admin'] }
meta: { title: 'acl.appManage', icon: 'appstore', permission: ['acl_admin'] }
}
]
}

View File

@@ -11,7 +11,7 @@
:xs="24">
<a-card>
<a-card-meta :title="app.name">
<div slot="description" :title="app.description || ''">{{ app.description || '' }}</div>
<div slot="description" :title="app.description || ''">{{ app.description || $t('none') }}</div>
<a-avatar style="background-color: #5dc2f1" slot="avatar">{{ app.name[0].toUpperCase() }}</a-avatar>
</a-card-meta>
<template slot="actions">
@@ -65,11 +65,11 @@ export default {
handleDeleteApp(app) {
const that = this
this.$confirm({
title: '危险操作',
content: '确定要删除该App吗?',
title: that.$t('danger'),
content: that.$t('confirmDeleteApp'),
onOk() {
deleteApp(app.id).then((res) => {
that.$message.success(`删除成功${app.name}`)
that.$message.success(that.$t('deleteSuccess'))
that.loadApps()
})
},

View File

@@ -1,7 +1,7 @@
<template>
<div class="acl-history">
<a-tabs default-active-key="1">
<a-tab-pane key="1" tab="权限变更">
<a-tab-pane key="1" :tab="$t('acl.permissionChange')">
<permisson-history-table
v-if="isloaded"
:allResourceTypes="allResourceTypes"
@@ -17,7 +17,7 @@
@resourceClear="resourceClear"
></permisson-history-table>
</a-tab-pane>
<a-tab-pane key="2" tab="角色变更">
<a-tab-pane key="2" :tab="$t('acl.roleChange')">
<role-history-table
v-if="isloaded"
:allUsers="allUsers"
@@ -26,7 +26,7 @@
:allUsersMap="allUsersMap"
></role-history-table>
</a-tab-pane>
<a-tab-pane key="3" tab="资源变更">
<a-tab-pane key="3" :tab="$t('acl.resourceChange')">
<resource-history-table
v-if="isloaded"
:allResources="allResources"
@@ -41,7 +41,7 @@
@resourceClear="resourceClear"
></resource-history-table>
</a-tab-pane>
<a-tab-pane key="4" tab="资源类型变更">
<a-tab-pane key="4" :tab="$t('acl.resourceTypeChange')">
<resource-type-history-table
v-if="isloaded"
:allResourceTypes="allResourceTypes"
@@ -52,7 +52,7 @@
:allResourceTypesMap="allResourceTypesMap"
></resource-type-history-table>
</a-tab-pane>
<a-tab-pane key="5" tab="触发器变更">
<a-tab-pane key="5" :tab="$t('acl.triggerChange')">
<trigger-history-table
v-if="isloaded"
:allTriggers="allTriggers"

View File

@@ -1,11 +1,12 @@
<template>
<CustomDrawer @close="handleClose" width="500" :title="title" :visible="visible" :closable="false">
<a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="应用名称">
<a-input v-decorator="['name', { rules: [{ required: true, message: '请输入应用名称' }] }]"> </a-input>
<a-form-item :label="$t('acl.app')">
<a-input v-decorator="['name', { rules: [{ required: true, message: $t('acl.appNameInput') }] }]"> </a-input>
</a-form-item>
<a-form-item label="描述">
<a-input v-decorator="['description', { rules: [{ required: true, message: '请输入描述' }] }]"> </a-input>
<a-form-item :label="$t('desc')">
<a-input v-decorator="['description', { rules: [{ required: true, message: $t('acl.descInput') }] }]">
</a-input>
</a-form-item>
<a-form-item label="AppId">
<a-input v-decorator="['app_id', { rules: [{ required: false }] }]" :disabled="mode === 'update'"> </a-input>
@@ -19,8 +20,8 @@
</a-form-item>
</a-form>
<div class="custom-drawer-bottom-action">
<a-button @click="handleClose">取消</a-button>
<a-button @click="handleSubmit" type="primary">提交</a-button>
<a-button @click="handleClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">{{ $t('submit') }}</a-button>
</div>
</CustomDrawer>
</template>
@@ -32,10 +33,14 @@ export default {
data() {
return {
visible: false,
title: '创建应用',
mode: 'create',
}
},
computed: {
title() {
return this.$t('acl.addApp')
},
},
beforeCreate() {
this.form = this.$form.createForm(this)
},
@@ -43,7 +48,7 @@ export default {
handleEdit(ele) {
this.visible = true
if (ele) {
this.title = '修改应用'
this.title = this.$t('updateApp')
this.mode = 'update'
console.log(ele)
const { name, description } = ele
@@ -55,7 +60,7 @@ export default {
})
} else {
this.mode = 'create'
this.title = '创建应用'
this.title = this.$t('acl.addApp')
}
},
handleClose() {
@@ -69,11 +74,11 @@ export default {
}
if (values.id) {
await updateApp(values.id, values).then((res) => {
this.$message.success('修改成功!')
this.$message.success(this.$t('updateSuccess'))
})
} else {
await addApp(values).then((res) => {
this.$message.success('创建成功!')
this.$message.success(this.$t('addSuccess'))
})
}
this.handleClose()

View File

@@ -1,116 +0,0 @@
<template>
<div>
<a-row class="row" type="flex" justify="end">
<a-col>
<a-space align="end">
<a-button class="left-button" size="small" :disabled="prevIsDisabled" @click="prevPage"><a-icon type="left" /></a-button>
<a-button class="page-button" size="small">{{ currentPage }}</a-button>
<a-button class="right-button" size="small" :disabled="nextIsDisabled" @click="nextPage"><a-icon type="right" /></a-button>
<a-dropdown class="dropdown" size="small" placement="topCenter" :trigger="['click']" :disabled="dropdownIsDisabled">
<a-menu slot="overlay">
<a-menu-item v-for="(size,index) in pageSizes" :key="index" @click="handleItemClick(size)">
{{ size }}/
</a-menu-item>
</a-menu>
<a-button size="small"> {{ pageSize }}/ <a-icon type="down" /> </a-button>
</a-dropdown>
</a-space>
</a-col>
</a-row>
</div>
</template>
<script>
export default {
props: {
currentPage: {
type: Number,
required: true
},
pageSize: {
type: Number,
required: true
},
pageSizes: {
type: Array,
required: true
},
total: {
type: Number,
required: true
},
isLoading: {
type: Boolean,
required: false
}
},
data() {
return {
dropdownIsDisabled: false,
prevIsDisabled: true,
}
},
computed: {
nextIsDisabled() {
return this.isLoading || this.total < this.pageSize
}
},
watch: {
isLoading: {
immediate: true,
handler: function (val) {
if (val === true) {
this.dropdownIsDisabled = true
this.prevIsDisabled = true
} else {
this.dropdownIsDisabled = false
if (this.currentPage === 1) {
this.prevIsDisabled = true
} else {
this.prevIsDisabled = false
}
}
}
},
currentPage: {
immediate: true,
handler: function (val) {
if (val === 1) {
this.prevIsDisabled = true
}
}
}
},
methods: {
handleItemClick(size) {
this.$emit('showSizeChange', size)
},
nextPage() {
const pageNum = this.currentPage + 1
this.$emit('change', pageNum)
},
prevPage() {
const pageNum = this.currentPage - 1
this.$emit('change', pageNum)
}
}
}
</script>
<style lang="less" scoped>
.row{
margin-top: 5px;
.left-button{
padding: 0;
width: 24px;
}
.right-button{
padding: 0;
width: 24px;
}
.page-button{
padding: 0;
width: 24px;
}
}
</style>

View File

@@ -1,6 +1,6 @@
<template>
<CustomDrawer
:title="`权限汇总: ${user.nickname}`"
:title="`${$t('acl.summaryPermissions')}: ${user.nickname}`"
:visible="visible"
placement="left"
width="100%"
@@ -24,7 +24,7 @@
<vxe-table :max-height="`${windowHeight - 230}px`" :data="resources" ref="rTable">
<vxe-column
field="name"
title="资源名"
:title="$t('acl.resourceName')"
width="30%"
:filters="[{ data: '' }]"
:filter-method="filterNameMethod"
@@ -39,62 +39,17 @@
v-model="option.data"
@input="$panel.changeOption($event, !!option.data, option)"
@keyup.enter="$panel.confirmFilter()"
placeholder="按回车确认筛选"
:placeholder="$t('acl.pressEnter')"
/>
</template>
</template>
</vxe-column>
<vxe-column field="permissions" title="权限列表" width="70%">
<vxe-column field="permissions" :title="$t('acl.permissionList')" width="70%">
<template #default="{row}">
<a-tag color="cyan" v-for="(r, index) in row.permissions" :key="index">{{ r }}</a-tag>
</template>
</vxe-column>
</vxe-table>
<!-- <a-table
:columns="tableColumns"
:dataSource="resources"
:rowKey="record=>record.id"
:pagination="{ showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条记录` }"
showPagination="auto"
ref="rTable"
size="middle">
<div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" class="custom-filter-dropdown">
<a-input
v-ant-ref="c => searchInput = c"
:placeholder="` ${column.title}`"
:value="selectedKeys[0]"
@change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
@pressEnter="() => handleSearch(selectedKeys, confirm, column)"
style="width: 188px; margin-bottom: 8px; display: block;"
/>
<a-button
type="primary"
@click="() => handleSearch(selectedKeys, confirm, column)"
icon="search"
size="small"
style="width: 90px; margin-right: 8px"
>搜索</a-button>
<a-button
@click="() => handleReset(clearFilters, column)"
size="small"
style="width: 90px"
>重置</a-button>
</div>
<a-icon slot="filterIcon" slot-scope="filtered" type="search" :style="{ color: filtered ? '#108ee9' : undefined }" />
<template slot="nameSearchRender" slot-scope="text">
<span v-if="columnSearchText.name">
<template v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${columnSearchText.name})|(?=${columnSearchText.name})`, 'i'))">
<mark v-if="fragment.toLowerCase() === columnSearchText.name.toLowerCase()" :key="i" class="highlight">{{ fragment }}</mark>
<template v-else>{{ fragment }}</template>
</template>
</span>
<template v-else>{{ text }}</template>
</template>
<template slot="permissions" slot-scope="record">
<a-tag color="cyan" v-for="(r, index) in record" :key="index">{{ r }}</a-tag>
</template>
</a-table> -->
</a-spin>
</a-tab-pane>
</a-tabs>
@@ -122,33 +77,6 @@ export default {
resourceTypes: [],
resourceTypePerms: [],
resources: [],
// tableColumns: [
// {
// title: '资源名',
// dataIndex: 'name',
// sorter: false,
// width: 150,
// // scopedSlots: {
// // customRender: 'nameSearchRender',
// // filterDropdown: 'filterDropdown',
// // filterIcon: 'filterIcon'
// // },
// // onFilter: (value, record) => record.name && record.name.toLowerCase().includes(value.toLowerCase()),
// // onFilterDropdownVisibleChange: (visible) => {
// // if (visible) {
// // setTimeout(() => {
// // this.searchInput.focus()
// // }, 0)
// // }
// // }
// },
// {
// title: '权限列表',
// dataIndex: 'permissions',
// width: 300,
// scopedSlots: { customRender: 'permissions' },
// },
// ],
columnSearchText: {
name: '',
},
@@ -156,14 +84,14 @@ export default {
},
computed: {
...mapState({
windowHeight: state => state.windowHeight,
windowHeight: (state) => state.windowHeight,
}),
displayApps() {
const roles = this.$store.state.user.roles.permissions
if (roles.includes('acl_admin')) {
return this.apps
}
return this.apps.filter(item => {
return this.apps.filter((item) => {
if (roles.includes(`${item.name}_admin`)) {
return true
}
@@ -192,7 +120,7 @@ export default {
},
async loadRoles(_appId) {
const res = await searchRole({ app_id: _appId, page_size: 9999, is_all: true })
this.roles = res.roles.filter(item => item.uid)
this.roles = res.roles.filter((item) => item.uid)
},
async handleSwitchApp(appId) {
this.currentAppId = appId
@@ -218,7 +146,7 @@ export default {
},
async loadResource() {
this.spinning = true
const fil = this.roles.filter(role => role.uid === this.user.uid)
const fil = this.roles.filter((role) => role.uid === this.user.uid)
if (!fil[0]) {
return
}

View File

@@ -1,29 +1,33 @@
<template>
<CustomDrawer
:closable="false"
:title="drawerTitle"
:title="$t('acl.addResourceType')"
:visible="drawerVisible"
@close="onClose"
placement="right"
width="30%"
>
<a-form :form="form" :layout="formLayout" @submit="handleSubmit">
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="类型名">
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" :label="$t('acl.typeName')">
<a-input
name="name"
placeholder=""
v-decorator="['name', { rules: [{ required: true, message: '请输入资源名' }] }]"
v-decorator="['name', { rules: [{ required: true, message: $t('acl.resourceNameInput') }] }]"
/>
</a-form-item>
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="描述">
<a-textarea placeholder="请输入描述信息..." name="description" :rows="4" />
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" :label="$t('desc')">
<a-textarea :placeholder="$t('acl.descInput')" name="description" :rows="4" />
</a-form-item>
<a-form-item :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol" label="权限">
<a-form-item
:label-col="formItemLayout.labelCol"
:wrapper-col="formItemLayout.wrapperCol"
:label="$t('acl.permission')"
>
<div :style="{ borderBottom: '1px solid #E9E9E9' }">
<a-checkbox :indeterminate="indeterminate" @change="onCheckAllChange" :checked="checkAll">
全选
{{ $t('checkAll') }}
</a-checkbox>
</div>
<br />
@@ -35,8 +39,8 @@
</a-form-item>
<div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button>
<a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div>
</a-form>
</CustomDrawer>
@@ -49,7 +53,6 @@ export default {
name: 'ResourceForm',
data() {
return {
drawerTitle: '新增资源类型',
drawerVisible: false,
formLayout: 'vertical',
perms: ['1'],
@@ -142,8 +145,8 @@ export default {
})
},
updateResourceType(id, data) {
updateResourceTypeById(id, data).then(res => {
this.$message.success(`更新成功`)
updateResourceTypeById(id, data).then((res) => {
this.$message.success(this.$t('updateSuccess'))
this.handleOk()
this.onClose()
})
@@ -151,18 +154,12 @@ export default {
},
createResourceType(data) {
addResourceType(data).then(res => {
this.$message.success(`添加成功`)
addResourceType(data).then((res) => {
this.$message.success(this.$t('addSuccess'))
this.handleOk()
this.onClose()
})
// .catch(err => this.requestFailed(err))
},
// requestFailed (err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// }
},
watch: {},
props: {

View File

@@ -21,22 +21,22 @@
:height="`${windowHeight - windowHeightMinus}px`"
:scroll-y="{ enabled: false }"
>
<vxe-column field="created_at" width="144px" title="操作时间">
<vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')">
<template #default="{ row }">
<span>{{ row.deleted_at || row.updated_at || row.created_at }}</span>
</template>
</vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作">
<vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }">
<a-tag :color="row.operate_type === 'grant' ? 'green' : 'red'">{{
operateTypeMap.get(row.operate_type)
}}</a-tag>
</template>
</vxe-column>
<vxe-column field="rid" title="用户"></vxe-column>
<vxe-column field="resource_type_id" title="资源类型"></vxe-column>
<vxe-column field="resources" title="资源">
<vxe-column field="rid" :title="$t('user')"></vxe-column>
<vxe-column field="resource_type_id" :title="$t('acl.resourceType')"></vxe-column>
<vxe-column field="resources" :title="$t('acl.resource')">
<template #default="{ row }">
<template v-if="row.resource_ids.length > 0">
<a-tooltip placement="top">
@@ -55,14 +55,14 @@
</template>
</template>
</vxe-column>
<vxe-column title="权限">
<vxe-column :title="$t('acl.permission')">
<template #default="{ row }">
<a-tag v-for="(perm, index) in row.permission_ids" :key="'perms_' + perm + index">
{{ perm }}
</a-tag>
</template>
</vxe-column>
<vxe-column field="source" width="100px" title="来源"></vxe-column>
<vxe-column field="source" width="100px" :title="$t('acl.source')"></vxe-column>
</vxe-table>
<pager
:current-page.sync="queryParams.page"
@@ -79,7 +79,7 @@
<script>
import _ from 'lodash'
import Pager from './pager.vue'
import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue'
import { searchPermissonHistory } from '@/modules/acl/api/history'
import debounce from 'lodash/debounce'
@@ -122,10 +122,6 @@ export default {
loading: true,
app_id: this.$route.name.split('_')[0],
tableData: [],
operateTypeMap: new Map([
['grant', '授权'],
['revoke', '撤销'],
]),
queryParams: {
page: 1,
page_size: 50,
@@ -135,45 +131,45 @@ export default {
},
permissionTableAttrList: [
{
alias: '日期',
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '用户',
alias: this.$t('user'),
is_choice: true,
name: 'rid',
value_type: '2',
choice_value: this.allRoles,
},
{
alias: '资源类型',
alias: this.$t('acl.resourceType'),
is_choice: true,
name: 'resource_type_id',
value_type: '2',
choice_value: this.allResourceTypes,
},
{
alias: '资源',
alias: this.$t('acl.resource'),
is_choice: true,
name: 'resource_id',
value_type: '2',
choice_value: this.allResources,
},
{
alias: '操作',
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [{ 授权: 'grant' }, { 撤销: 'revoke' }],
choice_value: [{ [this.$t('grant')]: 'grant' }, { [this.$t('acl.cancel')]: 'revoke' }],
},
],
}
@@ -198,6 +194,12 @@ export default {
},
},
computed: {
operateTypeMap() {
return new Map([
['grant', this.$t('grant')],
['revoke', this.$t('acl.cancel')],
])
},
windowHeight() {
return this.$store.state.windowHeight
},

View File

@@ -1,6 +1,6 @@
<template>
<CustomDrawer
title="便捷授权"
:title="$t('acl.convenient')"
width="500px"
:maskClosable="false"
:closable="true"
@@ -10,12 +10,12 @@
<a-form :form="form">
<a-form-item>
<div slot="label" style="display: inline-block">
<span>角色列表</span>
<span>{{ $t('acl.roleList') }}</span>
<a-divider type="vertical" />
<a-switch
style="display: inline-block"
checked-children="用户"
un-checked-children="虚拟"
:checked-children="$t('user')"
:un-checked-children="$t('acl.virtual')"
@change="handleRoleTypeChange"
v-model="roleType"
/>
@@ -23,37 +23,37 @@
<el-select
:style="{ width: '100%' }"
size="small"
v-decorator="['roleIdList', { rules: [{ required: true, message: '请选择角色名称' }] }]"
v-decorator="['roleIdList', { rules: [{ required: true, message: $t('acl.role_placeholder2') }] }]"
multiple
filterable
placeholder="请选择角色名称,可多选!"
:placeholder="$t('acl.role_placeholder3')"
>
<el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select>
</a-form-item>
<a-form-item label="权限列表">
<a-form-item :label="$t('acl.permissionList')">
<el-select
:style="{ width: '100%' }"
size="small"
name="permName"
v-decorator="['permName', { rules: [{ required: true, message: '请选择权限' }] }]"
v-decorator="['permName', { rules: [{ required: true, message: this.$t('acl.permission_placeholder') }] }]"
multiple
placeholder="请选择权限,可多选!"
:placeholder="this.$t('acl.permission_placeholder')"
>
<el-option v-for="perm in allPerms" :key="perm.name" :value="perm.name" :label="perm.name"></el-option>
</el-select>
</a-form-item>
<a-form-item label="资源名">
<a-form-item :label="$t('acl.resourceName')">
<a-textarea
v-decorator="['resource_names', { rules: [{ required: true, message: '请输入资源名,换行分隔' }] }]"
v-decorator="['resource_names', { rules: [{ required: true, message: $t('acl.resourceBatchTips') }] }]"
:autoSize="{ minRows: 4 }"
placeholder="请输入资源名,换行分隔"
:placeholder="$t('acl.resourceBatchTips')"
/>
</a-form-item>
<div class="custom-drawer-bottom-action">
<a-button @click="handleRevoke" type="danger" ghost>权限回收</a-button>
<a-button @click="handleSubmit" type="primary">授权</a-button>
<a-button @click="handleRevoke" type="danger" ghost>{{ $t('acl.revoke') }}</a-button>
<a-button @click="handleSubmit" type="primary">{{ $t('grant') }}</a-button>
</div>
</a-form>
</CustomDrawer>
@@ -98,12 +98,12 @@ export default {
this.loadRoles(Number(target))
},
loadRoles(isUserRole) {
searchRole({ page_size: 9999, app_id: this.$route.name.split('_')[0], user_role: isUserRole }).then(res => {
searchRole({ page_size: 9999, app_id: this.$route.name.split('_')[0], user_role: isUserRole }).then((res) => {
this.allRoles = res.roles
})
},
loadPerm(resourceTypeId) {
getResourceTypePerms(resourceTypeId).then(res => {
getResourceTypePerms(resourceTypeId).then((res) => {
this.allPerms = res
})
},
@@ -111,13 +111,13 @@ export default {
this.form.validateFields((err, values) => {
if (!err) {
console.log(values)
values.roleIdList.forEach(roleId => {
values.roleIdList.forEach((roleId) => {
setBatchRoleResourceByResourceName(roleId, {
resource_names: values.resource_names.split('\n'),
perms: values.permName,
resource_type_id: this.resource_type_id,
}).then(res => {
this.$message.success('授权成功')
}).then((res) => {
this.$message.success(this.$t('operateSuccess'))
this.form.resetFields()
})
})
@@ -128,13 +128,13 @@ export default {
this.form.validateFields((err, values) => {
if (!err) {
console.log(values)
values.roleIdList.forEach(roleId => {
values.roleIdList.forEach((roleId) => {
setBatchRoleResourceRevokeByResourceName(roleId, {
resource_names: values.resource_names.split('\n'),
perms: values.permName,
resource_type_id: this.resource_type_id,
}).then(res => {
this.$message.success('权限回收成功')
}).then((res) => {
this.$message.success(this.$t('operateSuccess'))
this.form.resetFields()
})
})

View File

@@ -8,27 +8,27 @@
width="30%"
>
<a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="资源名">
<a-form-item :label="$t('acl.resourceName')">
<a-input
name="name"
placeholder=""
v-decorator="['name', { rules: [{ required: true, message: '请输入资源名' }] }]"
v-decorator="['name', { rules: [{ required: true, message: $t('acl.resourceNameInput') }] }]"
/>
</a-form-item>
<a-form-item label="资源类型">
<a-form-item :label="$t('acl.resourceType')">
<a-select v-model="selectedTypeId">
<a-select-option v-for="type in allTypes" :key="type.id">{{ type.name }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="是否组">
<a-form-item :label="$t('acl.isGroup')">
<a-radio-group v-model="isGroup">
<a-radio :value="true">
{{ $t('yes') }}
</a-radio>
<a-radio :value="false">
{{ $t('no') }}
</a-radio>
</a-radio-group>
</a-form-item>
@@ -36,8 +36,8 @@
<a-input name="id" type="hidden" v-decorator="['id', { rules: [] }]" />
</a-form-item>
<div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button>
<a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div>
</a-form>
</CustomDrawer>
@@ -52,7 +52,6 @@ export default {
name: 'ResourceForm',
data() {
return {
drawerTitle: '新增资源',
drawerVisible: false,
allTypes: [],
isGroup: false,
@@ -68,7 +67,11 @@ export default {
this.getAllResourceTypes()
},
computed: {},
computed: {
drawerTitle() {
return this.$t('acl.addResource')
},
},
mounted() {},
methods: {
getAllResourceTypes() {
@@ -95,7 +98,7 @@ export default {
values.type_id = this.selectedTypeId
values.app_id = this.$route.name.split('_')[0]
if (values.id) {
this.$message.error('错误提示')
this.$message.error(this.$t('acl.errorTips'))
} else {
this.createResource(values)
}
@@ -105,23 +108,17 @@ export default {
createResource(data) {
if (!this.isGroup) {
addResource(data).then((res) => {
this.$message.success(`添加成功`)
this.$message.success(this.$t('addSuccess'))
this.onClose()
})
// .catch(err => this.requestFailed(err))
} else {
addResourceGroup(data).then((res) => {
this.$message.success(`添加成功`)
this.$message.success(this.$t('addSuccess'))
this.onClose()
})
// .catch(err => this.requestFailed(err))
}
},
// requestFailed(err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
},
watch: {
'$route.name': function(newValue, oldValue) {

View File

@@ -1,5 +1,5 @@
<template>
<a-modal v-model="visible" :title="`组成员:${editRecord.name}`" :width="800" :footer="null">
<a-modal v-model="visible" :title="`${$t('acl.groupMember')}${editRecord.name}`" :width="800" :footer="null">
<div :style="{ maxHeight: '500px', overflow: 'auto' }">
<a-tag :style="{ marginBottom: '5px' }" v-for="mem in members" :key="mem.name">
{{ mem.name }}

View File

@@ -1,5 +1,5 @@
<template>
<a-modal v-model="visible" :title="`成员管理:${editRecord.name}`" @ok="handleSubmit" :width="690">
<a-modal v-model="visible" :title="`${$t('acl.memberManage')}${editRecord.name}`" @ok="handleSubmit" :width="690">
<!-- <CustomTransfer
ref="customTransfer"
:show-search="true"
@@ -26,7 +26,7 @@
@selectChange="selectChange"
:selectedKeys="selectedKeys"
>
<span slot="notFoundContent">暂无数据</span>
<span slot="notFoundContent">{{ $t('noData') }}</span>
<template slot="children" slot-scope="{ props: { direction, filteredItems } }">
<div class="ant-transfer-list-content" v-if="direction === 'right'">
<div
@@ -104,7 +104,7 @@ export default {
})
updateResourceGroup(this.editRecord['id'], { items: items.join(',') }).then(() => {
this.visible = false
this.$message.success('更新成功!')
this.$message.success(this.$t('updateSuccess'))
})
// .catch(err => this.$httpError(err))
},

View File

@@ -4,7 +4,7 @@
ref="child"
:attrList="resourceTableAttrList"
:hasSwitch="true"
switchValue=""
:switchValue="$t('acl.group2')"
@onSwitchChange="onSwitchChange"
@search="handleSearch"
@searchFormReset="searchFormReset"
@@ -22,30 +22,30 @@
resizable
:height="`${windowHeight - 310}px`"
>
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作">
<vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }">
<a-tag :color="handleTagColor(row.operate_type)">
{{ operateTypeMap.get(row.operate_type) }}
</a-tag>
</template>
</vxe-column>
<vxe-column field="link_id" title="资源名">
<vxe-column field="link_id" :title="$t('acl.resourceName')">
<template #default="{ row }">
<span>
{{ row.current.name || row.origin.name }}
</span>
</template>
</vxe-column>
<vxe-column title="描述">
<vxe-column :title="$t('desc')">
<template #default="{ row }">
<p>
{{ row.description }}
</p>
</template>
</vxe-column>
<vxe-column field="source" width="100px" title="来源"></vxe-column>
<vxe-column field="source" width="100px" :title="$t('acl.source')"></vxe-column>
</vxe-table>
<pager
:current-page.sync="queryParams.page"
@@ -62,7 +62,7 @@
<script>
import _ from 'lodash'
import Pager from './pager.vue'
import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue'
import { searchResourceHistory } from '@/modules/acl/api/history'
export default {
@@ -99,40 +99,6 @@ export default {
checked: false,
tableData: [],
app_id: this.$route.name.split('_')[0],
resourceTableAttrList: [
{
alias: '日期',
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '操作',
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [{ 新建: 'create' }, { 修改: 'update' }, { 删除: 'delete' }],
},
{
alias: '资源名',
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResources,
},
],
operateTypeMap: new Map([
['create', '新建'],
['update', '修改'],
['delete', '删除'],
]),
colorMap: new Map([
['create', 'green'],
['update', 'orange'],
@@ -146,6 +112,39 @@ export default {
start: '',
end: '',
},
resourceTableAttrList: [
{
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [
{ [this.$t('create')]: 'create' },
{ [this.$t('update')]: 'update' },
{ [this.$t('delete')]: 'delete' },
],
},
{
alias: this.$t('acl.resourceName'),
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResources,
},
],
}
},
async created() {
@@ -170,6 +169,13 @@ export default {
windowHeight() {
return this.$store.state.windowHeight
},
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
])
},
tableDataLength() {
return this.tableData.length
},
@@ -280,7 +286,7 @@ export default {
switch (operate_type) {
// create
case 'create': {
item.description = `新建资源${item.current.name}`
item.description = `${this.$t('acl.newResource')}${item.current.name}`
break
}
case 'update': {
@@ -290,9 +296,9 @@ export default {
const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null) {
item.description += ` ${key} : 改为 ${newVal} `
item.description += ` ${key} : -> ${newVal} `
} else {
item.description += ` ${key} : ${oldVal} 改为 ${newVal} `
item.description += ` ${key} : ${oldVal} -> ${newVal} `
}
}
}
@@ -300,18 +306,18 @@ export default {
const currentResource_ids = item.currentResource_ids
if (!_.isEqual(originResource_ids, currentResource_ids)) {
if (originResource_ids.length === 0) {
const str = ` resource_ids : 新增 ${currentResource_ids} `
const str = ` resource_ids : ${this.$t('new')} ${currentResource_ids} `
item.description += str
} else {
const str = ` resource_ids : ${originResource_ids} 改为 ${currentResource_ids} `
const str = ` resource_ids : ${originResource_ids} -> ${currentResource_ids} `
item.description += str
}
}
if (!item.description) item.description = '没有修改'
if (!item.description) item.description = this.$t('acl.noChange')
break
}
case 'delete': {
item.description = `删除资源${item.origin.name}`
item.description = `${this.$t('acl.deleteResource')}${item.origin.name}`
break
}
}

View File

@@ -17,7 +17,7 @@
>
<vxe-column
field="name"
title="角色名"
:title="$t('acl.role')"
width="20%"
:filters="[{ data: '' }]"
:filter-method="filterNameMethod"
@@ -32,19 +32,19 @@
v-model="option.data"
@input="$panel.changeOption($event, !!option.data, option)"
@keyup.enter="$panel.confirmFilter()"
placeholder="按回车确认筛选"
:placeholder="$t('acl.pressEnter')"
/>
</template>
</template>
</vxe-column>
<vxe-column field="users" title="下属用户" width="35%">
<vxe-column field="users" :title="$t('acl.subordinateUsers')" width="35%">
<template #default="{row}">
<a-tag color="green" v-for="user in row.users" :key="user.nickname">
{{ user.nickname }}
</a-tag>
</template>
</vxe-column>
<vxe-column field="perms" title="权限列表" width="35%">
<vxe-column field="perms" :title="$t('acl.permissionList')" width="35%">
<template #default="{row}">
<a-tag
closable
@@ -57,43 +57,18 @@
</a-tag>
</template>
</vxe-column>
<vxe-column field="operate" title="批量操作">
<vxe-column field="operate" :title="$t('acl.batchOperate')">
<template #default="{row}">
<a-button size="small" type="danger" @click="handleClearAll(row)">
清空
{{ $t('clear') }}
</a-button>
</template>
</vxe-column>
<template slot="empty">
<img :src="require(`@/assets/data_empty.png`)" />
<p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">暂无数据</p>
<p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">{{ $t('noData') }}</p>
</template>
</vxe-table>
<!-- <a-table
:columns="columns"
:dataSource="resPerms"
:rowKey="record => record.name"
:pagination="{ showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条记录` }"
showPagination="auto"
ref="rTable"
size="middle"
>
<div slot="perms" slot-scope="text">
<a-tag closable color="cyan" v-for="perm in text" :key="perm.name" @close="deletePerm(perm.rid, perm.name)">
{{ perm.name }}
</a-tag>
</div>
<div slot="users" slot-scope="text">
<a-tag color="green" v-for="user in text" :key="user.nickname">
{{ user.nickname }}
</a-tag>
</div>
<div slot="operate" slot-scope="text">
<a-button size="small" type="danger" @click="handleClearAll(text)">
清空
</a-button>
</div>
</a-table> -->
</CustomDrawer>
</template>
<script>
@@ -112,40 +87,11 @@ export default {
data() {
return {
isGroup: false,
drawerTitle: '权限列表',
drawerVisible: false,
record: null,
allPerms: [],
resPerms: [],
roleID: null,
// columns: [
// {
// title: '角色名',
// dataIndex: 'name',
// sorter: false,
// width: 50,
// },
// {
// title: '下属用户',
// dataIndex: 'users',
// sorter: false,
// width: 150,
// scopedSlots: { customRender: 'users' },
// },
// {
// title: '权限列表',
// dataIndex: 'perms',
// sorter: false,
// width: 150,
// scopedSlots: { customRender: 'perms' },
// },
// {
// title: '批量操作',
// sorter: false,
// width: 50,
// scopedSlots: { customRender: 'operate' },
// },
// ],
childrenDrawer: false,
allRoles: [],
}
@@ -154,6 +100,9 @@ export default {
...mapState({
windowHeight: (state) => state.windowHeight,
}),
drawerTitle() {
return this.$t('acl.permissionList')
}
},
beforeCreate() {
this.form = this.$form.createForm(this)
@@ -175,7 +124,7 @@ export default {
perms: [],
app_id: this.$route.name.split('_')[0],
}).then((res) => {
this.$message.success('删除成功')
this.$message.success(this.$t('deleteSuccess'))
this.$nextTick(() => {
this.getResPerms(this.record.id)
})
@@ -185,7 +134,7 @@ export default {
perms: [],
app_id: this.$route.name.split('_')[0],
}).then((res) => {
this.$message.success('删除成功')
this.$message.success(this.$t('deleteSuccess'))
// for (let i = 0; i < this.resPerms.length; i++) {
// if (this.resPerms[i].name === text.name) {
// this.resPerms[i].perms = []
@@ -227,7 +176,7 @@ export default {
perms: [permName],
app_id: this.$route.name.split('_')[0],
}).then((res) => {
this.$message.success(`删除成功`)
this.$message.success(this.$t('deleteSuccess'))
})
// .catch(err => this.requestFailed(err))
} else {
@@ -235,18 +184,13 @@ export default {
perms: [permName],
app_id: this.$route.name.split('_')[0],
}).then((res) => {
this.$message.success(`删除成功`)
this.$message.success(this.$t('deleteSuccess'))
})
// .catch(err => this.requestFailed(err))
}
},
handleCancel(e) {
this.drawerVisible = false
},
// requestFailed(err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
filterNameMethod({ option, row }) {
return row.name.toLowerCase().includes(option.data.toLowerCase())
},

View File

@@ -3,42 +3,42 @@
<a-form :form="form">
<a-form-item>
<div slot="label" style="display: inline-block">
<span>角色列表</span>
<span>{{ $t('acl.roleList') }}</span>
<a-divider type="vertical" />
<a-switch
style="display: inline-block"
checked-children="用户"
un-checked-children="虚拟"
:checked-children="$t('user')"
:un-checked-children="$t('acl.virtual')"
@change="handleRoleTypeChange"
/>
</div>
<el-select
:style="{ width: '100%' }"
size="small"
v-decorator="['roleIdList', { rules: [{ required: true, message: '请选择角色名称' }] }]"
v-decorator="['roleIdList', { rules: [{ required: true, message: $t('acl.role_placeholder2') }] }]"
multiple
filterable
placeholder="请选择角色名称,可多选!"
:placeholder="$t('acl.role_placeholder3')"
>
<el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select>
</a-form-item>
<a-form-item label="权限列表">
<a-form-item :label="$t('acl.permissionList')">
<el-select
:style="{ width: '100%' }"
size="small"
name="permName"
v-decorator="['permName', { rules: [{ required: true, message: '请选择权限' }] }]"
v-decorator="['permName', { rules: [{ required: true, message: $t('acl.permission_placeholder') }] }]"
multiple
placeholder="请选择权限,可多选!"
:placeholder="$t('acl.permission_placeholder') "
>
<el-option v-for="perm in allPerms" :key="perm.name" :value="perm.name" :label="perm.name"></el-option>
</el-select>
</a-form-item>
<div class="custom-drawer-bottom-action">
<a-button @click="closeForm">取消</a-button>
<a-button @click="handleSubmit" type="primary" :loading="loading">确定</a-button>
<a-button @click="closeForm">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary" :loading="loading">{{ $t('confirm') }}</a-button>
</div>
</a-form>
</CustomDrawer>
@@ -117,16 +117,12 @@ export default {
this.type = type
if (Array.isArray(record)) {
this.loadPerm(record[0]['resource_type_id'])
this.title = `${type === 'grant' ? '批量授权' : '批量权限回收'}`
this.title = `${type === 'grant' ? this.$t('acl.batchGrant') : this.$t('acl.batchRevoke')}`
} else {
this.title = `添加授权${record.name}`
this.title = `${this.$t('acl.editPerm')}${record.name}`
this.loadPerm(record['resource_type_id'])
}
},
// requestFailed(err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
handleSubmit(e) {
e.preventDefault()
this.form.validateFields((err, values) => {
@@ -136,16 +132,10 @@ export default {
this.loading = true
if (!this.isGroup) {
if (Array.isArray(this.instance)) {
// const promises = this.instance.map(item => {
// return setRoleResourcePerm(roleId, item.id, params)
// })
// Promise.all(promises).then(() => {
// this.$message.success('添加授权成功')
// })
if (this.type === 'grant') {
setBatchRoleResourcePerm(roleId, { ...params, resource_ids: this.instance.map((a) => a.id) })
.then((res) => {
this.$message.success('添加授权成功')
this.$message.success(this.$t('operateSuccess'))
})
.finally(() => {
this.loading = false
@@ -153,7 +143,7 @@ export default {
} else {
setBatchRoleResourceRevoke(roleId, { ...params, resource_ids: this.instance.map((a) => a.id) })
.then((res) => {
this.$message.success('批量权限回收成功')
this.$message.success(this.$t('operateSuccess'))
})
.finally(() => {
this.loading = false
@@ -162,7 +152,7 @@ export default {
} else {
setRoleResourcePerm(roleId, this.instance.id, params)
.then((res) => {
this.$message.success('添加授权成功')
this.$message.success(this.$t('operateSuccess'))
})
.finally(() => {
this.loading = false
@@ -170,16 +160,10 @@ export default {
}
} else {
if (Array.isArray(this.instance)) {
// const promises = this.instance.map(item => {
// return setRoleResourceGroupPerm(roleId, item.id, params)
// })
// Promise.all(promises).then(() => {
// this.$message.success('添加授权成功')
// })
if (this.type === 'grant') {
setBatchRoleResourceGroupPerm(roleId, { ...params, group_ids: this.instance.map((a) => a.id) })
.then((res) => {
this.$message.success('添加授权成功')
this.$message.success(this.$t('operateSuccess'))
})
.finally(() => {
this.loading = false
@@ -190,7 +174,7 @@ export default {
group_ids: this.instance.map((a) => a.id),
})
.then((res) => {
this.$message.success('批量权限回收成功')
this.$message.success(this.$t('operateSuccess'))
})
.finally(() => {
this.loading = false
@@ -199,7 +183,7 @@ export default {
} else {
setRoleResourceGroupPerm(roleId, this.instance.id, params)
.then((res) => {
this.$message.success('添加授权成功')
this.$message.success(this.$t('operateSuccess'))
})
.finally(() => {
this.loading = false

View File

@@ -1,32 +1,32 @@
<template>
<CustomDrawer
:closable="false"
:title="drawerTitle"
:title="$t('acl.addResourceType')"
:visible="drawerVisible"
@close="onClose"
placement="right"
width="500px"
>
<a-form :form="form" @submit="handleSubmit" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
<a-form-item label="类型名">
<a-form-item :label="$t('acl.typeName')">
<a-input
name="name"
placeholder="类型名称"
v-decorator="['name', { rules: [{ required: true, message: '请输入类型名' }] }]"
:placeholder="$t('acl.typeName')"
v-decorator="['name', { rules: [{ required: true, message: $t('acl.typeNameInput') }] }]"
/>
</a-form-item>
<a-form-item label="描述">
<a-form-item :label="$t('desc')">
<a-textarea
placeholder="请输入描述信息..."
:placeholder="$t('acl.descInput')"
name="description"
:rows="4"
v-decorator="['description', { rules: [] }]"
/>
</a-form-item>
<a-form-item label="权限">
<a-select mode="tags" v-model="perms" style="width: 100%" placeholder="请输入权限名..."> </a-select>
<a-form-item :label="$t('acl.permission')">
<a-select mode="tags" v-model="perms" style="width: 100%" :placeholder="$t('acl.permInput')"> </a-select>
</a-form-item>
<a-form-item>
@@ -34,8 +34,8 @@
</a-form-item>
<div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button>
<a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div>
</a-form>
</CustomDrawer>
@@ -48,7 +48,6 @@ export default {
name: 'ResourceForm',
data() {
return {
drawerTitle: '新增资源类型',
drawerVisible: false,
perms: [],
}
@@ -104,7 +103,7 @@ export default {
},
updateResourceType(id, data) {
updateResourceTypeById(id, data).then((res) => {
this.$message.success(`更新成功`)
this.$message.success(this.$t('updateSuccess'))
this.handleOk()
this.onClose()
})
@@ -113,17 +112,11 @@ export default {
createResourceType(data) {
addResourceType(data).then((res) => {
this.$message.success(`添加成功`)
this.$message.success(this.$t('addSuccess'))
this.handleOk()
this.onClose()
})
// .catch(err => this.requestFailed(err))
},
// requestFailed (err) {
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// }
},
watch: {},
props: {

View File

@@ -16,30 +16,30 @@
:loading="loading"
:height="`${windowHeight - 310}px`"
>
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作">
<vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }">
<a-tag :color="handleTagColor(row.operate_type)">
{{ operateTypeMap.get(row.operate_type) }}
</a-tag>
</template>
</vxe-column>
<vxe-column field="link_id" title="资源类型名">
<vxe-column field="link_id" :title="$t('acl.resourceTypeName')">
<template #default="{ row }">
<span>
{{ row.current.name || row.origin.name }}
</span>
</template>
</vxe-column>
<vxe-column title="描述">
<vxe-column :title="$t('desc')">
<template #default="{ row }">
<p>
{{ row.changeDescription }}
</p>
</template>
</vxe-column>
<vxe-column field="source" width="100px" title="来源"></vxe-column>
<vxe-column field="source" width="100px" :title="$t('acl.source')"></vxe-column>
</vxe-table>
<pager
:current-page.sync="queryParams.page"
@@ -56,7 +56,7 @@
<script>
import _ from 'lodash'
import Pager from './pager.vue'
import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue'
import { searchResourceHistory } from '@/modules/acl/api/history'
export default {
@@ -93,40 +93,6 @@ export default {
checked: false,
tableData: [],
app_id: this.$route.name.split('_')[0],
resourceTableAttrList: [
{
alias: '日期',
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '操作',
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [{ 新建: 'create' }, { 修改: 'update' }, { 删除: 'delete' }],
},
{
alias: '资源类型',
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResourceTypes,
},
],
operateTypeMap: new Map([
['create', '新建'],
['update', '修改'],
['delete', '删除'],
]),
colorMap: new Map([
['create', 'green'],
['update', 'orange'],
@@ -155,12 +121,50 @@ export default {
},
},
computed: {
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
])
},
windowHeight() {
return this.$store.state.windowHeight
},
tableDataLength() {
return this.tableData.length
},
resourceTableAttrList() {
return [
{
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [{ [this.$t('create')]: 'create' }, { [this.$t('update')]: 'update' }, { [this.$t('delete')]: 'delete' }],
},
{
alias: this.$t('acl.resourceType'),
is_choice: true,
name: 'link_id',
value_type: '2',
choice_value: this.allResourceTypes,
},
]
},
},
methods: {
async getTable(queryParams) {
@@ -236,7 +240,9 @@ export default {
switch (operate_type) {
// create
case 'create': {
item.changeDescription = `新增资源类型${item.current.name}\n描述${item.current.description}\n权限${item.extra.permission_ids.current}`
item.changeDescription = `${this.$t('acl.addResourceType')}${item.current.name}\n${this.$t('desc')}${
item.current.description
}\n${this.$t('acl.permission')}: ${item.extra.permission_ids.current}`
break
}
case 'update': {
@@ -246,10 +252,10 @@ export default {
const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null || oldVal === '') {
const str = ` ${key} : 改为 ${newVal} \n`
const str = ` ${key} : -> ${newVal} \n`
item.changeDescription += str
} else {
const str = ` ${key} : ${oldVal} 改为 ${newVal} \n`
const str = ` ${key} : ${oldVal} -> ${newVal} \n`
item.changeDescription += str
}
}
@@ -257,13 +263,13 @@ export default {
const currentPerms = item.extra.permission_ids.current
const originPerms = item.extra.permission_ids.origin
if (!_.isEqual(currentPerms, originPerms)) {
item.changeDescription += ` permission_ids : ${originPerms} 改为 ${currentPerms} `
item.changeDescription += ` permission_ids : ${originPerms} -> ${currentPerms} `
}
if (!item.changeDescription) item.changeDescription = '没有修改'
if (!item.changeDescription) item.changeDescription = this.$t('acl.noChange')
break
}
case 'delete': {
item.changeDescription = `删除资源类型${item.origin.name}\n描述${item.origin.description}\n权限${item.extra.permission_ids.origin}`
item.changeDescription = `${this.$t('acl.deleteResourceType')}${item.origin.name}\n${this.$t('desc')}: ${item.origin.description}\n${this.$t('acl.permission')}: ${item.extra.permission_ids.origin}`
break
}
}

View File

@@ -2,17 +2,17 @@
<CustomDrawer
width="800px"
placement="left"
title="资源列表"
:title="$t('acl.resourceList')"
@close="handleCancel"
:visible="visible"
:hasFooter="false"
>
<a-form-item label="资源类型" :label-col="{ span: 2 }" :wrapper-col="{ span: 14 }">
<a-form-item :label="$t('acl.resourceType')" :label-col="{ span: 4 }" :wrapper-col="{ span: 14 }">
<a-select v-model="typeSelected" style="width:100%" @change="refresh">
<a-select-option v-for="type in resourceTypes" :value="type.id" :key="type.id">{{ type.name }}</a-select-option>
</a-select>
</a-form-item>
<vxe-table
<ops-table
size="mini"
stripe
class="ops-stripe-table"
@@ -22,7 +22,7 @@
>
<vxe-column
field="name"
title="资源名"
:title="$t('acl.resourceName')"
width="30%"
:filters="[{ data: '' }]"
:filter-method="filterNameMethod"
@@ -30,7 +30,7 @@
>
<template #header="{ column }">
<span>{{ column.title }}</span>
<a-tooltip title="复制资源名">
<a-tooltip :title="$t('acl.copyResource')">
<a-icon @click="copyResourceName" class="resource-user-form-copy" theme="filled" type="copy" />
</a-tooltip>
</template>
@@ -43,84 +43,17 @@
v-model="option.data"
@input="$panel.changeOption($event, !!option.data, option)"
@keyup.enter="$panel.confirmFilter()"
placeholder="按回车确认筛选"
:placeholder="$t('acl.pressEnter')"
/>
</template>
</template>
</vxe-column>
<vxe-column field="permissions" title="权限列表" width="70%">
<vxe-column field="permissions" :title="$t('acl.permissionList')" width="70%">
<template #default="{row}">
<a-tag color="cyan" v-for="(r, index) in row.permissions" :key="index">{{ r }}</a-tag>
</template>
</vxe-column>
<template slot="empty">
<img :src="require(`@/assets/data_empty.png`)" />
<p style="font-size: 14px; line-height: 17px; color: rgba(0, 0, 0, 0.6)">暂无数据</p>
</template>
</vxe-table>
<!-- <a-table
:columns="columns"
:dataSource="records"
:rowKey="record => record.id"
:pagination="false"
ref="rTable"
size="middle"
:scroll="{ y: 300 }"
> -->
<!-- <div slot="filterDropdown" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" class="custom-filter-dropdown">
<a-input
v-ant-ref="c => searchInput = c"
:placeholder="` ${column.title}`"
:value="selectedKeys[0]"
@change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
@pressEnter="() => handleSearch(selectedKeys, confirm, column)"
style="width: 188px; margin-bottom: 8px; display: block;"
/>
<a-button
type="primary"
@click="() => handleSearch(selectedKeys, confirm, column)"
icon="search"
size="small"
style="width: 90px; margin-right: 8px"
>搜索</a-button>
<a-button
@click="() => handleReset(clearFilters, column)"
size="small"
style="width: 90px"
>重置</a-button>
</div>
<a-icon slot="filterIcon" slot-scope="filtered" type="search" :style="{ color: filtered ? '#108ee9' : undefined }" />
<template slot="nameSearchRender" slot-scope="text">
<span v-if="columnSearchText.name">
<template v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${columnSearchText.name})|(?=${columnSearchText.name})`, 'i'))">
<mark v-if="fragment.toLowerCase() === columnSearchText.name.toLowerCase()" :key="i" class="highlight">{{ fragment }}</mark>
<template v-else>{{ fragment }}</template>
</template>
</span>
<template v-else>{{ text }}</template>
</template> -->
<!-- <template slot="permissions" slot-scope="record">
<a-tag color="cyan" v-for="(r, index) in record" :key="index">{{ r }}</a-tag>
</template>
</a-table> -->
<!-- <div
:style="{
position: 'absolute',
left: 0,
bottom: 0,
width: '100%',
borderTop: '1px solid #e9e9e9',
padding: '10px 16px',
background: '#fff',
textAlign: 'right',
}"
>
<a-button :style="{marginRight: '8px'}" @click="handleCancel">
取消
</a-button>
<a-button @click="handleOk" type="primary">确定</a-button>
</div> -->
</ops-table>
</CustomDrawer>
</template>
<script>
@@ -141,38 +74,11 @@ export default {
name: '',
},
filterName: '',
// columns: [
// {
// title: '资源名',
// field: 'name',
// sorter: false,
// width: '30%',
// // scopedSlots: {
// // customRender: 'nameSearchRender',
// // filterDropdown: 'filterDropdown',
// // filterIcon: 'filterIcon'
// // },
// // onFilter: (value, record) => record.name && record.name.toLowerCase().includes(value.toLowerCase()),
// // onFilterDropdownVisibleChange: (visible) => {
// // if (visible) {
// // setTimeout(() => {
// // this.searchInput.focus()
// // }, 0)
// // }
// // }
// },
// {
// title: '权限列表',
// field: 'permissions',
// width: '70%',
// slots: { default: 'permissions_default' },
// },
// ],
}
},
computed: {
...mapState({
windowHeight: state => state.windowHeight,
windowHeight: (state) => state.windowHeight,
}),
},
mounted() {
@@ -184,18 +90,10 @@ export default {
this.rid = record.id
this.refresh()
},
// handleSearch(selectedKeys, confirm, column) {
// confirm()
// this.columnSearchText[column.dataIndex] = selectedKeys[0]
// },
// handleReset(clearFilters, column) {
// clearFilters()
// this.columnSearchText[column.dataIndex] = ''
// },
loadResourceTypes() {
this.resourceTypes = []
const appId = this.$route.name.split('_')[0]
searchResourceType({ app_id: appId }).then(res => {
searchResourceType({ app_id: appId }).then((res) => {
this.resourceTypes = res.groups
if (res.groups && res.groups.length > 0) {
this.typeSelected = res.groups[0].id
@@ -204,7 +102,6 @@ export default {
this.typeSelected = null
}
})
// .catch(err => this.$httpError(err))
},
handleOk() {
this.visible = false
@@ -214,10 +111,9 @@ export default {
searchPermResourceByRoleId(this.rid, {
resource_type_id: this.typeSelected,
app_id: this.$route.name.split('_')[0],
}).then(res => {
}).then((res) => {
this.records = res.resources
})
// .catch(err=>this.$httpError(err))
}
},
handleCancel() {
@@ -233,12 +129,12 @@ export default {
},
copyResourceName() {
const val = this.records
.filter(item => item.name.toLowerCase().includes(this.filterName.toLowerCase()))
.map(item => item.name)
.filter((item) => item.name.toLowerCase().includes(this.filterName.toLowerCase()))
.map((item) => item.name)
.join('\n')
this.copy(val, () => {
this.$message.success('复制成功')
this.$message.success(this.$t('copySuccess'))
})
},
copy(value, cb) {

View File

@@ -8,40 +8,29 @@
width="500px"
>
<a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }" @submit="handleSubmit">
<a-form-item label="角色名">
<a-form-item :label="$t('acl.role')">
<a-input
name="name"
placeholder="角色名"
v-decorator="['name', { rules: [{ required: true, message: '请输入角色名' }] }]"
:placeholder="$t('acl.role_placeholder1')"
v-decorator="['name', { rules: [{ required: true, message: $t('acl.role_placeholder1') }] }]"
/>
</a-form-item>
<a-form-item v-if="$route.name.split('_')[0] !== 'acl'" label="密码">
<a-input name="password" placeholder="密码" v-decorator="['password', { rules: [{ required: false }] }]" />
<a-form-item v-if="$route.name.split('_')[0] !== 'acl'" :label="$t('acl.password')">
<a-input name="password" :placeholder="$t('acl.password')" v-decorator="['password', { rules: [{ required: false }] }]" />
</a-form-item>
<!-- <a-form-item label="继承自">
<a-select
showSearch
v-model="selectedParents"
:filterOption="false"
placeholder="可选择继承角色"
mode="multiple"
>
<a-select-option v-for="role in scrollData" :key="role.id">{{ role.name }}</a-select-option>
</a-select>
</a-form-item> -->
<a-form-item label="继承自">
<a-form-item :label="$t('acl.inheritedFrom')">
<el-select
:style="{ width: '100%' }"
size="small"
v-model="selectedParents"
multiple
filterable
placeholder="可选择继承角色"
:placeholder="$t('acl.selectedParents')"
>
<el-option v-for="role in allRoles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select>
</a-form-item>
<a-form-item label="是否应用管理员">
<a-form-item :label="$t('acl.isAppAdmin')">
<a-switch
@change="onChange"
name="is_app_admin"
@@ -53,8 +42,8 @@
</a-form-item>
<div class="custom-drawer-bottom-action">
<a-button @click="onClose">取消</a-button>
<a-button @click="handleSubmit" type="primary">确定</a-button>
<a-button @click="onClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">{{ $t('confirm') }}</a-button>
</div>
</a-form>
</CustomDrawer>
@@ -93,7 +82,7 @@ export default {
// return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
// },
handleCreate() {
this.drawerTitle = '新增角色'
this.drawerTitle = this.$t('acl.addRole')
this.drawerVisible = true
},
onClose() {
@@ -107,7 +96,7 @@ export default {
},
handleEdit(record) {
this.drawerTitle = `编辑${record.name}`
this.drawerTitle = `${this.$t('edit')}: ${record.name}`
this.drawerVisible = true
this.current_id = record.id
const _parents = this.id2parents[record.id]
@@ -142,7 +131,7 @@ export default {
updateRole(id, data) {
this.updateParents(id)
updateRoleById(id, { ...data, app_id: this.$route.name.split('_')[0] }).then((res) => {
this.$message.success(`更新成功`)
this.$message.success(this.$t('updateSuccess'))
this.handleOk()
this.onClose()
})
@@ -151,7 +140,7 @@ export default {
createRole(data) {
addRole({ ...data, app_id: this.$route.name.split('_')[0] }).then((res) => {
this.$message.success(`添加成功`)
this.$message.success(this.$t('addSuccess'))
this.updateParents(res.id)
this.handleOk()
this.onClose()
@@ -171,16 +160,9 @@ export default {
child_ids: [id],
app_id: this.$route.name.split('_')[0],
})
// addParentRole(id, item, { app_id: this.$route.name.split('_')[0] })
// .catch(err => this.requestFailed(err))
}
})
},
// requestFailed(err) {
// console.log(err)
// const msg = ((err.response || {}).data || {}).message || '请求出现错误,请稍后再试'
// this.$message.error(`${msg}`)
// },
},
watch: {},
props: {

View File

@@ -4,7 +4,7 @@
ref="child"
:attrList="roleTableAttrList"
:hasSwitch="true"
switchValue="角色关系"
:switchValue="$t('acl.roleRelation')"
@onSwitchChange="onSwitchChange"
@search="handleSearch"
@searchFormReset="searchFormReset"
@@ -19,16 +19,16 @@
resizable
:height="`${windowHeight - 310}px`"
>
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column>
<vxe-column field="operate_uid" title="操作员" width="130px"></vxe-column>
<vxe-column field="operate_type" title="操作" width="112px">
<vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" :title="$t('acl.operator')" width="130px"></vxe-column>
<vxe-column field="operate_type" :title="$t('operation')" width="112px">
<template #default="{ row }">
<template>
<a-tag :color="handleTagColor(row.operate_type)">{{ operateTypeMap.get(row.operate_type) }}</a-tag>
</template>
</template>
</vxe-column>
<vxe-column :title="checked ? '角色' : '角色'">
<vxe-column :title="checked ? $t('acl.role2') : $t('acl.role2')">
<template #default="{ row }">
<template v-if="!checked">
<a-tag color="blue">{{ row.current.name || row.origin.name }}</a-tag>
@@ -40,7 +40,7 @@
</template>
</template>
</vxe-column>
<vxe-column :title="checked ? '继承自' : '管理员'" :width="checked ? '350px' : '80px'">
<vxe-column :title="checked ? $t('acl.inheritedFrom') : $t('acl.admin')" :width="checked ? '350px' : '80px'">
<template #default="{ row }">
<template v-if="!checked">
<a-icon type="check" v-if="row.current.is_app_admin" />
@@ -52,14 +52,14 @@
</template>
</template>
</vxe-column>
<vxe-column title="描述" v-if="!checked">
<vxe-column :title="$t('desc')" v-if="!checked">
<template #default="{ row }">
<p>
{{ row.description }}
</p>
</template>
</vxe-column>
<vxe-column field="source" title="来源" width="100px"></vxe-column>
<vxe-column field="source" :title="$t('acl.source')" width="100px"></vxe-column>
</vxe-table>
<pager
:current-page.sync="queryParams.page"
@@ -76,7 +76,7 @@
<script>
import _ from 'lodash'
import Pager from './pager.vue'
import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue'
import { searchRoleHistory } from '@/modules/acl/api/history'
export default {
@@ -105,13 +105,6 @@ export default {
checked: false,
tableData: [],
app_id: this.$route.name.split('_')[0],
operateTypeMap: new Map([
['create', '新建'],
['delete', '删除'],
['update', '修改'],
['role_relation_add', '添加角色关系'],
['role_relation_delete', '删除角色关系'],
]),
colorMap: new Map([
['create', 'green'],
['delete', 'red'],
@@ -127,42 +120,53 @@ export default {
start: '',
end: '',
},
roleTableAttrList: [
}
},
computed: {
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
['role_relation_add', this.$t('acl.roleRelationAdd')],
['role_relation_delete', this.$t('acl.roleRelationDelete')],
])
},
windowHeight() {
return this.$store.state.windowHeight
},
tableDataLength() {
return this.tableData.length
},
roleTableAttrList() {
return [
{
alias: '日期',
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '操作',
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [
{ 新建: 'create' },
{ 修改: 'update' },
{ 删除: 'delete' },
{ 添加角色关系: 'role_relation_add' },
{ 删除角色关系: 'role_relation_delete' },
{ [this.$t('create')]: 'create' },
{ [this.$t('update')]: 'update' },
{ [this.$t('delete')]: 'delete' },
{ [this.$t('acl.roleRelationAdd')]: 'role_relation_add' },
{ [this.$t('acl.roleRelationDelete')]: 'role_relation_delete' },
],
},
],
}
},
computed: {
windowHeight() {
return this.$store.state.windowHeight
},
tableDataLength() {
return this.tableData.length
]
},
},
async created() {
@@ -273,7 +277,7 @@ export default {
switch (operate_type) {
// create
case 'create': {
item.description = `新建角色${item.current.name}`
item.description = `${this.$t('acl.addRole')}${item.current.name}`
break
}
case 'update': {
@@ -283,15 +287,15 @@ export default {
const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null) {
const str = ` ${key} : 改为 ${newVal} `
const str = ` ${key} : -> ${newVal} `
item.description += str
} else {
const str = ` ${key} : ${oldVal} 改为 ${newVal} `
item.description += str
const str = ` ${key} : ${oldVal} -> ${newVal} `
item.description += ` ${key} : ${oldVal} -> ${newVal} `
}
}
}
if (!item.description) item.description = '没有修改'
if (!item.description) item.description = this.$t('acl.noChange')
break
}
case 'delete': {
@@ -321,7 +325,7 @@ export default {
resourceMap.forEach((value, key) => {
permsArr.push(`${id2resources[key].name}${value}`)
})
item.description = `继承者${child_ids}\n继承自${parent_ids}\n涉及资源及权限\n${permsArr.join(`\n`)}`
item.description = `${this.$t('acl.heir')}${child_ids}\n${this.$t('acl.inheritedFrom')}${parent_ids}\n${this.$t('acl.involvingRP')}\n${permsArr.join(`\n`)}`
break
}
}

View File

@@ -19,7 +19,7 @@
@popupScroll="loadMoreData(attr.name, $event)"
@search="(value) => fetchData(value, attr.name)"
v-model="queryParams[attr.name]"
placeholder="请选择"
:placeholder="$t('placeholder2')"
v-if="attr.is_choice"
show-search
:filter-option="filterOption"
@@ -38,7 +38,6 @@
@change="onChange"
:style="{ width: '100%' }"
format="YYYY-MM-DD HH:mm:ss"
:placeholder="['开始时间', '结束时间']"
:show-time="{
hideDisabledOptions: true,
defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
@@ -67,7 +66,7 @@
@popupScroll="loadMoreData(item.name, $event)"
@search="(value) => fetchData(value, item.name)"
v-model="queryParams[item.name]"
placeholder="请选择"
:placeholder="$t('placeholder2')"
v-if="item.is_choice"
show-search
:filter-option="filterOption"
@@ -85,7 +84,7 @@
:style="{ width: '100%' }"
@change="onChange"
format="YYYY-MM-DD HH:mm"
:placeholder="['开始时间', '结束时间']"
:placeholder="[$t('acl.startAt'), $t('acl.endAt')]"
v-else-if="valueTypeMap[item.value_type] == 'date' || valueTypeMap[item.value_type] == 'datetime'"
:show-time="{
hideDisabledOptions: true,
@@ -107,13 +106,13 @@
v-model="checked"
/>
<a-button :style="{ marginLeft: '8px' }" type="primary" html-type="submit" @click="handleSearch">
查询
{{ $t('query') }}
</a-button>
<a-button :style="{ marginLeft: '8px' }" @click="handleReset">
重置
{{ $t('reset') }}
</a-button>
<a :style="{ marginLeft: '8px', fontSize: '12px' }" @click="toggle" v-if="attrList.length >= 5">
{{ expand ? '隐藏' : '展开' }} <a-icon :type="expand ? 'up' : 'down'" />
{{ expand ? $t('expand') : $t('expand') }} <a-icon :type="expand ? 'up' : 'down'" />
</a>
</a-col>
</a-row>

View File

@@ -2,30 +2,40 @@
<CustomDrawer
@close="handleClose"
width="500"
:title="`${triggerId ? '修改' : '新建'}触发器`"
:title="`${triggerId ? $t('update') : $t('create')}${$t('acl.trigger')}`"
:visible="visible"
:maskClosable="false"
>
<a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }">
<a-form-item label="触发器名">
<a-input size="large" v-decorator="['name', { rules: [{ required: true, message: '请输入触发器名' }] }]">
<a-form-item :label="$t('name')">
<a-input
size="large"
v-decorator="['name', { rules: [{ required: true, message: $t('acl.triggerNameInput') }] }]"
>
</a-input>
</a-form-item>
<a-form-item label="资源名">
<a-input size="large" v-decorator="['wildcard']" placeholder="优先正则模式(次通配符)"> </a-input>
<a-form-item :label="$t('acl.resourceName')">
<a-input size="large" v-decorator="['wildcard']" :placeholder="$t('acl.triggerTips1')"> </a-input>
</a-form-item>
<a-form-item label="创建人">
<el-select :style="{ width: '100%' }" filterable multiple v-decorator="['uid']">
<a-form-item :label="$t('acl.creator')">
<el-select
:style="{ width: '100%' }"
filterable
multiple
v-decorator="['uid']"
:placeholder="$t('placeholder2')"
>
<template v-for="role in roles">
<el-option v-if="role.uid" :key="role.id" :value="role.uid" :label="role.name">{{ role.name }}</el-option>
</template>
</el-select>
</a-form-item>
<a-form-item label="资源类型">
<a-form-item :label="$t('acl.resourceType')">
<el-select
:style="{ width: '100%' }"
@change="handleRTChange"
v-decorator="['resource_type_id', { rules: [{ required: true, message: '请选择资源类型' }] }]"
:placeholder="$t('placeholder2')"
v-decorator="['resource_type_id', { rules: [{ required: true, message: $t('acl.pleaseSelectType') }] }]"
>
<el-option
v-for="resourceType in resourceTypeList"
@@ -34,25 +44,27 @@
:label="resourceType.name"
></el-option>
</el-select>
<a-tooltip title="查看正则匹配结果">
<a-tooltip :title="$t('acl.viewMatchResult')">
<a class="trigger-form-pattern" @click="handlePattern"><a-icon type="eye"/></a>
</a-tooltip>
</a-form-item>
<a-form-item label="角色">
<a-form-item :label="$t('acl.role2')">
<el-select
:style="{ width: '100%' }"
filterable
multiple
v-decorator="['roles', { rules: [{ required: true, message: '请选择角色' }] }]"
:placeholder="$t('placeholder2')"
v-decorator="['roles', { rules: [{ required: true, message: $t('acl.role_placeholder2') }] }]"
>
<el-option v-for="role in roles" :key="role.id" :value="role.id" :label="role.name"></el-option>
</el-select>
</a-form-item>
<a-form-item label="权限">
<a-form-item :label="$t('acl.permission')">
<el-select
:placeholder="$t('placeholder2')"
:style="{ width: '100%' }"
multiple
v-decorator="['permissions', { rules: [{ required: true, message: '请选择权限' }] }]"
v-decorator="['permissions', { rules: [{ required: true, message: $t('acl.permission_placeholder') }] }]"
>
<el-option
v-for="perm in selectResourceTypePerms"
@@ -62,13 +74,13 @@
></el-option>
</el-select>
</a-form-item>
<a-form-item label="启用/禁用">
<a-form-item :label="`${$t('acl.enable')} / ${$t('acl.disable')}`">
<a-switch v-decorator="['enabled', { rules: [], valuePropName: 'checked', initialValue: true }]" />
</a-form-item>
</a-form>
<div class="custom-drawer-bottom-action">
<a-button @click="handleClose">取消</a-button>
<a-button @click="handleSubmit" type="primary">提交</a-button>
<a-button @click="handleClose">{{ $t('cancel') }}</a-button>
<a-button @click="handleSubmit" type="primary">{{ $t('submit') }}</a-button>
</div>
<TriggerPattern ref="triggerPattern" :roles="roles" />
</CustomDrawer>
@@ -159,13 +171,13 @@ export default {
if (this.triggerId) {
updateTrigger(this.triggerId, { ...values, app_id: this.app_id }).then((res) => {
this.visible = false
this.$message.success('修改成功!')
this.$message.success(this.$t('updateSuccess'))
this.$emit('refresh')
})
} else {
addTrigger({ ...values, app_id: this.app_id }).then((res) => {
this.visible = false
this.$message.success('创建成功!')
this.$message.success(this.$t('addSuccess'))
this.$emit('refresh')
})
}

View File

@@ -16,23 +16,23 @@
resizable
:height="`${windowHeight - 310}px`"
>
<vxe-column field="created_at" width="144px" title="操作时间"></vxe-column>
<vxe-column field="operate_uid" width="130px" title="操作员"></vxe-column>
<vxe-column field="operate_type" width="80px" title="操作">
<vxe-column field="created_at" width="144px" :title="$t('acl.operateTime')"></vxe-column>
<vxe-column field="operate_uid" width="130px" :title="$t('acl.operator')"></vxe-column>
<vxe-column field="operate_type" width="100px" :title="$t('operation')">
<template #default="{ row }">
<a-tag :color="handleTagColor(row.operate_type)">
{{ operateTypeMap.get(row.operate_type) }}
</a-tag>
</template>
</vxe-column>
<vxe-column field="trigger_id" width="250px" title="触发器">
<vxe-column field="trigger_id" width="250px" :title="$t('acl.trigger')">
<template #default="{ row }">
<span>
{{ row.current.name || row.origin.name }}
</span>
</template>
</vxe-column>
<vxe-column title="描述">
<vxe-column :title="$t('desc')">
<template #default="{ row }">
<p>
{{ row.changeDescription }}
@@ -55,7 +55,7 @@
<script>
import _ from 'lodash'
import Pager from './pager.vue'
import Pager from '@/components/Pager'
import SearchForm from './searchForm.vue'
import { searchTriggerHistory } from '@/modules/acl/api/history'
export default {
@@ -95,13 +95,6 @@ export default {
app_id: this.$route.name.split('_')[0],
loading: true,
tableData: [],
operateTypeMap: new Map([
['create', '新建'],
['update', '修改'],
['delete', '删除'],
['trigger_apply', '应用'],
['trigger_cancel', '取消'],
]),
colorMap: new Map([
['create', 'green'],
['delete', 'red'],
@@ -109,41 +102,6 @@ export default {
['trigger_apply', 'green'],
['trigger_cancel', 'red'],
]),
triggerTableAttrList: [
{
alias: '日期',
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: '操作员',
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: '操作',
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [
{ 新建: 'create' },
{ 修改: 'update' },
{ 删除: 'delete' },
{ 应用: 'trigger_apply' },
{ 取消: 'trigger_cancel' },
],
},
{
alias: '触发器',
is_choice: true,
name: 'trigger_id',
value_type: '2',
choice_value: this.allTriggers,
},
],
queryParams: {
page: 1,
page_size: 50,
@@ -164,12 +122,58 @@ export default {
},
},
computed: {
operateTypeMap() {
return new Map([
['create', this.$t('create')],
['update', this.$t('update')],
['delete', this.$t('delete')],
['trigger_apply', this.$t('acl.apply')],
['trigger_cancel', this.$t('cancel')],
])
},
windowHeight() {
return this.$store.state.windowHeight
},
tableDataLength() {
return this.tableData.length
},
triggerTableAttrList() {
return [
{
alias: this.$t('acl.date'),
is_choice: false,
name: 'datetime',
value_type: '3',
},
{
alias: this.$t('acl.operator'),
is_choice: true,
name: 'operate_uid',
value_type: '2',
choice_value: this.allUsers,
},
{
alias: this.$t('operation'),
is_choice: true,
name: 'operate_type',
value_type: '2',
choice_value: [
{ [this.$t('create')]: 'create' },
{ [this.$t('update')]: 'update' },
{ [this.$t('delete')]: 'delete' },
{ [this.$t('acl.apply')]: 'trigger_apply' },
{ [this.$t('cancel')]: 'trigger_cancel' },
],
},
{
alias: this.$t('acl.trigger'),
is_choice: true,
name: 'trigger_id',
value_type: '2',
choice_value: this.allTriggers,
},
]
},
},
methods: {
async getTable(queryParams) {
@@ -220,9 +224,9 @@ export default {
const str = item.current.roles
const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `新增触发器${item.current.name}\n资源类型${this.allResourceTypesMap.get(
item.changeDescription = `${this.$t('acl.addTrigger')}: ${item.current.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.current.resource_type_id
)}资源名${item.current.wildcard}角色[${newStr}]\n权限${item.current.permissions}\n状态${
)}this.$t('acl.resourceName')${item.current.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.current.permissions}\n${this.$t('status')}: ${
item.current.enabled
}`
break
@@ -234,24 +238,24 @@ export default {
const oldVal = item.origin[key]
if (!_.isEqual(newVal, oldVal) && key !== 'updated_at' && key !== 'deleted_at' && key !== 'created_at') {
if (oldVal === null) {
const str = ` ${key} : 改为 ${newVal} `
const str = ` ${key} : -> ${newVal} `
item.changeDescription += str
} else {
const str = ` ${key} : ${oldVal} 改为 ${newVal} `
item.changeDescription += str
const str = ` ${key} : ${oldVal} -> ${newVal} `
item.changeDescription += ` ${key} : ${oldVal} -> ${newVal} `
}
}
}
if (!item.changeDescription) item.changeDescription = '没有修改'
if (!item.changeDescription) item.changeDescription = this.$t('acl.noChange')
break
}
case 'delete': {
const str = item.origin.roles
const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `删除触发器${item.origin.name}\n资源类型${this.allResourceTypesMap.get(
item.changeDescription = `${this.$t('acl.deleteTrigger')}: ${item.origin.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.origin.resource_type_id
)}资源名${item.origin.wildcard}角色[${newStr}]\n权限${item.origin.permissions}\n状态${
)}this.$t('acl.resourceName')${item.origin.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.origin.permissions}\n${this.$t('status')}: ${
item.origin.enabled
}`
break
@@ -260,9 +264,9 @@ export default {
const str = item.current.roles
const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `应用触发器${item.current.name}\n资源类型${this.allResourceTypesMap.get(
item.changeDescription = `${this.$t('acl.applyTrigger')}: ${item.current.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.current.resource_type_id
)}资源名${item.current.wildcard}角色[${newStr}]\n权限${item.current.permissions}\n状态${
)}this.$t('acl.resourceName')${item.current.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.current.permissions}\n${this.$t('status')}: ${
item.current.enabled
}`
break
@@ -271,9 +275,9 @@ export default {
const str = item.current.roles
const newArr = str.slice(1, str.length - 1).split(', ')
const newStr = newArr.map((i) => this.allRolesMap.get(Number(i))).join('')
item.changeDescription = `取消触发器${item.current.name}\n资源类型${this.allResourceTypesMap.get(
item.changeDescription = `${this.$t('acl.cancelTrigger')}: ${item.current.name}\n${this.$t('acl.resourceType')}: ${this.allResourceTypesMap.get(
item.current.resource_type_id
)}资源名${item.current.wildcard}角色[${newStr}]\n权限${item.current.permissions}\n状态${
)}this.$t('acl.resourceName')${item.current.wildcard}${this.$t('acl.role2')}: [${newStr}]\n${this.$t('acl.permission')}: ${item.current.permissions}\n${this.$t('status')}: ${
item.current.enabled
}`
break

Some files were not shown because too many files have changed in this diff Show More