remove dependence redis-sever, now use mem storage

update to layui, support PC and Mobile html render
This commit is contained in:
Leven
2023-01-09 23:05:16 +08:00
parent d10601b9ab
commit b82f2ececb
45 changed files with 1225 additions and 1344 deletions

View File

@@ -1,9 +1,11 @@
import ldap3
from ldap3 import *
from ldap3.core.exceptions import LDAPInvalidCredentialsResult, LDAPOperationResult, LDAPExceptionError,LDAPException
from ldap3.core.exceptions import LDAPInvalidCredentialsResult, LDAPOperationResult, LDAPExceptionError, LDAPException, \
LDAPSocketOpenError
from ldap3.core.results import *
from ldap3.utils.dn import safe_dn
import os
APP_ENV = os.getenv('APP_ENV')
if APP_ENV == 'dev':
from conf.local_settings_dev import *
@@ -36,7 +38,8 @@ unicodePwd 属性的语法为 octet-string;但是,目录服务预期八进制
class AdOps(object):
def __init__(self, auto_bind=True, use_ssl=AD_USE_SSL, port=AD_CONN_PORT, domain=AD_DOMAIN, user=AD_LOGIN_USER, password=AD_LOGIN_USER_PWD,
def __init__(self, auto_bind=True, use_ssl=AD_USE_SSL, port=AD_CONN_PORT, domain=AD_DOMAIN, user=AD_LOGIN_USER,
password=AD_LOGIN_USER_PWD,
authentication=NTLM):
"""
AD连接器 authentication [SIMPLE, ANONYMOUS, SASL, NTLM]
@@ -51,17 +54,38 @@ class AdOps(object):
self.password = password
self.authentication = authentication
self.auto_bind = auto_bind
self.server = None
self.conn = None
server = Server(host='%s' % AD_HOST, connect_timeout=1, use_ssl=self.use_ssl, port=port, get_info=ALL)
try:
self.conn = Connection(server, auto_bind=self.auto_bind, user=r'{}\{}'.format(self.domain, self.user), password=self.password,
authentication=self.authentication, raise_exceptions=True)
except LDAPInvalidCredentialsResult as lic_e:
raise LDAPOperationResult("LDAPInvalidCredentialsResult: " + str(lic_e.message))
except LDAPOperationResult as lo_e:
raise LDAPOperationResult("LDAPOperationResult: " + str(lo_e.message))
except LDAPException as l_e:
raise LDAPException("LDAPException: " + str(l_e))
def __server(self):
if self.server is None:
try:
self.server = Server(host='%s' % AD_HOST, connect_timeout=1, use_ssl=self.use_ssl, port=self.port,
get_info=ALL)
except LDAPInvalidCredentialsResult as lic_e:
return False, LDAPOperationResult("LDAPInvalidCredentialsResult: " + str(lic_e.message))
except LDAPOperationResult as lo_e:
return False, LDAPOperationResult("LDAPOperationResult: " + str(lo_e.message))
except LDAPException as l_e:
return False, LDAPException("LDAPException: " + str(l_e))
def __conn(self):
if self.conn is None:
try:
self.__server()
self.conn = Connection(self.server,
auto_bind=self.auto_bind, user=r'{}\{}'.format(self.domain, self.user),
password=self.password,
authentication=self.authentication,
raise_exceptions=True)
except LDAPInvalidCredentialsResult as lic_e:
return False, LDAPOperationResult("LDAPInvalidCredentialsResult: " + str(lic_e.message))
except LDAPOperationResult as lo_e:
return False, LDAPOperationResult("LDAPOperationResult: " + str(lo_e.message))
except LDAPException as l_e:
return False, LDAPException("LDAPException: " + str(l_e))
def ad_auth_user(self, username, password):
"""
@@ -71,8 +95,9 @@ class AdOps(object):
:return: True or False
"""
try:
server = Server(host='%s' % AD_HOST, use_ssl=self.use_ssl, port=self.port, get_info=ALL)
c_auth = Connection(server=server, user=r'{}\{}'.format(self.domain, username), password=password, auto_bind=True, raise_exceptions=True)
self.__server()
c_auth = Connection(server=self.server, user=r'{}\{}'.format(self.domain, username), password=password,
auto_bind=True, raise_exceptions=True)
c_auth.unbind()
return True, '旧密码验证通过。'
except LDAPInvalidCredentialsResult as e:
@@ -92,11 +117,15 @@ class AdOps(object):
# 如果仅仅使用普通凭据来绑定ldap用途请返回False, 让用户通过其他途径修改密码后再来验证登陆
# return False, '用户登陆前必须修改密码!'
# 设置该账号下次登陆不需要更改密码,再验证一次
self.conn.search(search_base=BASE_DN, search_filter='(sAMAccountName={}))'.format(username), attributes=['pwdLastSet'])
self.__conn()
self.conn.search(search_base=BASE_DN, search_filter='(sAMAccountName={}))'.format(username),
attributes=['pwdLastSet'])
self.conn.modify(self.conn.entries[0].entry_dn, {'pwdLastSet': [(MODIFY_REPLACE, ['-1'])]})
return self.ad_auth_user(username, password)
return True, self.ad_auth_user(username, password)
else:
return False, u'旧密码认证失败,请确认账号的旧密码是否正确或使用重置密码功能。'
except LDAPException as e:
return False, "连接Ldap失败报错如下{}".format(e)
def ad_ensure_user_by_account(self, username):
"""
@@ -105,9 +134,11 @@ class AdOps(object):
:return: True or False
"""
try:
return True, self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username), attributes=['sAMAccountName'])
self.__conn()
return True, self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username),
attributes=['sAMAccountName'])
except Exception as e:
return False, "AdOps Exception: {}" .format(e)
return False, "AdOps Exception: {}".format(e)
def ad_get_user_displayname_by_account(self, username):
"""
@@ -116,10 +147,11 @@ class AdOps(object):
:return: user_displayname
"""
try:
self.__conn()
self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username), attributes=['name'])
return True, self.conn.entries[0]['name']
except Exception as e:
return False, "AdOps Exception: {}" .format(e)
return False, "AdOps Exception: {}".format(e)
def ad_get_user_dn_by_account(self, username):
"""
@@ -128,10 +160,12 @@ class AdOps(object):
:return: DN
"""
try:
self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username), attributes=['distinguishedName'])
self.__conn()
self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username),
attributes=['distinguishedName'])
return True, str(self.conn.entries[0]['distinguishedName'])
except Exception as e:
return False, "AdOps Exception: {}" .format(e)
return False, "AdOps Exception: {}".format(e)
def ad_get_user_status_by_account(self, username):
"""
@@ -140,10 +174,12 @@ class AdOps(object):
:return: user_account_control code
"""
try:
self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username), attributes=['userAccountControl'])
self.__conn()
self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username),
attributes=['userAccountControl'])
return True, self.conn.entries[0]['userAccountControl']
except Exception as e:
return False, "AdOps Exception: {}" .format(e)
return False, "AdOps Exception: {}".format(e)
def ad_unlock_user_by_account(self, username):
"""
@@ -189,7 +225,8 @@ class AdOps(object):
# change was not successful, raises exception if raise_exception = True in connection or returns the operation result, error code is in result['result']
if self.conn.raise_exceptions:
from ldap3.core.exceptions import LDAPOperationResult
_msg = LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'],
_msg = LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'],
message=result['message'],
response_type=result['type'])
return False, _msg
return False, result['result']
@@ -203,35 +240,13 @@ class AdOps(object):
:return: 如果结果是1601-01-01说明账号未锁定返回0
"""
try:
self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username), attributes=['lockoutTime'])
self.__conn()
self.conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName={}))'.format(username),
attributes=['lockoutTime'])
locked_status = self.conn.entries[0]['lockoutTime']
if '1601-01-01' in str(locked_status):
return True, 'unlocked'
else:
return False, locked_status
except Exception as e:
return False, "AdOps Exception: {}" .format(e)
if __name__ == '__main__':
# server = Server(host='%s' % AD_HOST, use_ssl=AD_USE_SSL, port=AD_CONN_PORT, get_info=ALL)
# conn = Connection(server, auto_bind=True, user=str(AD_LOGIN_USER).lower(), password=AD_LOGIN_USER_PWD, authentication=SIMPLE)
# # conn.bind()
# # conn.search(BASE_DN, '(&(objectclass=user)(sAMAccountName=xiangle))', attributes=['name'])
# # print(conn.entries[0])
# print(conn.result)
# conn = _ad_connect()
# user = 'zhangsan'
# old_password = 'K2dhhuT1Zf11111cnJ1ollC3y'
# # old_password = 'L1qyrmZDUFeYW1OIualjlNhr4'
# new_password = 'K2dhhuT1Zf11111cnJ1ollC3y'
# ad_ops = AdOps()
# # ad_ops = AdOps(user=user, password=old_password)
# status, msg = ad_ops.ad_auth_user(username=user, password=old_password)
# print(msg)
# if status:
# res = ad_ops.ad_reset_user_pwd_by_account(user, new_password)
# print(res)
_ad = AdOps()
print(_ad.ad_ensure_user_by_account('le.xiang'))
return False, "AdOps Exception: {}".format(e)

View File

@@ -1,17 +0,0 @@
from cryptography.fernet import Fernet
class Crypto(object):
"""docstring for ClassName"""
def __init__(self, key):
self.factory = Fernet(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

@@ -4,8 +4,8 @@ from __future__ import absolute_import, unicode_literals
from dingtalk.client import AppKeyClient
from pwdselfservice import cache_storage
import os
APP_ENV = os.getenv('APP_ENV')
if APP_ENV == 'dev':
@@ -15,7 +15,8 @@ else:
class DingDingOps(AppKeyClient):
def __init__(self, corp_id=DING_CORP_ID, app_key=DING_APP_KEY, app_secret=DING_APP_SECRET, mo_app_id=DING_MO_APP_ID, mo_app_secret=DING_MO_APP_SECRET,
def __init__(self, corp_id=DING_CORP_ID, app_key=DING_APP_KEY, app_secret=DING_APP_SECRET, mo_app_id=DING_MO_APP_ID,
mo_app_secret=DING_MO_APP_SECRET,
storage=cache_storage):
super().__init__(corp_id, app_key, app_secret, storage)
self.corp_id = corp_id
@@ -58,18 +59,18 @@ class DingDingOps(AppKeyClient):
_status, user_id = self.get_user_id_by_code(code)
# 判断 user_id 在本企业钉钉/微信中是否存在
if not _status:
context = {
'msg': '获取userid失败错误信息{}'.format(user_id),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
context = {'global_title': TITLE,
'msg': '获取userid失败错误信息{}'.format(user_id),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
return False, context, user_id
detail_status, user_info = self.get_user_detail_by_user_id(user_id)
if not detail_status:
context = {
'msg': '获取用户信息失败,错误信息:{}'.format(user_info),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
context = {'global_title': TITLE,
'msg': '获取用户信息失败,错误信息:{}'.format(user_info),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
return False, context, user_info
return True, user_id, user_info

View File

@@ -51,8 +51,3 @@ def get_user_is_active(user_info):
except (KeyError, IndexError) as k_error:
return False, 'get_user_is_active: %s' % str(k_error)
if __name__ == '__main__':
user = 'jf.com\XiangLe'
username = format2username(user)
print(username)

View File

@@ -23,7 +23,7 @@ class MemoryStorage(BaseStorage):
else:
return default
def set(self, key, value, ttl=None):
def set(self, key, value, ttl=3600):
if value is None:
return
self._data[key] = (value, int(time.time()) + ttl)

View File

@@ -22,8 +22,6 @@ else:
CORP_API_TYPE = {
'GET_USER_TICKET_OAUTH2': ['/cgi-bin/auth/getuserinfo?access_token=ACCESS_TOKEN', 'GET'],
'GET_USER_INFO_OAUTH2': ['/cgi-bin/auth/getuserdetail?access_token=ACCESS_TOKEN', 'POST'],
'GET_ACCESS_TOKEN': ['/cgi-bin/gettoken', 'GET'],
'USER_CREATE': ['/cgi-bin/user/create?access_token=ACCESS_TOKEN', 'POST'],
'USER_GET': ['/cgi-bin/user/get?access_token=ACCESS_TOKEN', 'GET'],
@@ -35,12 +33,10 @@ CORP_API_TYPE = {
'USERID_TO_OPENID': ['/cgi-bin/user/convert_to_openid?access_token=ACCESS_TOKEN', 'POST'],
'OPENID_TO_USERID': ['/cgi-bin/user/convert_to_userid?access_token=ACCESS_TOKEN', 'POST'],
'USER_AUTH_SUCCESS': ['/cgi-bin/user/authsucc?access_token=ACCESS_TOKEN', 'GET'],
'DEPARTMENT_CREATE': ['/cgi-bin/department/create?access_token=ACCESS_TOKEN', 'POST'],
'DEPARTMENT_UPDATE': ['/cgi-bin/department/update?access_token=ACCESS_TOKEN', 'POST'],
'DEPARTMENT_DELETE': ['/cgi-bin/department/delete?access_token=ACCESS_TOKEN', 'GET'],
'DEPARTMENT_LIST': ['/cgi-bin/department/list?access_token=ACCESS_TOKEN', 'GET'],
'TAG_CREATE': ['/cgi-bin/tag/create?access_token=ACCESS_TOKEN', 'POST'],
'TAG_UPDATE': ['/cgi-bin/tag/update?access_token=ACCESS_TOKEN', 'POST'],
'TAG_DELETE': ['/cgi-bin/tag/delete?access_token=ACCESS_TOKEN', 'GET'],
@@ -48,34 +44,24 @@ CORP_API_TYPE = {
'TAG_ADD_USER': ['/cgi-bin/tag/addtagusers?access_token=ACCESS_TOKEN', 'POST'],
'TAG_DELETE_USER': ['/cgi-bin/tag/deltagusers?access_token=ACCESS_TOKEN', 'POST'],
'TAG_GET_LIST': ['/cgi-bin/tag/list?access_token=ACCESS_TOKEN', 'GET'],
'BATCH_JOB_GET_RESULT': ['/cgi-bin/batch/getresult?access_token=ACCESS_TOKEN', 'GET'],
'BATCH_INVITE': ['/cgi-bin/batch/invite?access_token=ACCESS_TOKEN', 'POST'],
'AGENT_GET': ['/cgi-bin/agent/get?access_token=ACCESS_TOKEN', 'GET'],
'AGENT_SET': ['/cgi-bin/agent/set?access_token=ACCESS_TOKEN', 'POST'],
'AGENT_GET_LIST': ['/cgi-bin/agent/list?access_token=ACCESS_TOKEN', 'GET'],
'MENU_CREATE': ['/cgi-bin/menu/create?access_token=ACCESS_TOKEN', 'POST'],
'MENU_GET': ['/cgi-bin/menu/get?access_token=ACCESS_TOKEN', 'GET'],
'MENU_DELETE': ['/cgi-bin/menu/delete?access_token=ACCESS_TOKEN', 'GET'],
'MESSAGE_SEND': ['/cgi-bin/message/send?access_token=ACCESS_TOKEN', 'POST'],
'MESSAGE_REVOKE': ['/cgi-bin/message/revoke?access_token=ACCESS_TOKEN', 'POST'],
'MEDIA_GET': ['/cgi-bin/media/get?access_token=ACCESS_TOKEN', 'GET'],
'GET_USER_INFO_BY_CODE': ['/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN', 'GET'],
'GET_USER_DETAIL': ['/cgi-bin/user/getuserdetail?access_token=ACCESS_TOKEN', 'POST'],
'GET_TICKET': ['/cgi-bin/ticket/get?access_token=ACCESS_TOKEN', 'GET'],
'GET_JSAPI_TICKET': ['/cgi-bin/get_jsapi_ticket?access_token=ACCESS_TOKEN', 'GET'],
'GET_CHECKIN_OPTION': ['/cgi-bin/checkin/getcheckinoption?access_token=ACCESS_TOKEN', 'POST'],
'GET_CHECKIN_DATA': ['/cgi-bin/checkin/getcheckindata?access_token=ACCESS_TOKEN', 'POST'],
'GET_APPROVAL_DATA': ['/cgi-bin/corp/getapprovaldata?access_token=ACCESS_TOKEN', 'POST'],
'GET_INVOICE_INFO': ['/cgi-bin/card/invoice/reimburse/getinvoiceinfo?access_token=ACCESS_TOKEN', 'POST'],
'UPDATE_INVOICE_STATUS':
['/cgi-bin/card/invoice/reimburse/updateinvoicestatus?access_token=ACCESS_TOKEN', 'POST'],
@@ -94,7 +80,8 @@ CORP_API_TYPE = {
class WeWorkOps(AbstractApi):
def __init__(self, corp_id=WEWORK_CORP_ID, agent_id=WEWORK_AGENT_ID, agent_secret=WEWORK_AGNET_SECRET, storage=cache_storage, prefix='wework'):
def __init__(self, corp_id=WEWORK_CORP_ID, agent_id=WEWORK_AGENT_ID, agent_secret=WEWORK_AGNET_SECRET,
storage=cache_storage, prefix='wework'):
super().__init__()
self.corp_id = corp_id
self.agent_id = agent_id
@@ -172,38 +159,33 @@ class WeWorkOps(AbstractApi):
临时授权码换取userinfo
"""
_status, ticket_data = self.get_user_ticket_by_code_with_oauth2(code)
print('ticket_data ----------- ', ticket_data)
# 判断 user_ticket 是否存在
if not _status:
context = {
'msg': '获取userid失败错误信息{}'.format(ticket_data),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
context = {'global_title': TITLE,
'msg': '获取userid失败错误信息{}'.format(ticket_data),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
return False, context, ticket_data
user_id = ticket_data.get('userid')
if ticket_data.get('user_ticket') is None:
context = {
'msg': '获取用户Ticket失败当前扫码用户[{}]可能未加入企业!'.format(user_id),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
context = {'global_title': TITLE,
'msg': '获取用户Ticket失败当前扫码用户[{}]可能未加入企业!'.format(user_id),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
return False, context, user_id
# 通过user_ticket获取企业微信用户详情信息
detail_status, user_info = self.get_user_info_by_ticket_with_oauth2(ticket_data.get('user_ticket'))
print("get_user_info_by_ticket_with_oauth2 --- ", user_info)
if not detail_status:
context = {
'msg': '获取用户信息失败,错误信息:{}'.format(user_id),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
context = {'global_title': TITLE,
'msg': '获取用户信息失败,错误信息:{}'.format(user_id),
'button_click': "window.location.href='%s'" % home_url,
'button_display': "返回主页"
}
return False, context
return True, user_id, user_info
if __name__ == '__main__':
wx = WeWorkOps()
print(wx.get_user_detail_by_user_id('XiangLe'))