jumpserver/juser/views.py

502 lines
16 KiB
Python
Raw Normal View History

2015-01-05 15:55:05 +00:00
# coding: utf-8
2015-01-10 07:24:16 +00:00
# Author: Guanghongwei
# Email: ibuler@qq.com
import time
2015-01-12 15:52:41 +00:00
import os
2015-01-10 07:54:09 +00:00
import random
2015-01-12 15:52:41 +00:00
import subprocess
from Crypto.PublicKey import RSA
import crypt
2015-01-22 15:57:18 +00:00
from django.http import HttpResponseRedirect
2015-01-05 15:55:05 +00:00
2015-01-03 12:42:20 +00:00
from django.shortcuts import render_to_response
2015-01-13 14:14:50 +00:00
from django.core.exceptions import ObjectDoesNotExist
2015-01-28 07:08:16 +00:00
from django.db.models import Q
2015-01-30 03:18:30 +00:00
from django.http import HttpResponse
2015-02-01 15:03:28 +00:00
from django.core.paginator import Paginator, EmptyPage, InvalidPage
2015-01-03 12:42:20 +00:00
2015-01-10 05:50:59 +00:00
from juser.models import UserGroup, User
2015-01-10 07:54:09 +00:00
from connect import PyCrypt, KEY
2015-01-12 15:52:41 +00:00
from connect import BASE_DIR
from connect import CONF
2015-02-06 10:39:20 +00:00
from jumpserver.views import md5_crypt,LDAPMgmt
2015-02-01 15:03:28 +00:00
2015-01-10 07:54:09 +00:00
2015-01-13 14:14:50 +00:00
CRYPTOR = PyCrypt(KEY)
2015-01-13 14:57:27 +00:00
LDAP_ENABLE = CONF.getint('ldap', 'ldap_enable')
2015-01-13 14:14:50 +00:00
if LDAP_ENABLE:
LDAP_HOST_URL = CONF.get('ldap', 'host_url')
LDAP_BASE_DN = CONF.get('ldap', 'base_dn')
LDAP_ROOT_DN = CONF.get('ldap', 'root_dn')
LDAP_ROOT_PW = CONF.get('ldap', 'root_pw')
2015-01-10 07:54:09 +00:00
2015-01-12 15:52:41 +00:00
def gen_rand_pwd(num):
2015-01-10 07:54:09 +00:00
"""生成随机密码"""
seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
salt_list = []
for i in range(num):
salt_list.append(random.choice(seed))
salt = ''.join(salt_list)
return salt
2015-01-07 15:56:36 +00:00
2015-01-12 15:52:41 +00:00
def bash(cmd):
"""执行bash命令"""
return subprocess.call(cmd, shell=True)
def is_dir(dir_name, mode=0755):
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
os.chmod(dir_name, mode)
2015-01-07 15:56:36 +00:00
class AddError(Exception):
pass
2015-01-03 12:42:20 +00:00
2015-01-12 15:52:41 +00:00
def gen_sha512(salt, password):
return crypt.crypt(password, '$6$%s$' % salt)
2015-01-27 07:01:09 +00:00
def group_db_add(**kwargs):
group_name = kwargs.get('name')
group = UserGroup.objects.filter(name=group_name)
if group:
2015-01-28 07:08:16 +00:00
raise AddError('Group %s have been exist .' % group_name)
2015-01-27 07:01:09 +00:00
UserGroup.objects.create(**kwargs)
2015-01-28 09:35:06 +00:00
def group_add_user(group_name, user_id=None, username=None):
2015-01-28 07:08:16 +00:00
try:
2015-01-28 09:35:06 +00:00
if user_id:
user = User.objects.get(id=user_id)
else:
user = User.objects.get(username=username)
2015-01-28 07:08:16 +00:00
except ObjectDoesNotExist:
2015-01-28 09:35:06 +00:00
raise AddError('用户获取失败')
2015-01-28 07:08:16 +00:00
else:
2015-01-28 09:35:06 +00:00
group = UserGroup.objects.get(name=group_name)
group.user_set.add(user)
2015-01-28 07:08:16 +00:00
2015-01-30 03:18:30 +00:00
def group_update_user(group_id, users_id):
group = UserGroup.objects.get(id=group_id)
group.user_set.clear()
for user_id in users_id:
user = User.objects.get(id=user_id)
group.user_set.add(user)
2015-01-28 09:35:06 +00:00
def db_add_user(**kwargs):
groups_post = kwargs.pop('groups')
user = User(**kwargs)
group_select = []
for group_id in groups_post:
group = UserGroup.objects.filter(id=group_id)
group_select.extend(group)
user.save()
user.user_group = group_select
def db_update_user(**kwargs):
groups_post = kwargs.pop('groups')
username = kwargs.get('username')
user = User.objects.filter(username=username)
user.update(**kwargs)
user = User.objects.get(username=username)
group_select = []
for group_id in groups_post:
group = UserGroup.objects.filter(id=group_id)
group_select.extend(group)
user.save()
user.user_group = group_select
def db_del_user(username):
try:
user = User.objects.get(username=username)
user.delete()
except ObjectDoesNotExist:
pass
def gen_ssh_key(username, password=None, length=2048):
private_key_dir = os.path.join(BASE_DIR, 'keys/jumpserver/')
private_key_file = os.path.join(private_key_dir, username)
public_key_dir = '/home/%s/.ssh/' % username
public_key_file = os.path.join(public_key_dir, 'authorized_keys')
is_dir(private_key_dir)
is_dir(public_key_dir, mode=0700)
key = RSA.generate(length)
with open(private_key_file, 'w') as pri_f:
pri_f.write(key.exportKey('PEM', password))
os.chmod(private_key_file, 0600)
pub_key = key.publickey()
with open(public_key_file, 'w') as pub_f:
pub_f.write(pub_key.exportKey('OpenSSH'))
os.chmod(public_key_file, 0600)
bash('chown %s:%s %s' % (username, username, public_key_file))
def server_add_user(username, password, ssh_key_pwd):
bash('useradd %s; echo %s | passwd --stdin %s' % (username, password, username))
gen_ssh_key(username, ssh_key_pwd)
def server_del_user(username):
bash('userdel -r %s' % username)
def ldap_add_user(username, ldap_pwd):
user_dn = "uid=%s,ou=People,%s" % (username, LDAP_BASE_DN)
password_sha512 = gen_sha512(gen_rand_pwd(6), ldap_pwd)
user = User.objects.get(username=username)
user_attr = {'uid': [str(username)],
'cn': [str(username)],
'objectClass': ['account', 'posixAccount', 'top', 'shadowAccount'],
'userPassword': ['{crypt}%s' % password_sha512],
'shadowLastChange': ['16328'],
'shadowMin': ['0'],
'shadowMax': ['99999'],
'shadowWarning': ['7'],
'loginShell': ['/bin/bash'],
'uidNumber': [str(user.id)],
'gidNumber': [str(user.id)],
'homeDirectory': [str('/home/%s' % username)]}
group_dn = "cn=%s,ou=Group,%s" % (username, LDAP_BASE_DN)
group_attr = {'objectClass': ['posixGroup', 'top'],
'cn': [str(username)],
'userPassword': ['{crypt}x'],
'gidNumber': [str(user.id)]}
sudo_dn = 'cn=%s,ou=Sudoers,%s' % (username, LDAP_BASE_DN)
sudo_attr = {'objectClass': ['top', 'sudoRole'],
'cn': ['%s' % str(username)],
'sudoCommand': ['/bin/pwd'],
'sudoHost': ['192.168.1.1'],
'sudoOption': ['!authenticate'],
'sudoRunAsUser': ['root'],
'sudoUser': ['%s' % str(username)]}
ldap_conn = LDAPMgmt(LDAP_HOST_URL, LDAP_BASE_DN, LDAP_ROOT_DN, LDAP_ROOT_PW)
ldap_conn.add(user_dn, user_attr)
ldap_conn.add(group_dn, group_attr)
ldap_conn.add(sudo_dn, sudo_attr)
def ldap_del_user(username):
user_dn = "uid=%s,ou=People,%s" % (username, LDAP_BASE_DN)
group_dn = "cn=%s,ou=Group,%s" % (username, LDAP_BASE_DN)
sudo_dn = 'cn=%s,ou=Sudoers,%s' % (username, LDAP_BASE_DN)
ldap_conn = LDAPMgmt(LDAP_HOST_URL, LDAP_BASE_DN, LDAP_ROOT_DN, LDAP_ROOT_PW)
ldap_conn.delete(user_dn)
ldap_conn.delete(group_dn)
ldap_conn.delete(sudo_dn)
2015-01-27 09:24:33 +00:00
2015-02-01 15:03:28 +00:00
def group_add(request, group_type_select='A'):
2015-01-07 15:56:36 +00:00
error = ''
msg = ''
2015-01-10 08:24:44 +00:00
header_title, path1, path2 = '添加属组 | Add Group', 'juser', 'group_add'
2015-01-28 07:08:16 +00:00
group_types = {
2015-02-01 15:03:28 +00:00
'M': '部门',
'A': '用户组',
2015-01-28 07:08:16 +00:00
}
2015-02-01 15:03:28 +00:00
users_all = User.objects.all()
if group_type_select == 'M':
users = [user for user in users_all if not user.user_group.filter(type='M')]
else:
users = users_all
2015-01-07 15:56:36 +00:00
if request.method == 'POST':
2015-01-28 07:08:16 +00:00
group_name = request.POST.get('group_name', '')
group_type = request.POST.get('group_type', 'A')
users_selected = request.POST.getlist('users_selected', '')
comment = request.POST.get('comment', '')
2015-01-07 15:56:36 +00:00
try:
if not group_name:
error = u'组名不能为空'
raise AddError
2015-01-28 07:08:16 +00:00
group_db_add(name=group_name, comment=comment, type=group_type)
for user_id in users_selected:
2015-01-28 09:35:06 +00:00
group_add_user(group_name, user_id=user_id)
2015-01-28 07:08:16 +00:00
2015-01-07 15:56:36 +00:00
except AddError:
pass
except TypeError:
2015-01-28 07:08:16 +00:00
error = u'保存用户组失败'
2015-01-07 15:56:36 +00:00
else:
2015-01-07 16:07:00 +00:00
msg = u'添加组 %s 成功' % group_name
2015-01-07 15:56:36 +00:00
2015-01-12 15:52:41 +00:00
return render_to_response('juser/group_add.html', locals())
2015-01-07 15:20:48 +00:00
2015-02-01 15:03:28 +00:00
def group_add_ajax(request):
group_type = request.POST.get('type', 'A')
users_all = User.objects.all()
if group_type == 'A':
users = users_all
else:
users = [user for user in users_all if not user.user_group.filter(type='M')]
return render_to_response('juser/group_add_ajax.html', locals())
2015-01-09 14:10:38 +00:00
def group_list(request):
2015-01-24 04:54:25 +00:00
header_title, path1, path2 = '查看属组 | Show Group', 'juser', 'group_list'
2015-02-01 15:03:28 +00:00
groups = contact_list = UserGroup.objects.filter(Q(type='M') | Q(type='A')).order_by('type')
2015-01-24 04:54:25 +00:00
p = paginator = Paginator(contact_list, 10)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
2015-01-12 15:52:41 +00:00
return render_to_response('juser/group_list.html', locals())
2015-01-09 14:10:38 +00:00
2015-01-24 05:20:52 +00:00
def group_detail(request):
group_id = request.GET.get('id', None)
if not group_id:
return HttpResponseRedirect('/')
group = UserGroup.objects.get(id=group_id)
2015-01-28 09:35:06 +00:00
users = group.user_set.all()
2015-01-24 05:20:52 +00:00
return render_to_response('juser/group_detail.html', locals())
def group_del(request):
group_id = request.GET.get('id', None)
if not group_id:
return HttpResponseRedirect('/')
group = UserGroup.objects.get(id=group_id)
group.delete()
return HttpResponseRedirect('/juser/group_list/', locals())
def group_edit(request):
error = ''
msg = ''
header_title, path1, path2 = '修改属组 | Edit Group', 'juser', 'group_edit'
2015-01-30 03:18:30 +00:00
group_types = {
2015-02-01 15:03:28 +00:00
'M': '部门',
'A': '用户组',
2015-01-30 03:18:30 +00:00
}
2015-01-24 05:20:52 +00:00
if request.method == 'GET':
group_id = request.GET.get('id', None)
group = UserGroup.objects.get(id=group_id)
group_name = group.name
comment = group.comment
2015-01-30 03:18:30 +00:00
group_type = group.type
users_all = User.objects.all()
users_selected = group.user_set.all()
users = [user for user in users_all if user not in users_selected]
2015-01-24 05:20:52 +00:00
2015-02-01 15:03:28 +00:00
return render_to_response('juser/group_edit.html', locals())
2015-01-24 05:20:52 +00:00
else:
2015-01-24 05:42:56 +00:00
group_id = request.POST.get('group_id', None)
2015-01-24 05:34:36 +00:00
group_name = request.POST.get('group_name', None)
comment = request.POST.get('comment', '')
2015-01-30 03:18:30 +00:00
users_selected = request.POST.getlist('users_selected')
group_type = request.POST.get('group_type')
2015-01-24 05:34:36 +00:00
group = UserGroup.objects.filter(id=group_id)
2015-01-30 03:18:30 +00:00
group.update(name=group_name, comment=comment, type=group_type)
group_update_user(group_id, users_selected)
2015-01-24 05:34:36 +00:00
return HttpResponseRedirect('/juser/group_list/')
2015-01-24 05:20:52 +00:00
2015-01-09 14:10:38 +00:00
def user_list(request):
2015-01-14 15:51:30 +00:00
user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
2015-01-22 14:26:13 +00:00
header_title, path1, path2 = '查看用户 | Show User', 'juser', 'user_list'
users = contact_list = User.objects.all().order_by('id')
p = paginator = Paginator(contact_list, 10)
2015-01-22 14:12:41 +00:00
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
contacts = paginator.page(page)
except (EmptyPage, InvalidPage):
contacts = paginator.page(paginator.num_pages)
2015-01-22 14:14:21 +00:00
return render_to_response('juser/user_list.html', locals())
2015-01-09 14:10:38 +00:00
2015-01-22 15:57:18 +00:00
def user_detail(request):
2015-01-24 05:49:52 +00:00
user_id = request.GET.get('id', None)
if not user_id:
2015-01-22 15:57:18 +00:00
return HttpResponseRedirect('/')
2015-01-24 05:49:52 +00:00
user = User.objects.get(id=user_id)
2015-01-22 16:00:29 +00:00
return render_to_response('juser/user_detail.html', locals())
2015-01-22 15:57:18 +00:00
2015-01-22 16:07:44 +00:00
def user_del(request):
2015-01-24 05:49:52 +00:00
user_id = request.GET.get('id', None)
if not user_id:
2015-01-22 16:07:44 +00:00
return HttpResponseRedirect('/')
2015-01-24 05:49:52 +00:00
user = User.objects.get(id=user_id)
2015-01-22 16:07:44 +00:00
user.delete()
2015-01-27 09:30:20 +00:00
group = UserGroup.objects.get(name=user.username)
group.delete()
2015-01-28 10:00:09 +00:00
server_del_user(user.username)
ldap_del_user(user.username)
2015-01-22 16:07:44 +00:00
return HttpResponseRedirect('/juser/user_list/', locals())
2015-01-22 16:41:17 +00:00
def user_edit(request):
2015-01-23 14:44:29 +00:00
header_title, path1, path2 = '编辑用户 | Edit User', 'juser', 'user_edit'
2015-01-24 05:20:52 +00:00
readonly = "readonly"
2015-01-22 16:41:17 +00:00
if request.method == 'GET':
2015-01-24 05:34:36 +00:00
user_id = request.GET.get('id', None)
if not user_id:
2015-01-22 16:41:17 +00:00
return HttpResponseRedirect('/')
2015-01-24 05:34:36 +00:00
user = User.objects.get(id=user_id)
2015-01-22 16:41:17 +00:00
username = user.username
password = user.password
2015-01-28 03:17:29 +00:00
ssh_key_pwd = user.ssh_key_pwd
2015-01-22 16:41:17 +00:00
name = user.name
2015-02-01 15:03:28 +00:00
manage_groups = UserGroup.objects.filter(type='M')
auth_groups = UserGroup.objects.filter(type='A')
manage_group_id = user.user_group.get(type='M').id
groups_str = ' '.join([str(group.id) for group in auth_groups])
2015-01-22 16:41:17 +00:00
user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
role_post = user.role
ssh_pwd = user.ssh_pwd
email = user.email
2015-01-23 14:44:29 +00:00
else:
username = request.POST.get('username', None)
password = request.POST.get('password', None)
name = request.POST.get('name', None)
email = request.POST.get('email', '')
2015-02-01 15:03:28 +00:00
manage_group_id = request.POST.get('manage_group', '')
auth_groups = request.POST.getlist('groups', None)
groups = auth_groups
groups.append(manage_group_id)
groups_str = ' '.join(auth_groups)
2015-01-23 14:44:29 +00:00
role_post = request.POST.get('role', None)
ssh_pwd = request.POST.get('ssh_pwd', None)
2015-01-28 03:17:29 +00:00
ssh_key_pwd = request.POST.get('ssh_key_pwd', None)
2015-01-23 14:44:29 +00:00
is_active = request.POST.get('is_active', '1')
ldap_pwd = gen_rand_pwd(16)
2015-01-28 09:35:06 +00:00
all_group = UserGroup.objects.filter(Q(type='M') | Q(type='A'))
2015-01-23 15:45:55 +00:00
user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
2015-01-23 14:44:29 +00:00
if username:
2015-01-23 15:40:37 +00:00
user = User.objects.get(username=username)
2015-01-23 14:44:29 +00:00
else:
return HttpResponseRedirect('/')
if password != user.password:
password = md5_crypt(password)
if ssh_pwd != user.ssh_pwd:
ssh_pwd = CRYPTOR.encrypt(ssh_pwd)
2015-01-28 03:17:29 +00:00
if ssh_key_pwd != user.ssh_key_pwd:
ssh_key_pwd = CRYPTOR.encrypt(ssh_key_pwd)
2015-01-23 14:44:29 +00:00
db_update_user(username=username,
password=password,
name=name,
email=email,
groups=groups,
role=role_post,
ssh_pwd=ssh_pwd,
2015-01-28 03:17:29 +00:00
ssh_key_pwd=ssh_key_pwd)
2015-01-23 14:44:29 +00:00
msg = u'修改用户成功'
2015-01-23 16:20:29 +00:00
return HttpResponseRedirect('/juser/user_list/')
2015-01-23 14:44:29 +00:00
return render_to_response('juser/user_add.html', locals())
2015-01-22 16:41:17 +00:00
2015-01-05 13:20:09 +00:00
def user_add(request):
2015-01-10 05:10:44 +00:00
error = ''
msg = ''
2015-01-10 08:24:44 +00:00
header_title, path1, path2 = '添加用户 | Add User', 'juser', 'user_add'
2015-01-10 06:52:35 +00:00
user_role = {'SU': u'超级管理员', 'GA': u'组管理员', 'CU': u'普通用户'}
2015-02-01 15:03:28 +00:00
manage_groups = UserGroup.objects.filter(type='M')
auth_groups = UserGroup.objects.filter(type='A')
2015-01-10 05:10:44 +00:00
if request.method == 'POST':
2015-01-10 07:15:49 +00:00
username = request.POST.get('username', None)
2015-01-28 09:35:06 +00:00
password = request.POST.get('password', '')
2015-01-10 07:15:49 +00:00
name = request.POST.get('name', None)
email = request.POST.get('email', '')
2015-02-01 15:03:28 +00:00
manage_group_id = request.POST.get('manage_group')
auth_groups = request.POST.getlist('groups', None)
groups = auth_groups
groups.append(manage_group_id)
groups_str = ' '.join(auth_groups)
2015-01-28 09:35:06 +00:00
role_post = request.POST.get('role', 'CU')
ssh_pwd = request.POST.get('ssh_pwd', '')
ssh_key_pwd = request.POST.get('ssh_key_pwd', '')
2015-01-10 07:15:49 +00:00
is_active = request.POST.get('is_active', '1')
2015-01-12 15:52:41 +00:00
ldap_pwd = gen_rand_pwd(16)
2015-01-10 05:10:44 +00:00
2015-01-10 06:52:35 +00:00
try:
2015-01-28 03:17:29 +00:00
if None in [username, password, ssh_key_pwd, name, groups, role_post, is_active]:
2015-01-10 06:52:35 +00:00
error = u'带*内容不能为空'
raise AddError
user = User.objects.filter(username=username)
if user:
error = u'用户 %s 已存在' % username
raise AddError
except AddError:
pass
else:
2015-01-10 07:24:16 +00:00
time_now = time.time()
2015-01-13 14:14:50 +00:00
try:
db_add_user(username=username,
password=md5_crypt(password),
name=name, email=email,
groups=groups, role=role_post,
2015-01-28 09:35:06 +00:00
ssh_pwd=CRYPTOR.encrypt(ssh_pwd) if ssh_pwd else '',
2015-01-28 03:17:29 +00:00
ssh_key_pwd=CRYPTOR.encrypt(ssh_key_pwd),
2015-01-13 14:14:50 +00:00
ldap_pwd=CRYPTOR.encrypt(ldap_pwd),
is_active=is_active,
date_joined=time_now)
2015-01-28 03:17:29 +00:00
server_add_user(username, password, ssh_key_pwd)
2015-01-28 07:08:16 +00:00
group_db_add(name=username, comment=username, type='P')
2015-01-28 09:35:06 +00:00
group_add_user(group_name=username, username=username)
2015-01-13 14:14:50 +00:00
if LDAP_ENABLE:
ldap_add_user(username, ldap_pwd)
2015-01-13 14:44:58 +00:00
msg = u'添加用户 %s 成功!' % username
2015-01-13 14:14:50 +00:00
except Exception, e:
2015-01-13 14:44:58 +00:00
error = u'添加用户 %s 失败 %s ' % (username, e)
try:
db_del_user(username)
server_del_user(username)
if LDAP_ENABLE:
ldap_del_user(username)
except Exception:
pass
2015-01-13 14:14:50 +00:00
2015-01-12 15:52:41 +00:00
return render_to_response('juser/user_add.html', locals())
2015-01-07 15:20:48 +00:00
2015-01-03 12:42:20 +00:00
2014-12-22 09:18:51 +00:00
2015-01-10 04:30:21 +00:00