授权管理

pull/26/head
ibuler@qq.com 2015-10-07 17:16:20 +08:00
parent d3465be672
commit afbbad1604
14 changed files with 252 additions and 394 deletions

View File

@ -14,48 +14,48 @@ class AssetGroup(models.Model):
def __unicode__(self):
return self.name
def get_asset(self):
return self.asset_set.all()
def get_asset_info(self, printable=False):
assets = self.get_asset()
ip_comment = {}
for asset in assets:
ip_comment[asset.ip] = asset.comment
for ip in sorted(ip_comment):
if ip_comment[ip]:
print '%-15s -- %s' % (ip, ip_comment[ip])
else:
print '%-15s' % ip
print ''
def get_asset_num(self):
return len(self.get_asset())
def get_user_group(self):
perm_list = self.perm_set.all()
user_group_list = []
for perm in perm_list:
user_group_list.append(perm.user_group)
return user_group_list
def get_user(self):
user_list = []
user_group_list = self.get_user_group()
for user_group in user_group_list:
user_list.extend(user_group.user_set.all())
return user_list
def is_permed(self, user=None, user_group=None):
if user:
if user in self.get_user():
return True
if user_group:
if user_group in self.get_user_group():
return True
return False
# def get_asset(self):
# return self.asset_set.all()
#
# def get_asset_info(self, printable=False):
# assets = self.get_asset()
# ip_comment = {}
# for asset in assets:
# ip_comment[asset.ip] = asset.comment
#
# for ip in sorted(ip_comment):
# if ip_comment[ip]:
# print '%-15s -- %s' % (ip, ip_comment[ip])
# else:
# print '%-15s' % ip
# print ''
#
# def get_asset_num(self):
# return len(self.get_asset())
#
# def get_user_group(self):
# perm_list = self.perm_set.all()
# user_group_list = []
# for perm in perm_list:
# user_group_list.append(perm.user_group)
# return user_group_list
#
# def get_user(self):
# user_list = []
# user_group_list = self.get_user_group()
# for user_group in user_group_list:
# user_list.extend(user_group.user_set.all())
# return user_list
#
# def is_permed(self, user=None, user_group=None):
# if user:
# if user in self.get_user():
# return True
#
# if user_group:
# if user_group in self.get_user_group():
# return True
# return False
class Asset(models.Model):
@ -72,21 +72,21 @@ class Asset(models.Model):
def __unicode__(self):
return self.ip
def get_user(self):
perm_list = []
asset_group_all = self.bis_group.all()
for asset_group in asset_group_all:
perm_list.extend(asset_group.perm_set.all())
user_group_list = []
for perm in perm_list:
user_group_list.append(perm.user_group)
user_permed_list = []
for user_group in user_group_list:
user_permed_list.extend(user_group.user_set.all())
user_permed_list = list(set(user_permed_list))
return user_permed_list
# def get_user(self):
# perm_list = []
# asset_group_all = self.bis_group.all()
# for asset_group in asset_group_all:
# perm_list.extend(asset_group.perm_set.all())
#
# user_group_list = []
# for perm in perm_list:
# user_group_list.append(perm.user_group)
#
# user_permed_list = []
# for user_group in user_group_list:
# user_permed_list.extend(user_group.user_set.all())
# user_permed_list = list(set(user_permed_list))
# return user_permed_list
class AssetAlias(models.Model):

View File

@ -278,15 +278,15 @@ def asset_edit(request):
if request.method == 'POST':
ip = request.POST.get('ip')
port = request.POST.get('port')
groups = request.POST.getlist('groups')
use_default_auth = True if request.POST.getlist('use_default_auth', []) else False
use_default = True if request.POST.getlist('use_default', []) else False
is_active = True if request.POST.get('is_active') else False
comment = request.POST.get('comment')
if not use_default_auth:
if not use_default:
username = request.POST.get('username')
password = request.POST.get('password')
port = request.POST.get('port')
if password == asset.password:
password_encode = password
else:
@ -294,6 +294,7 @@ def asset_edit(request):
else:
username = None
password_encode = None
port = 22
try:
asset_test = get_object(Asset, ip=ip)
@ -303,7 +304,7 @@ def asset_edit(request):
except ServerError:
pass
else:
db_asset_update(id=asset_id, ip=ip, port=port, use_default_auth=use_default_auth,
db_asset_update(id=asset_id, ip=ip, port=port, use_default=use_default,
username=username, password=password_encode,
is_active=is_active, comment=comment)
msg = u'主机 %s 修改成功' % ip

View File

@ -59,24 +59,43 @@ def playbook_run(inventory, playbook, default_user=None, default_port=None, defa
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
# run the playbook
results = PlayBook(host_list=inventory,
playbook=playbook,
forks=5,
remote_user=default_user,
remote_port=default_port,
private_key_file=default_pri_key_path,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
stats=stats,
become=True,
become_user='root').run()
print default_user, default_port, default_pri_key_path, inventory, playbook
if default_user and default_port and default_pri_key_path:
playbook = PlayBook(host_list=inventory,
playbook=playbook,
forks=5,
remote_user=default_user,
remote_port=default_port,
private_key_file=default_pri_key_path,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
stats=stats,
become=True,
become_user='root')
else:
playbook = PlayBook(host_list=inventory,
playbook=playbook,
forks=5,
callbacks=playbook_cb,
runner_callbacks=runner_cb,
stats=stats,
become=True,
become_user='root')
results = playbook.run()
results_r = {'unreachable': [], 'failures': [], 'success': []}
for hostname, result in results.items():
if result.get('failures', 2):
if result.get('unreachable', 2):
results_r['unreachable'].append(hostname)
print "%s >>> unreachable" % hostname
elif result.get('failures', 2):
results_r['failures'].append(hostname)
print "%s >>> Failed" % hostname
else:
results_r['success'].append(hostname)
print "%s >>> Success" % hostname
return results
return results_r
def perm_user_api(asset_new, asset_del, asset_group_new, asset_group_del, user=None, user_group=None):
@ -84,21 +103,12 @@ def perm_user_api(asset_new, asset_del, asset_group_new, asset_group_del, user=N
asset_new_ip = [] # 新授权的ip列表
asset_del_ip = [] # 回收授权的ip列表
if '' in asset_group_new:
asset_group_new.remove('')
if '' in asset_group_del:
asset_group_del.remove('')
asset_new_ip.extend([asset.ip for asset in get_object_list(Asset, asset_new)]) # 查库获取新授权ip
for asset_group_id in asset_group_new:
asset_new_ip.extend([asset.ip for asset in get_object(AssetGroup, id=asset_group_id).asset_set.all()]) # 同理
asset_del_ip.extend([asset.ip for asset in get_object_list(Asset, asset_del)]) # 查库获取回收授权的ip
for asset_group_id in asset_group_del:
asset_del_ip.extend([asset.ip for asset in get_object(AssetGroup, id=asset_group_id).asset_set.all()]) # 同理
print asset_new_ip
print asset_del_ip
asset_new_ip.extend([asset.ip for asset in asset_new]) # 查库获取新授权ip
for asset_group in asset_group_new:
asset_new_ip.extend([asset.ip for asset in asset_group.asset_set.all()]) # 同理
asset_del_ip.extend([asset.ip for asset in asset_del]) # 查库获取回收授权的ip
for asset_group in asset_group_del:
asset_del_ip.extend([asset.ip for asset in asset_group.asset_set.all()]) # 同理
if asset_new_ip or asset_del_ip:
host_group = {'new': asset_new_ip, 'del': asset_del_ip}
@ -123,8 +133,8 @@ def perm_user_api(asset_new, asset_del, asset_group_new, asset_group_del, user=N
else:
default_user = default_port = default_pri_key_path = ''
results = playbook_run(inventory, playbook, default_user, default_port, default_pri_key_path)
return results
results_r = playbook_run(inventory, playbook, default_user, default_port, default_pri_key_path)
return results_r
def refresh_group_api(user_group=None, asset_group=None):

File diff suppressed because one or more lines are too long

View File

@ -4,6 +4,7 @@ from django.db import models
class Setting(models.Model):
name = models.CharField(max_length=100)
default_user = models.CharField(max_length=100, null=True, blank=True)
default_port = models.IntegerField(max_length=10, null=True, blank=True)
default_pri_key_path = models.CharField(max_length=100, null=True, blank=True)

View File

@ -70,16 +70,14 @@ def user_asset_count(user):
"""
返回用户权限主机的数量
"""
assets_id = user.assets.split(',')
asset_groups = user.asset_groups.split(',')
assets = user.asset.all()
asset_groups = user.asset_group.all()
for asset_group_id in asset_groups:
asset_group = get_object(AssetGroup, id=asset_group_id)
for asset_group in asset_groups:
if asset_group:
assets_id.extend(asset.id for asset in asset_group.asset_set.all())
assets.extend(asset_group.asset_set.all())
assets_id = set(map(str, assets_id))
return len(assets_id)
return len(assets)
@register.filter(name='user_asset_group_count')
@ -87,7 +85,7 @@ def user_asset_group_count(user):
"""
返回用户权限主机组的数量
"""
return len(filter(lambda x: x, user.asset_groups.split(',')))
return len(user.asset_group.all())
#
# @register.filter(name='user_group_asset_count')

View File

@ -232,6 +232,8 @@ def logout(request):
def setting(request):
header_title, path1 = '项目设置', '设置'
setting_r = get_object(Setting, name='default')
if request.method == "POST":
username = request.POST.get('username', '')
port = request.POST.get('port', '')
@ -246,11 +248,11 @@ def setting(request):
f.write(private_key)
os.chmod(private_key_path, 0600)
if settings:
Setting.objects.filter(id=1).update(default_user=username, default_port=port,
default_pri_key_path=private_key_path)
Setting.objects.filter(name='default').update(default_user=username, default_port=port,
default_pri_key_path=private_key_path)
else:
settings = Setting(default_user=username, default_port=port,
default_pri_key_path=private_key_path).save()
setting_r = Setting(name='default', default_user=username, default_port=port,
default_pri_key_path=private_key_path).save()
msg = "设置成功"
return my_render('setting.html', locals(), request)

View File

@ -1,4 +1,4 @@
#coding: utf-8
# coding: utf-8
from django.db import models
@ -9,20 +9,20 @@ class UserGroup(models.Model):
name = models.CharField(max_length=80, unique=True)
# assets = models.TextField(max_length=1000, verbose_name="Assets", default='')
# asset_groups = models.CharField(max_length=1000, verbose_name="Asset Groups", default='')
assets = models.ManyToManyField(Asset)
asset_groups = models.ManyToManyField(AssetGroup)
comment = models.CharField(max_length=160, blank=True, null=True)
asset = models.ManyToManyField(Asset)
asset_group = models.ManyToManyField(AssetGroup)
def __unicode__(self):
return self.name
def get_user(self):
return self.user_set.all()
def update(self, **kwargs):
for key, value in kwargs.items():
self.__setattr__(key, value)
self.save()
# def get_user(self):
# return self.user_set.all()
#
# def update(self, **kwargs):
# for key, value in kwargs.items():
# self.__setattr__(key, value)
# self.save()
class User(models.Model):
@ -38,100 +38,100 @@ class User(models.Model):
role = models.CharField(max_length=2, choices=USER_ROLE_CHOICES, default='CU')
uuid = models.CharField(max_length=100)
group = models.ManyToManyField(UserGroup)
assets = models.ManyToManyField(Asset)
asset_groups = models.ManyToManyField(AssetGroup)
ssh_key_pwd = models.CharField(max_length=200)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True)
date_joined = models.DateTimeField(null=True)
asset = models.ManyToManyField(Asset)
asset_group = models.ManyToManyField(AssetGroup)
def __unicode__(self):
return self.username
def get_asset_group(self):
"""
Get user host_groups.
获取用户有权限的主机组
"""
host_group_list = []
perm_list = []
user_group_all = self.group.all()
for user_group in user_group_all:
perm_list.extend(user_group.perm_set.all())
for perm in perm_list:
host_group_list.append(perm.asset_group)
return host_group_list
def get_asset_group_info(self, printable=False):
"""
Get or print asset group info
获取或打印用户授权资产组
"""
asset_groups_info = {}
asset_groups = self.get_asset_group()
for asset_group in asset_groups:
asset_groups_info[asset_group.id] = [asset_group.name, asset_group.comment]
if printable:
for group_id in asset_groups_info:
if asset_groups_info[group_id][1]:
print "[%3s] %s -- %s" % (group_id,
asset_groups_info[group_id][0],
asset_groups_info[group_id][1])
else:
print "[%3s] %s" % (group_id, asset_groups_info[group_id][0])
print ''
else:
return asset_groups_info
def get_asset(self):
"""
Get the assets of under the user control.
获取主机列表
"""
assets = []
asset_groups = self.get_asset_group()
for asset_group in asset_groups:
assets.extend(asset_group.asset_set.all())
return assets
def get_asset_info(self, printable=False):
"""
Get or print the user asset info
获取或打印用户资产信息
"""
from jasset.models import AssetAlias
assets_info = {}
assets = self.get_asset()
for asset in assets:
asset_alias = AssetAlias.objects.filter(user=self, asset=asset)
if asset_alias and asset_alias[0].alias != '':
assets_info[asset.ip] = [asset.id, asset.ip, str(asset_alias[0].alias)]
else:
assets_info[asset.ip] = [asset.id, asset.ip, str(asset.comment)]
if printable:
ips = assets_info.keys()
ips.sort()
for ip in ips:
if assets_info[ip][2]:
print '%-15s -- %s' % (ip, assets_info[ip][2])
else:
print '%-15s' % ip
print ''
else:
return assets_info
def update(self, **kwargs):
for key, value in kwargs.items():
self.__setattr__(key, value)
self.save()
# def get_asset_group(self):
# """
# Get user host_groups.
# 获取用户有权限的主机组
# """
# host_group_list = []
# perm_list = []
# user_group_all = self.group.all()
# for user_group in user_group_all:
# perm_list.extend(user_group.perm_set.all())
#
# for perm in perm_list:
# host_group_list.append(perm.asset_group)
#
# return host_group_list
#
# def get_asset_group_info(self, printable=False):
# """
# Get or print asset group info
# 获取或打印用户授权资产组
# """
# asset_groups_info = {}
# asset_groups = self.get_asset_group()
#
# for asset_group in asset_groups:
# asset_groups_info[asset_group.id] = [asset_group.name, asset_group.comment]
#
# if printable:
# for group_id in asset_groups_info:
# if asset_groups_info[group_id][1]:
# print "[%3s] %s -- %s" % (group_id,
# asset_groups_info[group_id][0],
# asset_groups_info[group_id][1])
# else:
# print "[%3s] %s" % (group_id, asset_groups_info[group_id][0])
# print ''
# else:
# return asset_groups_info
#
# def get_asset(self):
# """
# Get the assets of under the user control.
# 获取主机列表
# """
# assets = []
# asset_groups = self.get_asset_group()
#
# for asset_group in asset_groups:
# assets.extend(asset_group.asset_set.all())
#
# return assets
#
# def get_asset_info(self, printable=False):
# """
# Get or print the user asset info
# 获取或打印用户资产信息
# """
# from jasset.models import AssetAlias
# assets_info = {}
# assets = self.get_asset()
#
# for asset in assets:
# asset_alias = AssetAlias.objects.filter(user=self, asset=asset)
# if asset_alias and asset_alias[0].alias != '':
# assets_info[asset.ip] = [asset.id, asset.ip, str(asset_alias[0].alias)]
# else:
# assets_info[asset.ip] = [asset.id, asset.ip, str(asset.comment)]
#
# if printable:
# ips = assets_info.keys()
# ips.sort()
# for ip in ips:
# if assets_info[ip][2]:
# print '%-15s -- %s' % (ip, assets_info[ip][2])
# else:
# print '%-15s' % ip
# print ''
# else:
# return assets_info
#
# def update(self, **kwargs):
# for key, value in kwargs.items():
# self.__setattr__(key, value)
# self.save()
class AdminGroup(models.Model):

View File

@ -16,6 +16,13 @@ function check_all(form) {
}
}
function checkAll(){
// 选择该页面所有checkbox
$('input[type=checkbox]').each(function(){
$(this).attr('checked', true)
})
}
//提取指定行的数据JSON格式
function GetRowData(row){
var rowData = {};
@ -89,29 +96,32 @@ function move(from, to, from_o, to_o) {
//}
//
function selectAllOption(){
var checklist = document.getElementsByName ("selected");
if(document.getElementById("select_all").checked)
{
for(var i=0;i<checklist.length;i++)
{
checklist[i].checked = 1;
}
}else{
for(var j=0;j<checklist.length;j++)
{
checklist[j].checked = 0;
}
}
//function selectAllOption(){
// var checklist = document.getElementsByName ("selected");
// if(document.getElementById("select_all").checked)
// {
// for(var i=0;i<checklist.length;i++)
// {
// checklist[i].checked = 1;
// }
// }else{
// for(var j=0;j<checklist.length;j++)
// {
// checklist[j].checked = 0;
// }
// }
//
// }
}
function checkAll(formID){
$('#'+formID+'option').each(function(){
$(this).attr('checked', true)
function selectAll(){
// 选择该页面所有option
$('option').each(function(){
$(this).attr('selected', true)
})
}
//
//function move_all(from, to){
// $("#"+from).children().each(function(){

View File

@ -50,21 +50,21 @@
<div class="col-sm-1">
<div class="radio i-checks">
<label>
<input type="checkbox" {% ifequal asset.use_default_auth 1 %} checked="" {% endifequal %} value="1" id="use_default_auth" name="use_default_auth">
<input type="checkbox" {% ifequal asset.use_default 1 %} checked="" {% endifequal %} value="1" id="use_default" name="use_default">
</label>
</div>
</div>
</div>
<div class="form-group" id="admin_account" {% ifequal asset.use_default_auth 1 %} style="display: none" {% endifequal %}>
<div class="form-group" id="admin_account" {% ifequal asset.use_default 1 %} style="display: none" {% endifequal %}>
<label class="col-sm-2 control-label"> 管理用户名<span class="red-fonts">*</span> </label>
<div class="col-sm-3">
<input type="text" {% ifnotequal asset.use_default_auth 1 %} value="{{ asset.username }}" {% endifnotequal %} name="username" class="form-control">
<input type="text" {% ifnotequal asset.use_default 1 %} value="{{ asset.username }}" {% endifnotequal %} name="username" class="form-control">
</div>
<label class="col-sm-1 control-label"> 密码<span class="red-fonts">*</span> </label>
<div class="col-sm-4">
<input type="password" {% ifnotequal asset.use_default_auth 1 %} value="{{ asset.password }}" {% endifnotequal %} name="password" class="form-control">
<input type="password" {% ifnotequal asset.use_default 1 %} value="{{ asset.password }}" {% endifnotequal %} name="password" class="form-control">
</div>
</div>
@ -123,7 +123,7 @@
<script>
$('document').ready(function(){
$('#use_default_auth').click(function(){
$('#use_default').click(function(){
if ($(this).is(':checked')){
$('#admin_account').css('display', 'none')
}

View File

@ -107,7 +107,7 @@
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">取消</button>
<button id="submit_button" class="btn btn-primary" type="submit" onclick="selectAllOption('userForm')">确认保存</button>
<button id="submit_button" class="btn btn-primary" type="submit" onclick="selectAll()">确认保存</button>
</div>
</div>
</div>

View File

@ -34,7 +34,6 @@
<div class="form-group">
<label for="" class="col-sm-2 control-label">用户<span class="red-fonts">*</span></label>
<div class="col-sm-4">
<input id="user_group_id" name="user_group_id"type="text" value="{{ user.id }}" style="display: none">
<input id="user_group_name" name="user_group_name" type="text" class="form-control" value="{{ user.name }}" readonly>
</div>
</div>
@ -108,7 +107,7 @@
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">取消</button>
<button id="submit_button" class="btn btn-primary" type="submit" onclick="selectAllOption('userForm')">确认保存</button>
<button id="submit_button" class="btn btn-primary" type="submit" onclick="checkAll('userPerm')">确认保存</button>
</div>
</div>
</div>
@ -120,37 +119,4 @@
</div>
</div>
<script>
$('#sudoPerm').validator({
timely: 2,
theme: "yellow_right_effect",
fields: {
"name": {
rule: "required",
tip: "输入授权名",
ok: "",
msg: {required: "必须填写!"}
}
},
valid: function(form) {
form.submit();
}
});
$(document).ready(function(){
$("#submit_button").click(function(){
$('#user_groups_select option').each(function(){
$(this).prop('selected', true)
})
$('#asset_groups_select option').each(function(){
$(this).prop('selected', true)
})
})
})
</script>
{% endblock %}

View File

@ -54,8 +54,8 @@
<td class="text-center">
<a href="/juser/user_list/?gid={{ user.id }}">{{ user.group.all | groups2str }} </a>
</td>
<td class="text-center"> <a href="/jasset/asset_list/?gid={{ user.id }}">{{ user | user_asset_count }} </a> </td>
<td class="text-center"> <a href="/jasset/group_list/?gid={{ user.id }}">{{ user | user_asset_group_count }}</a></td>
<td class="text-center"> <a href="/jasset/asset_list/?gid={{ user.id }}">{{ user.name }} </a> </td>
<td class="text-center"> <a href="/jasset/group_list/?gid={{ user.id }}">{{ user.name }}</a></td>
<td class="text-center">
<a href="../perm_user_detail/?id={{ user.id }}" class="btn btn-xs btn-primary">详情</a>
<a href="../perm_user_edit/?id={{ user.id }}" class="btn btn-xs btn-danger">编辑</a>

View File

@ -47,21 +47,21 @@
<div class="form-group">
<label for="username" class="col-sm-2 control-label">默认用户名<span class="red-fonts">*</span></label>
<div class="col-sm-8">
<input id="username" name="username" placeholder="Username" type="text" class="form-control">
<input id="username" name="username" placeholder="Username" type="text" value="{{ setting_r.default_user }}" class="form-control">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label for="port" class="col-sm-2 control-label">默认ssh端口<span class="red-fonts">*</span></label>
<div class="col-sm-8">
<input id="port" name="port" placeholder="Port" type="text" class="form-control">
<input id="port" name="port" placeholder="Port" type="text" value="{{ setting_r.default_port }}" class="form-control">
</div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label for="key" class="col-sm-2 control-label">默认密钥<span class="red-fonts">*</span></label>
<div class="col-sm-8">
<textarea class="form-control" name="key" placeholder="" rows="10" style="font-size: 9px;"></textarea>
<textarea class="form-control" name="key" placeholder="请复制粘贴私钥(原来的因为安全原因不被显示)" rows="10" style="font-size: 9px;"></textarea>
</div>
</div>
<div class="hr-line-dashed"></div>
@ -91,20 +91,4 @@
</div>
</div>
</div>
<script>
$(document).ready(function(){
});
$("#refresh").click(function(){
$.get('/jperm/sudo_refresh/',
{'test':''},
function(data){
alert(data)
}
)
})
});
</script>
{% endblock %}