域账号密码自助-后台逻辑

密码修改|重置核心类
# coding:utf8
import pythoncom
import win32com.client


class NTUser(object):
# Uses ADSI to change password under user privileges
def __init__(self, username):
# 初始化
pythoncom.CoInitialize()
self.adsiNS = win32com.client.Dispatch('ADsNameSpaces')
Userpath = "WinNT://10.105.42.13/" + username + ",user"
self.adsNTUser = self.adsiNS.GetObject("", Userpath)


def modify(self, old_password, new_password):
self.adsNTUser.ChangePassword(old_password, new_password)
# 释放资源
pythoncom.CoUninitialize()

def reset(self, new_password):
self.adsNTUser.SetPassword(new_password)
# 释放资源
pythoncom.CoUninitialize()
密码修改
class PwdModifyView(View):
def get(self,request):
current_year = datetime.now().year
return render(request, "pwd-modify.html", {
'current_year':current_year
})

def post(self,request):
current_year = datetime.now().year
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
pwd_modify_form = PwdModifyForm(request.POST)
if pwd_modify_form.is_valid():
username = request.POST.get("username", "")
pwd_old = request.POST.get("pwd_old", "")
pwd_new1 = request.POST.get("pwd_new1", "")
pwd_new2 = request.POST.get("pwd_new2", "")
# try:
# user_profile = UserProfile.objects.get(username=username)
# except Exception as e:
# print e
# user_profile = UserProfile()
if pwd_new1 != pwd_new2:
return render(request, 'pwd-modify.html',{
'pwd_new_errors':True,
"msg": "2次密码输入不一致!",
'current_year': current_year,
'pwd_modify_form':pwd_modify_form
})
try:
nt = NTUser(username=username)
nt.modify(pwd_old, pwd_new1)
user_profile, created = UserProfile.objects.get_or_create(username=username)
user_profile.password = make_password(pwd_new1)
user_profile.save()
data = {
'username': username,
'email': '{0}@genewiz.com.cn'.format(username),
'ip': ip,
'current_year': current_year
}
if SendMail(data, send_type='user_modify_pwd'):
UserActionLog.objects.create(
status=True,
user_type='user_modify_pwd',
client_ip=ip,
username=username,
comment='密码修改成功'
)
return render(request, 'pwd-modify-success.html', {
'pwd_modify_form':pwd_modify_form,
'ip': ip,
'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"msg": "成功",
'current_year': current_year
})
except pythoncom.com_error, (hr, msg, exc, arg):
stderr = exc[2]
# cmd = 'Set-ADAccountPassword -Identity {0} -OldPassword (ConvertTo-SecureString -AsPlainText "{1}" -Force) -NewPassword (ConvertTo-SecureString -AsPlainText "{2}" -Force)'.format(username, pwd_old, pwd_new1)
# p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
# stdout, stderr = p.communicate()
# 释放资源
pythoncom.CoUninitialize()
if stderr:
if 'found' in stderr:
UserActionLog.objects.create(
status=False,
user_type='user_modify_pwd',
client_ip=ip,
username=username,
comment='帐号不存在,请重新输入!'
)
return render(request, "pwd-modify.html", {
'username_errors':True,
'pwd_modify_form': pwd_modify_form,
'msg': '帐号不存在,请重新输入!',
'current_year': current_year
})
elif 'correct' in stderr:
UserActionLog.objects.create(
status=False,
user_type='user_modify_pwd',
client_ip=ip,
username=username,
comment='旧密码有误,请重新输入!(输错5次,帐号将被锁定!)'
)
return render(request, "pwd-modify.html", {
'pwd_old_errors': True,
'pwd_modify_form': pwd_modify_form,
'msg': '旧密码有误!',
'current_year': current_year
})
elif 'meet' in stderr:
UserActionLog.objects.create(
status = False,
user_type='user_modify_pwd',
client_ip = ip,
username = username,
comment = '新密码不满足|复杂性|历史性|要求!'
)
return render(request, "pwd-modify.html", {
'pwd_new_errors': True,
"msg": "新密码不满足|复杂性|历史性|要求!",
'pwd_modify_form':pwd_modify_form,
'current_year': current_year
})
elif 'denied' in stderr:
cmd = 'powershell -command Get-ADUser -Identity %s -Properties lockedout' % username
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
data_list = stdout.strip().split('\r\n')
while '' in data_list:
data_list.remove('')
data = {}
for i in data_list:
temp_list = [i.strip() for i in i.split(':')]
if len(temp_list) == 2:
k, v = temp_list
else:
k = temp_list[0]
v = ":".join(temp_list[1:])
data[k] = v
if data['LockedOut'] == 'True':
UserActionLog.objects.create(
status=False,
user_type='user_modify_pwd',
client_ip=ip,
username=username,
comment='帐号已被锁定!'
)
return render(request, "pwd-modify.html", {
'username_lock_errors': True,
'pwd_modify_form':pwd_modify_form,
'msg': '帐号已被锁定!',
'current_year': current_year
})
else:
UserActionLog.objects.create(
status=False,
user_type='user_modify_pwd',
client_ip=ip,
username=username,
comment='访问被拒绝,请稍后重试!'
)
return render(request, "pwd-modify.html", {
'username_lock_errors': True,
'pwd_modify_form':pwd_modify_form,
'msg': '访问被拒绝,请稍后重试!',
'current_year': current_year
})
else:
UserActionLog.objects.create(
status=False,
user_type='user_modify_pwd',
client_ip=ip,
username=username,
comment=stderr[:100]
)
return render(request, "pwd-modify.html", {
'pwd_new_errors': True,
"msg": "发生未知错误,请联系管理员!",
'pwd_modify_form':pwd_modify_form,
'current_year': current_year
})
# else:
# user_profile, created = UserProfile.objects.get_or_create(username=username)
# user_profile.password = make_password(pwd_new1)
# user_profile.save()
# data = {
# 'username': username,
# 'email': '{0}@genewiz.com.cn'.format(username),
# 'ip': ip,
# 'current_year': current_year
# }
# if SendMail(data, send_type='user_modify_pwd'):
# UserActionLog.objects.create(
# status=True,
# user_type='user_modify_pwd',
# client_ip=ip,
# username=username,
# comment='密码修改成功'
# )
# return render(request, 'pwd-modify-success.html', {
# 'pwd_modify_form':pwd_modify_form,
# 'ip': ip,
# 'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
# "msg": "成功",
# 'current_year': current_year
# })
else:
return render(request, "pwd-modify.html", {
'current_year': current_year,
'pwd_modify_form':pwd_modify_form
           })
密码重置
class PwdResetView(View):
def get(self,request):
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
current_year = datetime.now().year
username = request.GET.get("username", "")
if username:
cmd = 'powershell -command Get-ADUser -Identity {0}'.format(username)
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stderr:
if 'find' in stderr:
UserActionLog.objects.create(
status = False,
user_type = 'user_reset_pwd',
client_ip = ip,
username = username,
comment = '帐号不存在,请重新输入!'
)
return render(request, "pwd-reset.html", {
'username_errors':True,
'msg': '帐号不存在,请重新输入!',
'username':username,
'current_year': current_year
})
else:
user_profile, created = UserProfile.objects.get_or_create(username=username)
if not user_profile.rescue_email:
return render(request, 'pwd-reset2.html', {
'success': True,
'user_profile': user_profile,
'current_year': current_year
})
else:
return render(request, 'pwd-reset3.html', {
'success': True,
'user_profile': user_profile,
'current_year': current_year
})
else:
return render(request, "pwd-reset.html", {
'current_year': current_year,
})

def post(self,request):
current_year = datetime.now().year
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
pwd_reset_form = PwdResetForm(request.POST)
if pwd_reset_form.is_valid():
username = request.POST.get("username", "")
email = request.POST.get("email", "")
reset_code = request.POST.get("reset_code", "")
pwd_new1 = request.POST.get("pwd_new1", "")
pwd_new2 = request.POST.get("pwd_new2", "")
user_profile = UserProfile.objects.get(username=username)
if pwd_new1 != pwd_new2:
UserActionLog.objects.create(
status=False,
user_type='user_reset_pwd',
client_ip=ip,
username=username,
comment='2次密码输入不一致!'
)
return render(request,'pwd-reset3.html',{
'pwd_new_errors': True,
"msg": "2次密码输入不一致!",
'current_year': current_year,
'pwd_reset_form': pwd_reset_form,
'user_profile':user_profile
})
try:
email_verify_record = EmailVerifyRecord.objects.get(code=reset_code,email=email, send_type='user_reset_pwd_code',user=user_profile, is_used=False)
except Exception as e:
UserActionLog.objects.create(
status=False,
user_type='user_reset_pwd',
client_ip=ip,
username=username,
comment='重置码有误或已使用过!'
)
return render(request, "pwd-reset3.html", {
'pwd_reset_code_errors': True,
"msg": "重置码有误或已使用过!",
'pwd_reset_form':pwd_reset_form,
'user_profile': user_profile,
'current_year': current_year
})
if email_verify_record:
try:
nt = NTUser(username=username)
nt.reset(pwd_new1)
data = {
'username': username,
'email': '{0}@genewiz.com.cn'.format(username),
'ip': ip,
'pwd_new1': pwd_new1,
'current_year': current_year
}
if SendMail(data, send_type='user_reset_pwd'):
email_verify_record.is_used = True
email_verify_record.save()
UserActionLog.objects.create(
status=True,
user_type='user_reset_pwd',
client_ip=ip,
username=username,
comment='密码重置成功'
)
return render(request, 'pwd-reset-success.html', {
'success': True,
'user_profile': user_profile,
'pwd_reset_form': pwd_reset_form,
'ip': ip,
'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
"msg": "成功",
'current_year': current_year
})
# cmd = 'Set-ADAccountPassword -identity "{0}" -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "{1}" -Force)'.format(username, pwd_new1)
# x = PxPowerShell()
# x.start_process()
# result = x.run(cmd)
# x.stop_process()
# p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
# stdout, stderr = p.communicate()
except pythoncom.com_error, (hr, msg, exc, arg):
stderr = exc[2]
# 释放资源
pythoncom.CoUninitialize()
if stderr:
if 'meet' in stderr:
UserActionLog.objects.create(
status=False,
user_type='user_reset_pwd',
client_ip=ip,
username=username,
comment='新密码不满足|复杂性|历史性|要求!'
)
return render(request, "pwd-reset3.html",{
'pwd_new_errors': True,
"msg": "新密码不满足|复杂性|历史性|要求!",
'user_profile': user_profile,
'current_year': current_year,
'pwd_reset_form':pwd_reset_form
})
else:
UserActionLog.objects.create(
status=False,
user_type='user_reset_pwd',
client_ip=ip,
username=username,
comment=stderr[:100]
)
return render(request, "pwd-reset3.html",{
'pwd_new_errors': True,
"msg": "发生未知错误,请联系管理员!",
'user_profile': user_profile,
'current_year': current_year,
'pwd_reset_form':pwd_reset_form
})
else:
username = request.POST.get("username", "")
user_profile = UserProfile.objects.get(username=username)
return render(request, "pwd-reset3.html", {
'user_profile': user_profile,
'pwd_reset_form': pwd_reset_form,
'current_year': current_year
           })
密码重置码
class PwdResetCodeView(View):
def get(self, request):
username = request.GET.get('username', '')
user_profile = UserProfile.objects.get(username=username)
email = user_profile.rescue_email
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
current_year = datetime.now().year
data = {
'username': username,
'email': email,
'ip': ip,
'current_year': current_year
}
if SendMail(data, send_type='user_reset_pwd_code'):
UserActionLog.objects.create(
status=True,
user_type = 'user_reset_pwd_code',
client_ip=ip,
username=username,
comment='发送密码重置码'
)
           return HttpResponse(json.dumps({'status':'success', 'msg':'重置码发送成功,请查收!'}), content_type='application/json')
邮箱绑定
class EmailBindView(View):
def get(self, request):
current_year = datetime.now().year
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
return render(request, 'email-bind-index.html', {
'hashkey': hashkey,
'image_url': image_url,
'current_year': current_year
})

def post(self, request):
current_year = datetime.now().year
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
email_bind_form = EmailBindForm(request.POST)
if email_bind_form.is_valid():
username = request.POST.get('username', '')
pwd = request.POST.get('pwd', '')
email = request.POST.get('email', '')
cmd = 'powershell -command Get-ADUser -Identity {0}'.format(username)
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stderr:
if 'find' in stderr:
UserActionLog.objects.create(
status = False,
user_type = 'user_bind_email',
client_ip = ip,
username = username,
comment = '帐号不存在,请重新输入!'
)
return render(request, "email-bind-index.html", {
'username_errors':True,
'msg': '帐号不存在,请重新输入!',
'email_bind_form': email_bind_form,
'hashkey': hashkey,
'image_url': image_url,
'current_year': current_year
})
else:
user_profile, created = UserProfile.objects.get_or_create(username=username)
user = authenticate(username=username, password=pwd)
if user is not None:
if user_profile.rescue_email:
UserActionLog.objects.create(
status=False,
user_type='user_bind_email',
client_ip=ip,
username=username,
comment='外部邮箱已绑定,请不要重复绑定!'
)
return render(request, 'email-bind-fail.html', {
'hashkey': hashkey,
'image_url': image_url,
'current_year': current_year
})
else:
user_profile.rescue_email = email
user_profile.save()
UserActionLog.objects.create(
status=True,
user_type='user_bind_email',
client_ip=ip,
username=username,
comment='外部邮箱绑定成功!'
)
return render(request, 'email-bind-success.html', {
'user_profile': user_profile,
'email_bind_form': email_bind_form,
'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
'ip': ip
})
else:
return render(request, 'email-bind-index.html', {
'pwd_errors':True,
'msg': '密码错误!',
'hashkey': hashkey,
'image_url': image_url,
'email_bind_form': email_bind_form,
'current_year': current_year
})
else:
return render(request, 'email-bind-index.html', {
'hashkey': hashkey,
'image_url': image_url,
'email_bind_form':email_bind_form,
'current_year': current_year
           })
邮箱修改
class EmailModifyView(View):
def get(self, request):
current_year = datetime.now().year
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
username = request.GET.get('username', '')
if username:
cmd = 'powershell -command Get-ADUser -Identity {0}'.format(username)
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stderr:
if 'find' in stderr:
UserActionLog.objects.create(
status=False,
user_type = 'user_modify_email',
client_ip=ip,
username=username,
comment='帐号不存在,请重新输入!'
)
return render(request, "email-modify-index.html", {
'username_errors': True,
'msg': '帐号不存在,请重新输入!',
'username': username,
'current_year': current_year
})
else:
user_profile, created = UserProfile.objects.get_or_create(username=username)
if user_profile.rescue_email:
return render(request, 'email-modify-submit.html', {
'success': True,
'user_profile': user_profile,
'current_year': current_year,
})
else:
return render(request, 'email-modify-fail.html', {
'current_year': current_year
})
else:
return render(request, 'email-modify-index.html', {
'current_year': current_year
})

def post(self, request):
current_year = datetime.now().year
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
email_modify_form = EmailModifyForm(request.POST)
if email_modify_form.is_valid():
username = request.POST.get('username', '')
email = request.POST.get('email', '')
email_new = request.POST.get('email_new', '')
reset_code = request.POST.get("reset_code", "")
user_profile = UserProfile.objects.get(username=username)
try:
email_verify_record = EmailVerifyRecord.objects.get(code=reset_code,email=email, send_type='user_reset_email_code',user=user_profile, is_used=False)
except Exception as e:
UserActionLog.objects.create(
status=False,
user_type='user_modify_email',
client_ip=ip,
username=username,
comment='重置码有误或已使用过!'
)
return render(request, "email-modify-submit.html", {
'email_reset_code_errors': True,
"msg": "重置码有误或已使用过!",
'user_profile': user_profile,
'email_modify_form':email_modify_form,
'current_year': current_year
})
user_profile.rescue_email = email_new
user_profile.save()
email_verify_record.is_used = True
email_verify_record.save()
UserActionLog.objects.create(
status=True,
user_type='user_modify_email',
client_ip=ip,
username=username,
comment='邮箱修改成功-' + email_new
)
return render(request, 'email-modify-success.html', {
'current_year': current_year,
'email_modify_form':email_modify_form,
'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
'ip': ip
})
else:
username = request.POST.get('username', '')
user_profile = UserProfile.objects.get(username=username)
return render(request, 'email-modify-submit.html',{
'email_modify_form':email_modify_form,
'user_profile':user_profile,
'current_year': current_year,
})
用户解锁
class UserUnlockView(View):
def get(self,request):
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
current_year = datetime.now().year
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
username = request.GET.get("username", "")

if username:
cmd = 'powershell -command Get-ADUser -Identity {0}'.format(username)
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stderr:
if 'find' in stderr:
UserActionLog.objects.create(
status=False,
user_type='user_unlock',
client_ip=ip,
username=username,
comment='帐号不存在,请重新输入!'
)
return render(request, "user-unlock-index.html", {
'username_errors': True,
'msg': '帐号不存在,请重新输入!',
'username': username,
'current_year': current_year
})
else:
# try:
# user_profile = UserProfile.objects.get(username=username)
# except Exception as e:
# print e
# user_profile = UserProfile()
user_profile, created = UserProfile.objects.get_or_create(username=username)
return render(request, 'user-unlock-submit.html', {
'user_profile': user_profile,
'current_year': current_year,
'hashkey': hashkey,
'image_url': image_url
})
else:
return render(request, "user-unlock-index.html", {
'current_year': current_year,
})

def post(self, request):
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
current_year = datetime.now().year
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
user_unlock_form = UserUnlockForm(request.POST)
username = request.POST.get("username", '')
user_profile = UserProfile.objects.get(username=username)
if user_unlock_form.is_valid():
cmd = 'powershell -Command Unlock-ADAccount -Identity %s' % username
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = p.communicate()
if stderr:
UserActionLog.objects.create(
status=False,
user_type='user_unlock',
client_ip=ip,
username=username,
comment='帐号解锁失败'
)
return render(request, 'user-unlock-success.html', {
'msg':'解锁失败',
'username':username,
'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
'ip':ip
})
else:
data = {
'username': username,
'email': '{0}@genewiz.com.cn'.format(username),
'ip': ip,
'current_year': current_year
}
if SendMail(data, send_type='user_unlock'):
UserActionLog.objects.create(
status=True,
user_type='user_unlock',
client_ip=ip,
username=username,
comment='帐号解锁成功'
)
return render(request, 'user-unlock-success.html', {
'msg':'解锁成功',
'username':username,
'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
'ip':ip
})
else:
return render(request, 'user-unlock-submit.html', {
'user_unlock_form': user_unlock_form,
'user_profile':user_profile,
'hashkey': hashkey,
'image_url': image_url,
'current_year': current_year,

})
邮箱重置码
class EmailResetCodeView(View):
def get(self, request):
username = request.GET.get('username', '')
user_profile = UserProfile.objects.get(username=username)
email = user_profile.rescue_email
if request.META.has_key('HTTP_X_FORWARDED_FOR'):
ip = request.META['HTTP_X_FORWARDED_FOR']
else:
ip = request.META['REMOTE_ADDR']
current_year = datetime.now().year
data = {
'username': username,
'email': email,
'ip': ip,
'current_year': current_year
}
if SendMail(data, send_type='user_reset_email_code'):
UserActionLog.objects.create(
status=True,
user_type='user_reset_email_code',
client_ip=ip,
username=username,
comment='发送邮箱验证码成功-' + email
)
return HttpResponse(json.dumps({'status':'success', 'msg':'邮箱重置码发送成功,请查收!'}), content_type='application/json')
0%