修改用户添加视图

pull/26/head
root 2015-08-29 00:09:36 +08:00
parent 10d96a9767
commit 1e170714c0
7 changed files with 156 additions and 167 deletions

View File

@ -28,8 +28,9 @@ web_socket_host = 192.168.40.140:3000
[mail] [mail]
mail_enable = 1
email_host = smtp.qq.com email_host = smtp.qq.com
email_port = 25 email_port = 25
email_host_user = 1152704203@qq.com email_host_user = xxxxxxxxxx@qq.com
email_host_password = xxxxx email_host_password = xxxxxxxxx
email_use_tls = False email_use_tls = False

View File

@ -51,6 +51,7 @@ LOGIN_NAME = getpass.getuser()
LDAP_ENABLE = CONF.getint('ldap', 'ldap_enable') LDAP_ENABLE = CONF.getint('ldap', 'ldap_enable')
SEND_IP = CONF.get('base', 'ip') SEND_IP = CONF.get('base', 'ip')
SEND_PORT = CONF.get('base', 'port') SEND_PORT = CONF.get('base', 'port')
MAIL_ENABLE = CONF.get('mail', 'mail_enable')
MAIL_FROM = CONF.get('mail', 'email_host_user') MAIL_FROM = CONF.get('mail', 'email_host_user')
log_dir = os.path.join(BASE_DIR, 'logs') log_dir = os.path.join(BASE_DIR, 'logs')
@ -397,18 +398,22 @@ class PyCrypt(object):
self.mode = AES.MODE_CBC self.mode = AES.MODE_CBC
@staticmethod @staticmethod
def random_pass(): def random_pass(length, especial=False):
""" """
random password random password
随机生成密码 随机生成密码
""" """
salt_key = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@$%^&*()_' salt_key = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
symbol = '!@$%^&*()_' symbol = '!@$%^&*()_'
salt_list = [] salt_list = []
for i in range(60): if especial:
salt_list.append(random.choice(salt_key)) for i in range(length-4):
for i in range(4): salt_list.append(random.choice(salt_key))
salt_list.append(random.choice(symbol)) for i in range(4):
salt_list.append(random.choice(symbol))
else:
for i in range(length):
salt_list.append(random.choice(salt_key))
salt = ''.join(salt_list) salt = ''.join(salt_list)
return salt return salt

View File

@ -119,3 +119,13 @@ class User(models.Model):
print '' print ''
else: else:
return assets_info return assets_info
class AdminGroup(models.Model):
"""
under the user control group
用户可以管理的用户组或组的管理员是该用户
"""
user = models.ForeignKey(User)
group = models.ForeignKey(UserGroup)

View File

@ -11,7 +11,7 @@ urlpatterns = patterns('juser.views',
(r'^group_list/$', group_list), (r'^group_list/$', group_list),
(r'^group_del/$', group_del), (r'^group_del/$', group_del),
(r'^group_del_ajax', group_del_ajax), (r'^group_del_ajax', group_del_ajax),
(r'^group_edit/$', view_splitter, {'su': group_edit, 'adm': group_edit_adm}), (r'^group_edit/$',group_edit),
(r'^user_add/$', view_splitter, {'su': user_add, 'adm': user_add_adm}), (r'^user_add/$', view_splitter, {'su': user_add, 'adm': user_add_adm}),
(r'^user_list/$', view_splitter, {'su': user_list, 'adm': user_list_adm}), (r'^user_list/$', view_splitter, {'su': user_list, 'adm': user_list_adm}),
(r'^user_detail/$', 'user_detail'), (r'^user_detail/$', 'user_detail'),

View File

@ -2,6 +2,7 @@
from Crypto.PublicKey import RSA from Crypto.PublicKey import RSA
from juser.models import AdminGroup
from jumpserver.api import * from jumpserver.api import *
@ -55,6 +56,8 @@ def db_add_user(**kwargs):
数据库中添加用户 数据库中添加用户
""" """
groups_post = kwargs.pop('groups') groups_post = kwargs.pop('groups')
admin_groups = kwargs.pop('admin_groups')
role = kwargs.get('role', 'CU')
user = User(**kwargs) user = User(**kwargs)
user.save() user.save()
if groups_post: if groups_post:
@ -63,6 +66,12 @@ def db_add_user(**kwargs):
group = UserGroup.objects.filter(id=group_id) group = UserGroup.objects.filter(id=group_id)
group_select.extend(group) group_select.extend(group)
user.group = group_select user.group = group_select
if admin_groups and role == 'GA': # 如果是组管理员就要添加组管理员和组到管理组中
for group_id in admin_groups:
group = get_object(UserGroup, id=group_id)
if group:
AdminGroup(user=user, group=group).save()
return user return user
@ -132,6 +141,27 @@ def server_add_user(username, password, ssh_key_pwd):
gen_ssh_key(username, ssh_key_pwd) gen_ssh_key(username, ssh_key_pwd)
def user_add_mail(user, kwargs):
"""
add user send mail
发送用户添加邮件
"""
print kwargs
user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
mail_title = u'恭喜你的跳板机用户 %s 添加成功 Jumpserver' % user.name
mail_msg = u"""
Hi, %s
您的用户名 %s
您的角色 %s
您的web登录密码 %s
您的ssh密钥文件密码 %s
密钥下载地址 http://%s:%s/juser/down_key/?id=%s
说明 请登陆后再下载密钥
""" % (user.name, user.username, user_role.get(user.role, u'普通用户'),
kwargs.get('password'), kwargs.get('ssh_key_pwd'), SEND_IP, SEND_PORT, user.id)
send_mail(mail_title, mail_msg, MAIL_FROM, [user.email], fail_silently=False)
def server_del_user(username): def server_del_user(username):
""" """
delete a user from jumpserver linux system delete a user from jumpserver linux system
@ -146,11 +176,9 @@ def ldap_add_user(username, ldap_pwd):
在LDAP中添加用户 在LDAP中添加用户
""" """
user_dn = "uid=%s,ou=People,%s" % (username, LDAP_BASE_DN) user_dn = "uid=%s,ou=People,%s" % (username, LDAP_BASE_DN)
password_sha512 = PyCrypt.gen_sha512(PyCrypt.gen_rand_pwd(6), ldap_pwd) password_sha512 = PyCrypt.gen_sha512(PyCrypt.random_pass(6), ldap_pwd)
user = User.objects.filter(username=username) user = get_object(UserGroup, username=username)
if user: if not user:
user = user[0]
else:
raise ServerError(u'用户 %s 不存在' % username) raise ServerError(u'用户 %s 不存在' % username)
user_attr = {'uid': [str(username)], user_attr = {'uid': [str(username)],

View File

@ -171,52 +171,52 @@ def group_edit(request):
return render_to_response('juser/group_edit.html', locals(), context_instance=RequestContext(request)) return render_to_response('juser/group_edit.html', locals(), context_instance=RequestContext(request))
@require_role(role='admin') # @require_role(role='admin')
def group_edit_adm(request): # def group_edit_adm(request):
error = '' # error = ''
msg = '' # msg = ''
header_title, path1, path2 = '修改小组信息', '用户管理', '编辑小组' # header_title, path1, path2 = '修改小组信息', '用户管理', '编辑小组'
user, dept = get_session_user_dept(request) # user, dept = get_session_user_dept(request)
if request.method == 'GET': # if request.method == 'GET':
group_id = request.GET.get('id', '') # group_id = request.GET.get('id', '')
if not validate(request, user_group=[group_id]): # if not validate(request, user_group=[group_id]):
return HttpResponseRedirect('/juser/group_list/') # return HttpResponseRedirect('/juser/group_list/')
group = UserGroup.objects.filter(id=group_id) # group = UserGroup.objects.filter(id=group_id)
if group: # if group:
group = group[0] # group = group[0]
users_all = dept.user_set.all() # users_all = dept.user_set.all()
users_selected = group.user_set.all() # users_selected = group.user_set.all()
users = [user for user in users_all if user not in users_selected] # users = [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 render_to_response('juser/group_edit.html', locals(), context_instance=RequestContext(request))
else: # else:
group_id = request.POST.get('group_id', '') # group_id = request.POST.get('group_id', '')
group_name = request.POST.get('group_name', '') # group_name = request.POST.get('group_name', '')
comment = request.POST.get('comment', '') # comment = request.POST.get('comment', '')
users_selected = request.POST.getlist('users_selected') # users_selected = request.POST.getlist('users_selected')
#
users = [] # users = []
try: # try:
if not validate(request, user=users_selected): # if not validate(request, user=users_selected):
raise ServerError(u'右侧非部门用户') # raise ServerError(u'右侧非部门用户')
#
if not validate(request, user_group=[group_id]): # if not validate(request, user_group=[group_id]):
raise ServerError(u'没有权限修改本组') # raise ServerError(u'没有权限修改本组')
#
for user_id in users_selected: # for user_id in users_selected:
users.extend(User.objects.filter(id=user_id)) # users.extend(User.objects.filter(id=user_id))
#
user_group = UserGroup.objects.filter(id=group_id) # user_group = UserGroup.objects.filter(id=group_id)
if user_group: # if user_group:
user_group.update(name=group_name, comment=comment, dept=dept) # user_group.update(name=group_name, comment=comment, dept=dept)
user_group = user_group[0] # user_group = user_group[0]
user_group.user_set.clear() # user_group.user_set.clear()
user_group.user_set = users # user_group.user_set = users
#
except ServerError, e: # except ServerError, e:
error = e # error = e
#
return HttpResponseRedirect('/juser/group_list/') # return HttpResponseRedirect('/juser/group_list/')
@require_role(role='super') @require_role(role='super')
@ -224,46 +224,39 @@ def user_add(request):
error = '' error = ''
msg = '' msg = ''
header_title, path1, path2 = '添加用户', '用户管理', '添加用户' header_title, path1, path2 = '添加用户', '用户管理', '添加用户'
user_role = {'SU': u'超级管理员', 'DA': u'部门管理员', 'CU': u'普通用户'} user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
dept_all = DEPT.objects.all()
group_all = UserGroup.objects.all() group_all = UserGroup.objects.all()
if request.method == 'POST': if request.method == 'POST':
username = request.POST.get('username', '') username = request.POST.get('username', '')
password = PyCrypt.gen_rand_pwd(16) password = PyCrypt.random_pass(16)
name = request.POST.get('name', '') name = request.POST.get('name', '')
email = request.POST.get('email', '') email = request.POST.get('email', '')
dept_id = request.POST.get('dept_id') dept_id = request.POST.get('dept_id')
groups = request.POST.getlist('groups', []) groups = request.POST.getlist('groups', [])
role_post = request.POST.get('role', 'CU') admin_groups = request.POST.getlist('admin_groups', [])
ssh_key_pwd = PyCrypt.gen_rand_pwd(16) role = request.POST.get('role', 'CU')
ssh_key_pwd = PyCrypt.random_pass(16)
is_active = True if request.POST.get('is_active', '1') == '1' else False is_active = True if request.POST.get('is_active', '1') == '1' else False
ldap_pwd = PyCrypt.gen_rand_pwd(16) ldap_pwd = PyCrypt.random_pass(32, especial=True)
try: try:
if '' in [username, password, ssh_key_pwd, name, groups, role_post, is_active]: if '' in [username, password, ssh_key_pwd, name, groups, role, is_active]:
error = u'带*内容不能为空' error = u'带*内容不能为空'
raise ServerError raise ServerError
user = User.objects.filter(username=username) user_test = get_object(User, username=username)
if user: if user_test:
error = u'用户 %s 已存在' % username error = u'用户 %s 已存在' % username
raise ServerError raise ServerError
dept = DEPT.objects.filter(id=dept_id)
if dept:
dept = dept[0]
else:
error = u'部门不存在'
raise ServerError(error)
except ServerError: except ServerError:
pass pass
else: else:
try: try:
user = db_add_user(username=username, user = db_add_user(username=username,
password=CRYPTOR.md5_crypt(password), password=CRYPTOR.md5_crypt(password),
name=name, email=email, dept=dept, name=name, email=email, role=role,
groups=groups, role=role_post, groups=groups, admin_groups=admin_groups,
ssh_key_pwd=CRYPTOR.md5_crypt(ssh_key_pwd), ssh_key_pwd=CRYPTOR.md5_crypt(ssh_key_pwd),
ldap_pwd=CRYPTOR.encrypt(ldap_pwd), ldap_pwd=CRYPTOR.encrypt(ldap_pwd),
is_active=is_active, is_active=is_active,
@ -272,18 +265,6 @@ def user_add(request):
server_add_user(username, password, ssh_key_pwd) server_add_user(username, password, ssh_key_pwd)
if LDAP_ENABLE: if LDAP_ENABLE:
ldap_add_user(username, ldap_pwd) ldap_add_user(username, ldap_pwd)
mail_title = u'恭喜你的跳板机用户添加成功 Jumpserver'
mail_msg = """
Hi, %s
您的用户名 %s
您的部门: %s
您的角色 %s
您的web登录密码 %s
您的ssh密钥文件密码 %s
密钥下载地址 http://%s:%s/juser/down_key/?id=%s
说明 请登陆后再下载密钥
""" % (name, username, dept.name, user_role.get(role_post, ''),
password, ssh_key_pwd, SEND_IP, SEND_PORT, user.id)
except Exception, e: except Exception, e:
error = u'添加用户 %s 失败 %s ' % (username, e) error = u'添加用户 %s 失败 %s ' % (username, e)
@ -295,8 +276,9 @@ def user_add(request):
except Exception: except Exception:
pass pass
else: else:
send_mail(mail_title, mail_msg, MAIL_FROM, [email], fail_silently=False) if MAIL_ENABLE:
msg = u'添加用户 %s 成功! 用户密码已发送到 %s 邮箱!' % (username, email) user_add_mail(user, kwargs=locals())
msg = u'添加用户 %s 成功! 用户密码已发送到 %s 邮箱!' % (username, email)
return render_to_response('juser/user_add.html', locals(), context_instance=RequestContext(request)) return render_to_response('juser/user_add.html', locals(), context_instance=RequestContext(request))

View File

@ -17,12 +17,6 @@
<a class="dropdown-toggle" data-toggle="dropdown" href="#"> <a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i> <i class="fa fa-wrench"></i>
</a> </a>
<ul class="dropdown-menu dropdown-user">
<li><a href="#">未启用 1</a>
</li>
<li><a href="#">未启用 2</a>
</li>
</ul>
<a class="close-link"> <a class="close-link">
<i class="fa fa-times"></i> <i class="fa fa-times"></i>
</a> </a>
@ -42,26 +36,6 @@
<input id="username" name="username" placeholder="Username" type="text" class="form-control" {% if error %}value="{{ username }}" {% endif %}> <input id="username" name="username" placeholder="Username" type="text" class="form-control" {% if error %}value="{{ username }}" {% endif %}>
</div> </div>
</div> </div>
{# <div class="hr-line-dashed"></div>#}
{# <div class="form-group">#}
{# <label for="password" class="col-sm-2 control-label">密码<span class="red-fonts">*</span></label>#}
{# <div class="col-sm-8">#}
{# <input id="password" name="password" placeholder="Password" type="password" class="form-control" {% if error %}value="{{ password }}" {% endif %}>#}
{# <span class="help-block m-b-none">#}
{# 登陆web的密码#}
{# </span>#}
{# </div>#}
{# </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>#}
{# <div class="col-sm-8">#}
{# <input id="ssh_key_pwd" name="ssh_key_pwd" placeholder="SSH Key Password" type="password" class="form-control" {% if error %}value="{{ ssh_key_pwd }}" {% endif %}>#}
{# <span class="help-block m-b-none">#}
{# 登陆 Jumpserver 使用的SSH密钥的密码#}
{# </span>#}
{# </div>#}
{# </div>#}
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
<div class="form-group"> <div class="form-group">
<label for="name" class="col-sm-2 control-label">姓名<span class="red-fonts">*</span></label> <label for="name" class="col-sm-2 control-label">姓名<span class="red-fonts">*</span></label>
@ -69,22 +43,9 @@
<input id="name" name="name" placeholder="Name" type="text" class="form-control" {% if error %}value="{{ name }}" {% endif %} > <input id="name" name="name" placeholder="Name" type="text" class="form-control" {% if error %}value="{{ name }}" {% endif %} >
</div> </div>
</div> </div>
{% ifequal session_role_id 2 %}
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
<div class="form-group"> <div class="form-group">
<label for="dept_id" class="col-lg-2 control-label">部门<span class="red-fonts">*</span></label> <label for="groups" class="col-sm-2 control-label">用户组</label>
<div class="col-sm-8">
<select id="dept_id" name="dept_id" class="form-control m-b">
{% for dept in dept_all %}
<option value="{{ dept.id }}">{{ dept.name }}</option>
{% endfor %}
</select>
</div>
</div>
{% endifequal %}
<div class="hr-line-dashed"></div>
<div class="form-group">
<label for="groups" class="col-lg-2 control-label">小组</label>
<div class="col-sm-8"> <div class="col-sm-8">
<select id="groups" name="groups" class="form-control m-b" multiple size="12"> <select id="groups" name="groups" class="form-control m-b" multiple size="12">
{% for group in group_all %} {% for group in group_all %}
@ -100,17 +61,27 @@
{% ifequal session_role_id 2 %} {% ifequal session_role_id 2 %}
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
<div class="form-group"> <div class="form-group">
<label for="role" class="col-lg-2 control-label">角色<span class="red-fonts">*</span></label> <label for="role" class="col-sm-2 control-label">角色<span class="red-fonts">*</span></label>
<div class="col-sm-8"> <div class="col-sm-8">
<select id="role" name="role" class="form-control m-b"> {% for r, role_name in user_role.items %}
{% for r, role_name in user_role.items %} <div class="col-sm-3">
{% ifequal r role_post %} <div class="radio i-checks">
<option value="{{ r }}" selected>{{ role_name }}</option> <label><input type="radio" value="{{ r }}" class="role" name="role" {% ifequal r 'CU' %}checked{% endifequal %}>{{ role_name }}</label>
{% else %} </div>
<option value="{{ r }}">{{ role_name }}</option> </div>
{% endifequal %} {% endfor %}
{% endfor %} </div>
</select> </div>
<div class="form-group" id="admin_groups" style="display: none">
<label for="role" class="col-sm-2 control-label">管理用户组<span class="red-fonts">*</span></label>
<div class="col-sm-8">
{% for user_group in group_all %}
<div class="col-sm-3">
<div class="checkbox i-checks">
<label><input type="checkbox" value="{{ user_group.id }}" name="admin_groups" > {{ user_group.name }}</label>
</div>
</div>
{% endfor %}
</div> </div>
</div> </div>
{% endifequal %} {% endifequal %}
@ -118,7 +89,7 @@
<div class="form-group"> <div class="form-group">
<label for="email" class="col-sm-2 control-label">Email<span class="red-fonts">*</span></label> <label for="email" class="col-sm-2 control-label">Email<span class="red-fonts">*</span></label>
<div class="col-sm-8"> <div class="col-sm-8">
<input id="email" name="email" type="email" placeholder="Email" class="form-control" {% if error %}value="{{ email }}" {% endif %}> <input id="email" name="email" type="email" placeholder="username@jumpserver.org" class="form-control" {% if error %}value="{{ email }}" {% endif %}>
</div> </div>
</div> </div>
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
@ -135,7 +106,7 @@
<div class="hr-line-dashed"></div> <div class="hr-line-dashed"></div>
<div class="form-group"> <div class="form-group">
<div class="col-sm-4 col-sm-offset-2"> <div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="submit">取消</button> <button class="btn btn-white" type="reset">取消</button>
<button id="submit_button" class="btn btn-primary" type="submit">确认保存</button> <button id="submit_button" class="btn btn-primary" type="submit">确认保存</button>
</div> </div>
</div> </div>
@ -145,21 +116,22 @@
</div> </div>
</div> </div>
</div> </div>
{% endblock %}
{% block self_footer_js %}
<script> <script>
$('#userForm').validator({ $('#userForm').validator({
timely: 2, timely: 2,
theme: "yellow_right_effect", theme: "yellow_right_effect",
rules: { rules: {
check_ip: [/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/, 'ip地址不正确'], check_username: [/^\w{3,20}$/, '大小写字母数字和下划线'],
check_port: [/^\d{1,5}$/, '端口号不正确'],
type_m: function(element){ type_m: function(element){
return $("#M").is(":checked"); return $("#M").is(":checked");
} }
}, },
fields: { fields: {
"username": { "username": {
rule: "required", rule: "required;check_username",
tip: "输入用户名", tip: "输入用户名",
ok: "", ok: "",
msg: {required: "必须填写!"} msg: {required: "必须填写!"}
@ -170,18 +142,6 @@ $('#userForm').validator({
ok: "", ok: "",
msg: {required: "必须填写!"} msg: {required: "必须填写!"}
}, },
"ssh_key_pwd": {
rule: "required;length[6~50]",
tip: "ssh私钥密码",
ok: "",
msg: {required: "必须填写"}
},
"dept_id": {
rule: "checked",
tip: "选择部门",
ok: "",
msg: {checked: "至少选择一个部门"}
},
"name": { "name": {
rule: "required", rule: "required",
tip: "姓名", tip: "姓名",
@ -193,12 +153,6 @@ $('#userForm').validator({
tip: "Email", tip: "Email",
ok: "", ok: "",
msg: {required: "必须填写"} msg: {required: "必须填写"}
},
"role": {
rule: "checked",
tip: "角色",
ok: "",
msg: {required: "选择一个"}
} }
}, },
valid: function(form) { valid: function(form) {
@ -206,7 +160,16 @@ $('#userForm').validator({
} }
}); });
$("document").ready(function(){
$("input.role").click(function(){
if($("input.role[value=GA]").is( ":checked" )){
$("#admin_groups").css("display", 'block');
}
else {
$("#admin_groups").css("display", 'none');
}
})
})
</script> </script>
{% endblock %} {% endblock %}