用户模块修改告一段落

pull/26/head
ibuler 2015-09-06 21:37:22 +08:00
parent 3efd810fe1
commit 4eb78e151e
15 changed files with 178 additions and 208 deletions

View File

@ -9,15 +9,8 @@ from django.shortcuts import get_object_or_404
from jperm.models import Perm
from jumpserver.api import *
cryptor = PyCrypt(KEY)
class RaiseError(Exception):
pass
def my_render(template, data, request):
return render_to_response(template, data, context_instance=RequestContext(request))
def get_host_groups(groups):

View File

@ -538,11 +538,9 @@ def get_session_user_info(request):
获取用户的信息
"""
user_id = request.session.get('user_id', 0)
user = User.objects.filter(id=user_id)
user = get_object(User, id=user_id)
if user:
user = user[0]
dept = user.dept
return [user.id, user.username, user, dept.id, dept.name, dept]
return [user.id, user.username, user]
def get_user_dept(request):
@ -698,6 +696,10 @@ def http_error(request, emg):
return render_to_response('error.html', locals())
def my_render(template, data, request):
return render_to_response(template, data, context_instance=RequestContext(request))
CRYPTOR = PyCrypt(KEY)
# if LDAP_ENABLE:

View File

@ -7,19 +7,13 @@ from jperm.models import Apply
def name_proc(request):
user_id = request.session.get('user_id')
role_id = request.session.get('role_id')
if role_id == 2:
# if role_id == 2:
user_total_num = User.objects.all().count()
user_active_num = User.objects.filter().count()
host_total_num = Asset.objects.all().count()
host_active_num = Asset.objects.filter(is_active=True).count()
else:
user, dept = get_session_user_dept(request)
print user, dept
user_total_num = dept.user_set.all().count()
user_active_num = dept.user_set.filter(is_active=True).count()
host_total_num = dept.asset_set.all().count()
host_active_num = dept.asset_set.all().filter(is_active=True).count()
pass
# else:
# pass
username = User.objects.get(id=user_id).name
apply_info = Apply.objects.filter(admin=username, status=0, read=0)

View File

@ -290,7 +290,7 @@ def to_dept_name(user_id):
@register.filter(name='to_role_name')
def to_role_name(role_id):
role_dict = {'0': '普通用户', '1': '部门管理员', '2': '超级管理员'}
role_dict = {'0': '普通用户', '1': '管理员', '2': '超级管理员'}
return role_dict.get(str(role_id), '未知')
@ -302,7 +302,7 @@ def to_avatar(role_id='0'):
@register.filter(name='get_user_asset_group')
def get_user_asset_group(user):
return user_perm_group_api(user)
return user.get_asset_group()
@register.filter(name='group_asset_list')

View File

@ -50,12 +50,9 @@ def get_data(data, items, option):
@require_role(role='user')
def index_cu(request):
user_id = request.session.get('user_id')
user = User.objects.filter(id=user_id)
if user:
user = user[0]
user = get_object(User, id=user_id)
login_types = {'L': 'LDAP', 'M': 'MAP'}
user_id = request.session.get('user_id')
username = User.objects.get(id=user_id).username
username = user.username
posts = user.get_asset()
host_count = len(posts)
new_posts = []
@ -91,16 +88,16 @@ def index(request):
week_data = Log.objects.filter(start_time__range=[from_week, datetime.datetime.now()])
elif is_role_request(request, 'admin'):
user = get_session_user_info(request)[2]
dept_name, dept = get_session_user_info(request)[4:]
users = User.objects.filter(dept=dept)
hosts = Asset.objects.filter(dept=dept)
online = Log.objects.filter(dept_name=dept_name, is_finished=0)
online_host = online.values('host').distinct()
online_user = online.values('user').distinct()
active_users = users.filter(is_active=1)
active_hosts = hosts.filter(is_active=1)
week_data = Log.objects.filter(dept_name=dept_name, start_time__range=[from_week, datetime.datetime.now()])
return index_cu(request)
# user = get_session_user_info(request)[2]
# users = User.objects.filter(dept=dept)
# hosts = Asset.objects.filter(dept=dept)
# online = Log.objects.filter(dept_name=dept_name, is_finished=0)
# online_host = online.values('host').distinct()
# online_user = online.values('user').distinct()
# active_users = users.filter(is_active=1)
# active_hosts = hosts.filter(is_active=1)
# week_data = Log.objects.filter(dept_name=dept_name, start_time__range=[from_week, datetime.datetime.now()])
# percent of dashboard
if users.count() == 0:
@ -157,32 +154,32 @@ def skin_config(request):
return render_to_response('skin_config.html')
def pages(posts, r):
"""分页公用函数"""
contact_list = posts
p = paginator = Paginator(contact_list, 10)
try:
current_page = int(r.GET.get('page', '1'))
except ValueError:
current_page = 1
page_range = page_list_return(len(p.page_range), current_page)
try:
contacts = paginator.page(current_page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
if current_page >= 5:
show_first = 1
else:
show_first = 0
if current_page <= (len(p.page_range) - 3):
show_end = 1
else:
show_end = 0
return contact_list, p, contacts, page_range, current_page, show_first, show_end
# def pages(posts, r):
# """分页公用函数"""
# contact_list = posts
# p = paginator = Paginator(contact_list, 10)
# try:
# current_page = int(r.GET.get('page', '1'))
# except ValueError:
# current_page = 1
#
# page_range = page_list_return(len(p.page_range), current_page)
#
# try:
# contacts = paginator.page(current_page)
# except (EmptyPage, InvalidPage):
# contacts = paginator.page(paginator.num_pages)
#
# if current_page >= 5:
# show_first = 1
# else:
# show_first = 0
# if current_page <= (len(p.page_range) - 3):
# show_end = 1
# else:
# show_end = 0
#
# return contact_list, p, contacts, page_range, current_page, show_first, show_end
def is_latest():

View File

@ -120,6 +120,11 @@ class User(models.Model):
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

@ -22,7 +22,8 @@ urlpatterns = patterns('juser.views',
(r'^user_del_ajax/$', 'user_del_ajax'),
(r'^user_edit/$', view_splitter, {'su': user_edit, 'adm': user_edit_adm}),
(r'^profile/$', 'profile'),
(r'^chg_info/$', 'chg_info'),
(r'^change_info/$', 'change_info'),
(r'^regen_ssh_key/$', 'regen_ssh_key'),
(r'^chg_role/$', 'chg_role'),
(r'^down_key/$', 'down_key'),
)

View File

@ -55,7 +55,7 @@ def group_add(request):
else:
msg = u'添加组 %s 成功' % group_name
return render_to_response('juser/group_add.html', locals(), context_instance=RequestContext(request))
return my_render('juser/group_add.html', locals(), request)
@require_role(role='super')
@ -72,7 +72,7 @@ def group_list(request):
user_group_list = user_group_list.filter(Q(name__icontains=keyword) | Q(comment__icontains=keyword))
contacts, p, contacts, page_range, current_page, show_first, show_end = pages(user_group_list, request)
return render_to_response('juser/group_list.html', locals(), context_instance=RequestContext(request))
return my_render('juser/group_list.html', locals(), request)
@require_role(role='super')
@ -169,7 +169,7 @@ def group_edit(request):
users_selected = user_group.user_set.all()
users_remain = [user for user in users_all if user not in users_selected]
return render_to_response('juser/group_edit.html', locals(), context_instance=RequestContext(request))
return my_render('juser/group_edit.html', locals(), request)
# @require_role(role='admin')
@ -275,7 +275,7 @@ def user_add(request):
if MAIL_ENABLE and send_mail_need:
user_add_mail(user, kwargs=locals())
msg = get_display_msg(user, password, ssh_key_pwd, ssh_key_login_need, send_mail_need)
return render_to_response('juser/user_add.html', locals(), context_instance=RequestContext(request))
return my_render('juser/user_add.html', locals(), request)
# @require_role(role='admin')
@ -369,7 +369,7 @@ def user_list(request):
contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(contact_list, request)
return render_to_response('juser/user_list.html', locals(), context_instance=RequestContext(request))
return my_render('juser/user_list.html', locals(), request)
# @require_role(role='admin')
@ -413,12 +413,13 @@ def user_detail(request):
user = get_object(User, id=user_id)
if user:
pass
# asset_group_permed = user.get_asset_group()
logs_last = Log.objects.filter(user=user.name).order_by('-start_time')[0:10]
logs_all = Log.objects.filter(user=user.name).order_by('-start_time')
logs_num = len(logs_all)
# logs_last = Log.objects.filter(user=user.name).order_by('-start_time')[0:10]
# logs_all = Log.objects.filter(user=user.name).order_by('-start_time')
# logs_num = len(logs_all)
return render_to_response('juser/user_detail.html', locals(), context_instance=RequestContext(request))
return my_render('juser/user_detail.html', locals(), request)
@require_role(role='admin')
@ -545,9 +546,8 @@ def user_edit(request):
extra = request.POST.getlist('extra', [])
is_active = True if '0' in extra else False
email_need = True if '2' in extra else False
user_role = {'SU': u'超级管理员', 'DA': u'部门管理员', 'CU': u'普通用户'}
print '#'*10 + str(email_need)
print extra
user_role = {'SU': u'超级管理员', 'GA': u'部门管理员', 'CU': u'普通用户'}
if user_id:
user = get_object(User, id=user_id)
else:
@ -568,8 +568,9 @@ def user_edit(request):
role=role_post,
is_active=is_active)
if email_need:
print '#'* 10 + role_post
if email_need:
msg = u"""
Hi %s:
您的信息已修改请登录跳板机查看详细信息
@ -579,68 +580,69 @@ def user_edit(request):
角色%s
""" % (user.name, URL, user.username, password_decode, user_role.get(role_post, u''))
send_mail('您的信息已修改', msg, MAIL_FROM, [email], fail_silently=False)
return HttpResponseRedirect('/juser/user_list/')
return render_to_response('juser/user_edit.html', locals(), context_instance=RequestContext(request))
return my_render('juser/user_edit.html', locals(), request)
@require_role(role='admin')
# @require_role(role='admin')
def user_edit_adm(request):
header_title, path1, path2 = '编辑用户', '用户管理', '用户编辑'
user, dept = get_session_user_dept(request)
if request.method == 'GET':
user_id = request.GET.get('id', '')
if not user_id:
return HttpResponseRedirect('/juser/user_list/')
if not validate(request, user=[user_id]):
return HttpResponseRedirect('/juser/user_list/')
user = User.objects.filter(id=user_id)
dept_all = DEPT.objects.all()
group_all = dept.usergroup_set.all()
if user:
user = user[0]
groups_str = ' '.join([str(group.id) for group in user.group.all()])
else:
user_id = request.POST.get('user_id', '')
password = request.POST.get('password', '')
name = request.POST.get('name', '')
email = request.POST.get('email', '')
groups = request.POST.getlist('groups', [])
ssh_key_pwd = request.POST.get('ssh_key_pwd', '')
is_active = True if request.POST.get('is_active', '1') == '1' else False
if not validate(request, user=[user_id], user_group=groups):
return HttpResponseRedirect('/juser/user_edit/')
if user_id:
user = User.objects.filter(id=user_id)
if user:
user = user[0]
else:
return HttpResponseRedirect('/juser/user_list/')
if password != user.password:
password = CRYPTOR.md5_crypt(password)
if ssh_key_pwd != user.ssh_key_pwd:
ssh_key_pwd = CRYPTOR.encrypt(ssh_key_pwd)
db_update_user(user_id=user_id,
password=password,
name=name,
email=email,
groups=groups,
is_active=is_active,
ssh_key_pwd=ssh_key_pwd)
return HttpResponseRedirect('/juser/user_list/')
return render_to_response('juser/user_edit.html', locals(), context_instance=RequestContext(request))
pass
# header_title, path1, path2 = '编辑用户', '用户管理', '用户编辑'
# user, dept = get_session_user_dept(request)
# if request.method == 'GET':
# user_id = request.GET.get('id', '')
# if not user_id:
# return HttpResponseRedirect('/juser/user_list/')
#
# if not validate(request, user=[user_id]):
# return HttpResponseRedirect('/juser/user_list/')
#
# user = User.objects.filter(id=user_id)
# dept_all = DEPT.objects.all()
# group_all = dept.usergroup_set.all()
# if user:
# user = user[0]
# groups_str = ' '.join([str(group.id) for group in user.group.all()])
#
# else:
# user_id = request.POST.get('user_id', '')
# password = request.POST.get('password', '')
# name = request.POST.get('name', '')
# email = request.POST.get('email', '')
# groups = request.POST.getlist('groups', [])
# ssh_key_pwd = request.POST.get('ssh_key_pwd', '')
# is_active = True if request.POST.get('is_active', '1') == '1' else False
#
# if not validate(request, user=[user_id], user_group=groups):
# return HttpResponseRedirect('/juser/user_edit/')
# if user_id:
# user = User.objects.filter(id=user_id)
# if user:
# user = user[0]
# else:
# return HttpResponseRedirect('/juser/user_list/')
#
# if password != user.password:
# password = CRYPTOR.md5_crypt(password)
#
# if ssh_key_pwd != user.ssh_key_pwd:
# ssh_key_pwd = CRYPTOR.encrypt(ssh_key_pwd)
#
# db_update_user(user_id=user_id,
# password=password,
# name=name,
# email=email,
# groups=groups,
# is_active=is_active,
# ssh_key_pwd=ssh_key_pwd)
#
# return HttpResponseRedirect('/juser/user_list/')
#
# return render_to_response('juser/user_edit.html', locals(), context_instance=RequestContext(request))
#
def profile(request):
@ -651,40 +653,46 @@ def profile(request):
return render_to_response('juser/profile.html', locals(), context_instance=RequestContext(request))
def chg_info(request):
def change_info(request):
header_title, path1, path2 = '修改信息', '用户管理', '修改个人信息'
user_id = request.session.get('user_id')
user_set = User.objects.filter(id=user_id)
user = get_object(User, id=user_id)
error = ''
if user_set:
user = user_set[0]
else:
if not user:
return HttpResponseRedirect('/')
if request.method == 'POST':
name = request.POST.get('name', '')
password = request.POST.get('password', '')
ssh_key_pwd = request.POST.get('ssh_key_pwd', '')
email = request.POST.get('email', '')
if '' in [name, password, ssh_key_pwd, email]:
if '' in [name, password, email]:
error = '不能为空'
if len(password) < 6 or len(ssh_key_pwd) < 6:
if len(password) < 6 :
error = '密码须大于6位'
if not error:
if password != user.password:
password = CRYPTOR.md5_crypt(password)
if ssh_key_pwd != user.ssh_key_pwd:
gen_ssh_key(user.username, ssh_key_pwd)
ssh_key_pwd = CRYPTOR.md5_crypt(ssh_key_pwd)
user_set.update(name=name, password=password, ssh_key_pwd=ssh_key_pwd, email=email)
user.update(name=name, password=password, email=email)
msg = '修改成功'
return render_to_response('juser/chg_info.html', locals(), context_instance=RequestContext(request))
return render_to_response('juser/change_info.html', locals(), context_instance=RequestContext(request))
@require_role(role='user')
def regen_ssh_key(request):
uuid = request.GET.get('uuid', '')
user = get_object(User, uuid=uuid)
if not user:
return HttpResponse('没有该用户')
username = user.username
ssh_key_pass = PyCrypt.random_pass(16)
gen_ssh_key(username, ssh_key_pass)
return HttpResponse('ssh密钥已生成密码为 %s, 请到下载页面下载' % ssh_key_pass)
@require_role(role='user')
@ -693,21 +701,14 @@ def down_key(request):
if is_role_request(request, 'super'):
user_id = request.GET.get('id')
if is_role_request(request, 'admin'):
user_id = request.GET.get('id')
if not validate(request, user=[user_id]):
user_id = request.session.get('user_id')
if is_role_request(request, 'user'):
user_id = request.session.get('user_id')
if user_id:
user = User.objects.filter(id=user_id)
user = get_object(User, id=user_id)
if user:
user = user[0]
username = user.username
private_key_dir = os.path.join(BASE_DIR, 'keys/jumpserver/')
private_key_file = os.path.join(private_key_dir, username+".pem")
private_key_file = os.path.join(BASE_DIR, 'keys/jumpserver', username+".pem")
if os.path.isfile(private_key_file):
f = open(private_key_file)
data = f.read()

View File

@ -16,12 +16,6 @@
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#">未启用 1</a>
</li>
<li><a href="#">未启用 2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
@ -117,10 +111,6 @@
<td class="text-navy">角色</td>
<td>{{ user.id | get_role }}</td>
</tr>
<tr>
<td class="text-navy">部门</td>
<td>{{ user.dept.name }}</td>
</tr>
<tr>
<td class="text-navy">Email</td>
<td>{{ user.email }}</td>

View File

@ -14,15 +14,7 @@
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#">未启用 1</a>
</li>
<li><a href="#">未启用 2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
@ -59,11 +51,11 @@
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<label for="ssh_key_pwd" class="col-sm-2 control-label">密钥密码<span class="red-fonts">*</span></label>
<label for="ssh_key_pwd" class="col-sm-2 control-label">SSH密钥</label>
<div class="col-sm-8">
<input id="ssh_key_pwd" name="ssh_key_pwd" placeholder="SSH Key Password" type="password" class="form-control" value="{{ user.ssh_key_pwd }}">
<a value="/juser/regen_ssh_key/?uuid={{ user.uuid }}" id="regen_ssh_key" class="form-control"> 重新生成</a>
<span class="help-block m-b-none">
登陆 Jumpserver 使用的SSH密钥的密码,更改密钥密码需要重新下载密钥
重新生成密钥,需要重新下载并导入
</span>
</div>
</div>
@ -89,7 +81,9 @@
</div>
</div>
</div>
{% endblock %}
{% block self_footer_js %}
<script>
$('#userForm').validator({
timely: 2,
@ -102,12 +96,6 @@ $('#userForm').validator({
ok: "",
msg: {required: "必须填写!"}
},
"ssh_key_pwd": {
rule: "required;length[6~50]",
tip: "ssh私钥密码",
ok: "",
msg: {required: "必须填写"}
},
"name": {
rule: "required",
tip: "姓名",
@ -119,14 +107,25 @@ $('#userForm').validator({
tip: "Email",
ok: "",
msg: {required: "必须填写"}
},
}
},
valid: function(form) {
form.submit();
}
});
$("document").ready(function() {
$("#regen_ssh_key").click(function () {
alert('申请已提交,请等待,请勿重复提交');
$.get(
$(this).attr('value'),
{},
function(data){
alert(data)
}
)
})
})
</script>
{% endblock %}

View File

@ -32,7 +32,7 @@
<input type="text" class="form-control input-sm" id="search_input" name="search" placeholder="Search">
<div class="input-group-btn">
<button id='search_btn' type="submit" class="btn btn-sm btn-primary">
—搜索—
-搜索-
</button>
</div>
</div>

View File

@ -24,7 +24,6 @@
<td class="text-center">用户名</td>
<td class="text-center">姓名</td>
<td class="text-center">角色</td>
<td class="text-center">部门</td>
<td class="text-center">Email</td>
<td class="text-center">激活</td>
{# <td class="text-center">添加时间</td>#}
@ -38,7 +37,6 @@
<td class="text-center">{{ user.username }}</td>
<td class="text-center">{{ user.name }}</td>
<td class="text-center">{{ user.id | get_role }}</td>
<td class="text-center">{{ user.dept.name }}</td>
<td class="text-center">{{ user.email }}</td>
<td class="text-center">{{ user.is_active|bool2str }}</td>
{# <td class="text-center">{{ user.date_joined }}</td>#}

View File

@ -48,10 +48,6 @@
<td class="text-navy">角色</td>
<td>{{ user.id | get_role }}</td>
</tr>
<tr>
<td class="text-navy">部门</td>
<td>{{ user.dept.name }}</td>
</tr>
<tr>
<td class="text-navy">Email</td>
<td>{{ user.email }}</td>

View File

@ -10,18 +10,12 @@
<div class="ibox-title">
<h5> 查看用户 </h5>
<div class="ibox-tools">
<a class="collapse-link">
<a class="collapise-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#">未启用 1</a>
</li>
<li><a href="#">未启用 2</a>
</li>
</ul>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
@ -37,7 +31,7 @@
<input type="text" class="form-control input-sm" id="search_input" name="keyword" placeholder="Search">
<div class="input-group-btn">
<button id='search_btn' type="submit" class="btn btn-sm btn-primary">
- 搜索 -
-搜索-
</button>
</div>
</div>

View File

@ -7,7 +7,7 @@
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<span class="clear">
<span class="block m-t-xs">
<strong class="font-bold">{{ session_user_id | to_name}} <span style="color: #8095a8">{{ session_user_id | to_dept_name}}</span></strong>
<strong class="font-bold">{{ session_user_id | to_name}} <span style="color: #8095a8"></span></strong>
</span>
<span class="text-muted text-xs block">
{{ session_role_id | to_role_name }} <b class="caret"></b>
@ -16,8 +16,8 @@
</a>
<ul class="dropdown-menu animated fadeInRight m-t-xs">
<li><a value="/juser/profile/?id={{ session_user_id }}" class="iframe_user">个人信息</a></li>
<li><a href="/juser/chg_info/">修改信息</a></li>
<li><a href="/juser/chg_role/">切换角色</a></li>
<li><a href="/juser/change_info/">修改信息</a></li>
<li><a href="/juser/change_role/">切换角色</a></li>
<li class="divider"></li>
<li><a href="/logout/">注销</a></li>