Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mysql账号管理优化 #1436

Merged
merged 1 commit into from
Apr 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions sql/instance_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,13 @@ def users(request):
user['saved'] = True
cnf_users[f"`{user['user']}`@`{user['host']}`"] = user
# 获取所有用户
sql_get_user = "select concat('`', user, '`', '@', '`', host,'`') as query,user,host from mysql.user;"
query_engine = get_engine(instance=instance)
server_version = query_engine.server_version
# MySQL 5.7.6版本起支持ACCOUNT LOCK
if server_version >= (5, 7, 6):
sql_get_user = "select concat('`', user, '`', '@', '`', host,'`') as query,user,host,account_locked from mysql.user;"
else:
sql_get_user = "select concat('`', user, '`', '@', '`', host,'`') as query,user,host from mysql.user;"
query_result = query_engine.query('mysql', sql_get_user)
if not query_result.error:
db_users = query_result.rows
Expand All @@ -47,7 +52,8 @@ def users(request):
'user': db_user[1],
'host': db_user[2],
'privileges': user_priv,
'saved': False
'saved': False,
'is_locked': db_user[3] if server_version >= (5, 7, 6) else None
}
# 合并数据
if user_host in cnf_users.keys():
Expand Down Expand Up @@ -107,7 +113,7 @@ def create(request):
for host in hosts:
create_user_cmd += f"create user '{user}'@'{host}' identified by '{password1}';"
accounts.append(InstanceAccount(instance=instance, user=user, host=host, password=password1, remark=remark))
exec_result = engine.execute(db_name='information_schema', sql=create_user_cmd)
exec_result = engine.execute(db_name='mysql', sql=create_user_cmd)
if exec_result.error:
return JsonResponse({'status': 1, 'msg': exec_result.error})

Expand Down Expand Up @@ -223,7 +229,7 @@ def grant(request):
return JsonResponse({'status': 1, 'msg': '你所在组未关联该实例', 'data': []})

engine = get_engine(instance=instance)
exec_result = engine.execute(db_name='information_schema', sql=grant_sql)
exec_result = engine.execute(db_name='mysql', sql=grant_sql)
if exec_result.error:
return JsonResponse({'status': 1, 'msg': exec_result.error})
return JsonResponse({'status': 0, 'msg': '', 'data': grant_sql})
Expand Down Expand Up @@ -261,7 +267,7 @@ def reset_pwd(request):
return JsonResponse({'status': 1, 'msg': f'{msg}', 'data': []})

engine = get_engine(instance=instance)
exec_result = engine.execute(db_name='information_schema',
exec_result = engine.execute(db_name='mysql',
sql=f"ALTER USER {user_host} IDENTIFIED BY '{reset_pwd1}';")
if exec_result.error:
result = {'status': 1, 'msg': exec_result.error}
Expand All @@ -273,6 +279,37 @@ def reset_pwd(request):
return JsonResponse({'status': 0, 'msg': '', 'data': []})


@permission_required('sql.instance_account_manage', raise_exception=True)
def lock(request):
"""锁定/解锁账号"""
instance_id = request.POST.get('instance_id', 0)
user_host = request.POST.get('user_host')
is_locked = request.POST.get('is_locked')
lock_sql = ''

if not all([user_host]):
return JsonResponse({'status': 1, 'msg': '参数不完整,请确认后提交', 'data': []})

try:
instance = user_instances(request.user, db_type=['mysql']).get(id=instance_id)
except Instance.DoesNotExist:
return JsonResponse({'status': 1, 'msg': '你所在组未关联该实例', 'data': []})

# escape
user_host = MySQLdb.escape_string(user_host).decode('utf-8')

if is_locked == 'N':
lock_sql = f"ALTER USER {user_host} ACCOUNT LOCK;"
elif is_locked == 'Y':
lock_sql = f"ALTER USER {user_host} ACCOUNT UNLOCK;"

engine = get_engine(instance=instance)
exec_result = engine.execute(db_name='mysql', sql=lock_sql)
if exec_result.error:
return JsonResponse({'status': 1, 'msg': exec_result.error})
return JsonResponse({'status': 0, 'msg': '', 'data': []})


@permission_required('sql.instance_account_manage', raise_exception=True)
def delete(request):
"""删除账号"""
Expand All @@ -293,7 +330,7 @@ def delete(request):
user_host = MySQLdb.escape_string(user_host).decode('utf-8')

engine = get_engine(instance=instance)
exec_result = engine.execute(db_name='information_schema', sql=f"DROP USER {user_host};")
exec_result = engine.execute(db_name='mysql', sql=f"DROP USER {user_host};")
if exec_result.error:
return JsonResponse({'status': 1, 'msg': exec_result.error})
# 删除数据库对应记录
Expand Down
69 changes: 68 additions & 1 deletion sql/templates/instanceaccount.html
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,29 @@ <h6 style="color:red">注:此操作会修改账号密码,同时变更平台
</div>
</div>
</div>
<!-- 锁定账号模态框 -->
<div class="modal fade" id="lock-account" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">&times;</span></button>
<h4 class="modal-title"><span id="lock-title">锁定账号</span>
实例: <span id="lock-instance" style="color: red"></span>
账号: <span id="lock-user" style="color: red"></span></h4>
</div>
<div class="modal-body form-group">
<span id="lock-text" style="color: red">
确认锁定该账号?
</span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-danger" id="lockBtn">确定</button>
</div>
</div>
</div>
</div>
<!-- 删除账号模态框 -->
<div class="modal fade" id="delete-account" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
Expand Down Expand Up @@ -1138,7 +1161,13 @@ <h4 class="modal-title">删除账号
let btn_modify_grants = "<button class=\"btn btn-primary btn-xs\" user_host=\"" + row.user_host + "\" onclick=\"show_grants_modal(this)" + "\">授权</button>\n";
let btn_reset_passwd = "<button class=\"btn btn-warning btn-xs\" user_host=\"" + row.user_host + "\" onclick=\"show_reset_modal(this)" + "\">改密</button>\n";
let btn_del_account = "<button class=\"btn btn-danger btn-xs\" user_host=\"" + row.user_host + "\" onclick=\"show_delete_modal(this)" + "\">删除</button>\n";
return btn_edit + btn_modify_grants + btn_reset_passwd + btn_del_account
let btn_lock_account = "";
if (row.is_locked === 'N') {
btn_lock_account = "<button class=\"btn btn-danger btn-xs\" user_host=\"" + row.user_host + "\" is_locked=\"" + row.is_locked + "\" onclick=\"show_lock_modal(this)" + "\">锁定</button>\n";
} else if (row.is_locked === 'Y') {
btn_lock_account = "<button class=\"btn btn-success btn-xs\" user_host=\"" + row.user_host + "\" is_locked=\"" + row.is_locked + "\" onclick=\"show_lock_modal(this)" + "\">解锁</button>\n";
}
return btn_edit + btn_modify_grants + btn_reset_passwd + btn_lock_account + btn_del_account
}
}],
onLoadSuccess: function (data) {
Expand Down Expand Up @@ -1281,6 +1310,7 @@ <h4 class="modal-title">删除账号
let ins_name = $("#instance option:selected").text();
$("#modify-instance").text(ins_name);
$("#reset-instance").text(ins_name);
$("#lock-instance").text(ins_name);
$("#delete-instance").text(ins_name);
db_list();
}
Expand Down Expand Up @@ -1512,6 +1542,43 @@ <h4 class="modal-title">删除账号
});
}

//锁定or解锁账号
function show_lock_modal(obj) {
let user_host = $(obj).attr("user_host");
let is_locked = $(obj).attr("is_locked");
let operation = $(obj).text();
$("#lock-user").text(user_host);
$("#lock-title").text(operation + "账号")
$("#lock-text").text("确认" + operation + "该账号?")
$("#lock-account").modal('show');

$("#lockBtn").unbind("click").click(function () {
$.ajax({
type: "post",
url: "/instance/user/lock/",
dataType: "json",
data: {
instance_id: $("#instance").val(),
user_host: user_host,
is_locked: is_locked,
},
complete: function () {
},
success: function (data) {
if (data.status === 0) {
$('#lock-account').modal('hide');
user_list()
} else {
alert(data.msg);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
}

//删除账号
function show_delete_modal(obj) {
let user_host = $(obj).attr("user_host");
Expand Down
1 change: 1 addition & 0 deletions sql/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
path('instance/user/edit/', instance_account.edit),
path('instance/user/grant/', instance_account.grant),
path('instance/user/reset_pwd/', instance_account.reset_pwd),
path('instance/user/lock/', instance_account.lock),
path('instance/user/delete/', instance_account.delete),

path('instance/database/list/', sql.instance_database.databases),
Expand Down