整理结构

This commit is contained in:
GitHub
2019-08-02 09:49:38 +08:00
parent 00871e08f1
commit 1cf4e60be3
14 changed files with 81 additions and 5 deletions

View File

99
resetpwd/utils/ad.py Normal file
View File

@@ -0,0 +1,99 @@
from ldap3 import *
from pwdselfservice.local_settings import *
def __ad_connect():
username = str(AD_LOGIN_USER).lower()
server = Server(host=AD_HOST, use_ssl=True, port=636, get_info='ALL')
try:
conn = Connection(server, auto_bind=True, user=username, password=AD_LOGIN_USER_PWD, authentication='NTLM')
return conn
except Exception:
raise Exception('Server Error. Could not connect to Domain Controller')
def ad_ensure_user_by_sam(username):
"""
通过sAMAccountName查询某个用户是否在AD中
:param username: 除去@domain.com 的部分
:return: True or False
"""
conn = __ad_connect()
base_dn = BASE_DN
condition = '(&(objectclass=person)(mail=' + username + '))'
attributes = ['sAMAccountName']
return conn.search(base_dn, condition, attributes=attributes)
def ad_ensure_user_by_mail(user_mail_addr):
"""
通过mail查询某个用户是否在AD中
:param user_mail_addr:
:return: True or False
"""
conn = __ad_connect()
base_dn = BASE_DN
condition = '(&(objectclass=person)(mail=' + user_mail_addr + '))'
attributes = ['mail']
return conn.search(base_dn, condition, attributes=attributes)
def ad_get_user_displayname_by_mail(user_mail_addr):
conn = __ad_connect()
conn.search(BASE_DN, '(&(objectclass=person)(mail=' + user_mail_addr + '))', attributes=[
'displayName'])
user_displayname = conn.entries[0]['displayName']
conn.unbind()
return user_displayname
def ad_get_user_dn_by_mail(user_mail_addr):
conn = __ad_connect()
conn.search(BASE_DN,
'(&(objectclass=person)(mail=' + user_mail_addr + '))', attributes=['distinguishedName'])
user_dn = conn.entries[0]['distinguishedName']
return user_dn
def ad_get_user_status_by_mail(user_mail_addr):
conn = __ad_connect()
conn.search(BASE_DN,
'(&(objectclass=person)(mail=' + user_mail_addr + '))', attributes=['userAccountControl'])
user_account_control = conn.entries[0]['userAccountControl']
return user_account_control
def ad_unlock_user_by_mail(user_mail_addr):
conn = __ad_connect()
user_dn = ad_get_user_dn_by_mail(user_mail_addr)
result = conn.extend.microsoft.unlock_account(user="%s" % user_dn)
conn.unbind()
return result
def ad_reset_user_pwd_by_mail(user_mail_addr, new_password):
conn = __ad_connect()
user_dn = ad_get_user_dn_by_mail(user_mail_addr)
result = conn.extend.microsoft.modify_password(user="%s" % user_dn, new_password="%s" % new_password)
conn.unbind()
return result
def ad_modify_user_pwd_by_mail(user_mail_addr, old_password, new_password):
conn = __ad_connect()
user_dn = ad_get_user_dn_by_mail(user_mail_addr)
result = conn.extend.microsoft.modify_password(user="%s" % user_dn, new_password="%s" % new_password,
old_password="%s" % old_password)
conn.unbind()
return result
def ad_get_user_locked_status_by_mail(user_mail_addr):
conn = __ad_connect()
conn.search(BASE_DN, '(&(objectclass=person)(mail=' + user_mail_addr + '))', attributes=['lockoutTime'])
locked_status = conn.entries[0]['lockoutTime']
print(locked_status)
if '1601-01-01' in str(locked_status):
return 0
else:
return locked_status

22
resetpwd/utils/crypto.py Normal file
View File

@@ -0,0 +1,22 @@
from cryptography.fernet import Fernet
class Crypto(object):
"""docstring for ClassName"""
def __init__(self, key):
self.factory = Fernet(key)
@staticmethod
def generate_key():
key = Fernet.generate_key()
print(key)
# 加密
def encrypt(self, string):
token = str(self.factory.encrypt(string.encode('utf-8')), 'utf-8')
return token
# 解密
def decrypt(self, token):
string = self.factory.decrypt(bytes(token.encode('utf-8'))).decode('utf-8')
return string

View File

@@ -0,0 +1,82 @@
from dingtalk.client import *
import requests
from pwdselfservice.local_settings import *
def ding_get_access_token():
resp = requests.get(
url=DING_URL + "/gettoken",
params=dict(appid=DING_SELF_APP_ID, appsecret=DING_SELF_APP_SECRET)
)
resp = resp.json()
if resp['access_token']:
return resp['access_token']
else:
return None
def ding_get_persistent_code(code, token):
resp = requests.post(
url="%s/get_persistent_code?access_token=%s" % (DING_URL, token),
json=dict(tmp_auth_code=code),
)
resp = resp.json()
if resp['unionid']:
return resp['unionid']
else:
return None
def ding_client_connect():
client = AppKeyClient(corp_id=DING_CORP_ID, app_key=DING_APP_KEY, app_secret=DING_APP_SECRET)
return client
def ding_get_dept_user_list_detail(dept_id, offset, size):
client = ding_client_connect()
result = client.user.list(department_id=dept_id, offset=offset, size=size)
return result
def ding_get_userinfo_by_code(code):
"""
:param code: requestAuthCode接口中获取的CODE
:return:
"""
client = ding_client_connect()
resutl = client.user.getuserinfo(code)
return resutl
def ding_get_userid_by_unionid(unionid):
"""
:param unionid: 用户在当前钉钉开放平台账号范围内的唯一标识
:return:
"""
client = ding_client_connect()
resutl = client.user.get_userid_by_unionid(unionid)
if resutl['userid']:
return resutl['userid']
else:
return None
def ding_get_org_user_count():
"""
企业员工数量
only_active 是否包含未激活钉钉的人员数量
:return:
"""
client = ding_client_connect()
resutl = client.user.get_org_user_count('only_active')
return resutl
def ding_get_userinfo_detail(user_id):
"""
user_id 用户ID
:return:
"""
client = ding_client_connect()
resutl = client.user.get(user_id)
return resutl

34
resetpwd/utils/form.py Normal file
View File

@@ -0,0 +1,34 @@
from django.forms import fields as c_fields
from django import forms as c_forms
from django.core.exceptions import ValidationError
class CheckForm(c_forms.Form):
new_password = c_fields.RegexField(
'(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}',
# 密码必须同时包含大写、小写、数字和特殊字符其中三项且至少8位
strip=True,
min_length=8,
max_length=30,
error_messages={'required': '新密码不能为空.',
'invalid': '密码必须包含数字,字母、特殊字符',
'min_length': "密码长度不能小于8个字符",
'max_length': "密码长度不能大于30个字符"}
)
old_password = c_fields.CharField(error_messages={'required': '确认密码不能为空'})
ensure_password = c_fields.CharField(error_messages={'required': '确认密码不能为空'})
user_email = c_fields.CharField(error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'})
def clean(self):
pwd0 = self.cleaned_data.get('old_password')
pwd1 = self.cleaned_data.get('new_password')
pwd2 = self.cleaned_data.get('ensure_password')
if pwd1 == pwd2:
pass
elif pwd0 == pwd1:
# 这里异常模块导入要放在函数里面,放到文件开头有时会报错,找不到
from django.core.exceptions import ValidationError
raise ValidationError('新旧密码不能一样')
else:
from django.core.exceptions import ValidationError
raise ValidationError('新密码和确认密码输入不一致')

View File

@@ -0,0 +1,30 @@
from django.shortcuts import render, reverse, HttpResponsePermanentRedirect, redirect
from django.http import *
from django.contrib import messages
from dingtalk import *
from resetpwd.models import *
from .crypto import Crypto
from .ad import ad_get_user_locked_status_by_mail, ad_unlock_user_by_mail, ad_reset_user_pwd_by_mail, \
ad_get_user_status_by_mail, ad_ensure_user_by_mail, ad_modify_user_pwd_by_mail
from .dingding import ding_get_userinfo_detail, ding_get_userid_by_unionid, ding_get_userinfo_by_code, \
ding_get_persistent_code, ding_get_access_token
from pwdselfservice.local_settings import *
from .form import *
class CustomPasswortValidator(object):
def __init__(self, min_length=1, max_length=30):
self.min_length = min_length
def validate(self, password):
special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]"
if not any(char.isdigit() for char in password):
raise ValidationError(_('Password must contain at least %(min_length)d digit.') % {'min_length': self.min_length})
if not any(char.isalpha() for char in password):
raise ValidationError(_('Password must contain at least %(min_length)d letter.') % {'min_length': self.min_length})
if not any(char in special_characters for char in password):
raise ValidationError(_('Password must contain at least %(min_length)d special character.') % {'min_length': self.min_length})
def get_help_text(self):
return ""