def login(request): """ author:zxy function:登录先验证ldap再验证本地 param :request 前端发来的请求 return: 以user.id为内容的JsonResponse """ # 判断请求类型 if not request.method == "POST": return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED, data={}) bod = request.body bod = str(bod, encoding="utf-8") params = json.loads(bod) post_code = params.get("check_code", "").lower() session_code = request.session.get('verifycode', "").lower() username = params.get("username", "") # 输入的密码 password = params.get("password", "") # 判断验证码 if (not post_code) or (session_code != post_code): return JsonResponse({"error": "验证码错误"}, status=status.HTTP_417_EXPECTATION_FAILED, safe=False) try: user_ldap = LdapUser.objects.get(username=username) u_password = user_ldap.password very_ldap = sha.verify(password, u_password) if very_ldap == True: user = User.objects.get(username=user_ldap) auth.login(request, user) else: try: user = User.objects.get(username=username) except Exception as e: return JsonResponse({ 'error': '该用户不存在', 'e': str(e) }, status=status.HTTP_400_BAD_REQUEST) local_password = user.password very = sha.verify(password, local_password) if very == False: return JsonResponse({"error": "密码错误"}, status=status.HTTP_400_BAD_REQUEST) auth.login(request, user) except Exception as e: return JsonResponse({'error': '该用户不存在'}, status=status.HTTP_400_BAD_REQUEST) OperateLog.login(request) return JsonResponse({"id": user.id}, status=status.HTTP_200_OK)
def _on_Connection(self, server, user, password, auto_bind=None, client_strategy=None, authentication=None, check_names=None, auto_referrals=None, receive_timeout=None): """ We need to create a Connection object with methods: add() modify() search() unbind() and object response """ # check the password correct_password = False # Anonymous bind # Reload the directory just in case a change has been made to # user credentials self.directory = self._load_data(DIRECTORY) if authentication == ldap3.ANONYMOUS and user == "": correct_password = True for entry in self.directory: if entry.get("dn") == user: pw = entry.get("attributes").get("userPassword") # password can be unicode if to_bytes(pw) == to_bytes(password): correct_password = True elif pw.startswith('{SSHA}'): correct_password = ldap_salted_sha1.verify(password, pw) else: correct_password = False self.con_obj = Connection(self.directory) self.con_obj.bound = correct_password return self.con_obj
def personal_changepassword(request): if not request.method == "POST": return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED, data={}) data = ast.literal_eval(request.body.decode('utf-8')) OperateLog.create_log(request) try: with connect_ldap() as c: c.search('ou=Users,dc=xiaoneng,dc=cn', search_filter='(objectClass=inetOrgPerson)', attributes=['userPassword', 'cn'], search_scope=SUBTREE) ldap_password = '' dn = '' for i in c.entries: cn = i.entry_attributes_as_dict['cn'][0] print(cn) if i.entry_attributes_as_dict['cn'][0] == request.user.get_username(): ldap_password = i.entry_attributes_as_dict['userPassword'][0] dn = i.entry_dn break if ldap_password and sha.verify(data['old_password'], ldap_password): c.modify(dn, {'userpassword': [(MODIFY_REPLACE, sha.hash(data['new_password']))]}) # 修改本地密码 user = User.objects.get(username=cn) user.password = sha.hash(data['new_password']) user.save() else: return JsonResponse(status=status.HTTP_400_BAD_REQUEST, data={"result": False, "error": '旧密码错误, 验证失败'}) return JsonResponse(status=status.HTTP_200_OK, data={"result": True, "message": "修改成功"}) except Exception as e: return JsonResponse(status=status.HTTP_400_BAD_REQUEST, data={"result": False, "error": str(e.args)})
def query_ldap_password(username, password): hash = get_ldap().search_s(homecloud.config["LDAP_DOMAIN"], ldap.SCOPE_SUBTREE, "uid=" + username, ["userPassword"]) if len(hash[0][1]) == 0: return False try: return ldap_salted_sha1.verify(password, hash[0][1]["userPassword"][0]) except ValueError: return False
def personal_changepassword(request): if not request.method == "POST": return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED, data={}) data = ast.literal_eval(request.body.decode('utf-8')) user = request.user.get_username() OperateLog.create_log(request) mode = login_model # 校验ldap是否有该用户 ldap_exit = User.objects.filter(user_profile__create_source=1).filter(username=user).exists() # 校验本地是否有该用户 local_exit = User.objects.filter(user_profile__create_source=2).filter(username=user).exists() # ldap if mode == 1: ldap_change_password(request, **data) user = User.objects.filter(user_profile__create_source=1).get(username=user) user.password = sha.hash(data["new_password"]) user.save() # 本地 elif mode == 2: user = User.objects.filter(user_profile__create_source=2).get(username=user) if sha.verify(data['old_password'], user.password): user.password = sha.hash(data["new_password"]) user.save() # 本地+ldap ldap+本地 elif mode == 3 or mode == 4: if ldap_exit: ldap_change_password(request, **data) user = User.objects.filter(user_profile__create_source=1).get(username=user) user.password = sha.hash(data["new_password"]) user.save() if local_exit: user = User.objects.filter(user_profile__create_source=2).get(username=user) if sha.verify(data['old_password'], user.password): user.password = sha.hash(data["new_password"]) user.save() return JsonResponse(status=status.HTTP_200_OK, data={"info": "修改成功"})
def verify_password(plaintext, ciphertext): ''' 对明文密码和密文密码进行校验 :param str plaintext: 明文密码 :param str ciphertext: 密文密码 :return: 密码是否正确 :rtype: bool ''' if ciphertext.startswith('{SSHA}'): return ldap_salted_sha1.verify(plaintext, ciphertext) if ciphertext.startswith('{SMD5}'): return ldap_salted_md5.verify(plaintext, ciphertext) if ciphertext.startswith('{MD5}'): return ldap_md5.verify(plaintext, ciphertext) if ciphertext.startswith('{SHA}'): return ldap_sha1.verify(plaintext, ciphertext) return False
def ldap_change_password(request, **data): try: with connect_ldap() as c: c.search(get_login_model().user_ldapsearch, search_filter='(objectClass=inetOrgPerson)', attributes=['userPassword', 'cn'], search_scope=SUBTREE) ldap_password = '' dn = '' for i in c.entries: if i.entry_attributes_as_dict['cn'][0] == request.user.get_username(): ldap_password = i.entry_attributes_as_dict['userPassword'][0] dn = i.entry_dn break if ldap_password and sha.verify(data['old_password'], ldap_password): c.modify(dn, {'userpassword': [(MODIFY_REPLACE, sha.hash(data['new_password']))]}) except Exception as e: return JsonResponse(status=status.HTTP_400_BAD_REQUEST, data={"error": "ldap密码修改失败", "e": str(e.args)})
def _on_Connection(self, server, user, password, auto_bind=None, client_strategy=None, authentication=None, check_names=None, auto_referrals=None, receive_timeout=None): """ We need to create a Connection object with methods: add() modify() search() unbind() and object response """ # check the password correct_password = False # Anonymous bind # Reload the directory just in case a change has been made to # user credentials self.directory = self._load_data(DIRECTORY) if authentication == ldap3.ANONYMOUS and user == "": correct_password = True for entry in self.directory: if entry.get("dn") == user: pw = entry.get("attributes").get("userPassword") # password can be unicode if to_bytes(pw) == to_bytes(password): correct_password = True elif pw.startswith('{SSHA}'): correct_password = ldap_salted_sha1.verify(password, pw) else: correct_password = False self.con_obj = Connection(self.directory) self.con_obj.bound = correct_password return self.con_obj
def verify_password(self, plaintext, ciphertext): """ verify password. """ if plaintext is None or ciphertext is None: return False self.valid_encryption() if ciphertext.startswith('{SSHA}'): return ldap_salted_sha1.verify(plaintext, ciphertext) if ciphertext.startswith('{SMD5}'): return ldap_salted_md5.verify(plaintext, ciphertext) if ciphertext.startswith('{MD5}'): return ldap_md5.verify(plaintext, ciphertext) if ciphertext.startswith('{SHA}'): return ldap_sha1.verify(plaintext, ciphertext) return False
def ___boolean___verify_password___(self, password): return passlib___ldap_salted_sha1.verify(password, self.password)
from passlib.hash import ldap_salted_sha1 as lsm hash_str = lsm.hash('shit') print(lsm.verify('shits', hash_str))
def check_password(self, password): return ( ldap_pbkdf2_sha256.identify(self.hash_ldap) and \ ldap_pbkdf2_sha256.verify(password, self.hash_ldap) ) \ or (ldap_salted_sha1.identify(self.hash_ldap) and \ ldap_salted_sha1.verify(password, self.hash_ldap))
def login(request): """ author:zxy function:登录验证 param :request 前端发来的请求 return: 以user.id为内容的JsonResponse """ # 判断请求类型 if not request.method == "POST": return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED, data={}) params = request.POST post_code = params.get("check_code", "").lower() session_code = request.session.get('verifycode', "").lower() username = params.get("username", "") # 输入的密码 password = params.get("password", "") # 判断验证码 if (not post_code) or (session_code != post_code): return JsonResponse({"error": "验证码错误"}, status=status.HTTP_417_EXPECTATION_FAILED, safe=False) # 1:ldap 2: 本地 3: 本地+ldap 4: ldap+本地 login_mode = get_login_model() mode = login_mode.login_model try: use = User.objects.filter(username=username).first() if use and use.is_superuser == True: if use.password.startswith('{SSHA}'): ps = sha.verify(password, use.password) else: ps = check_password(password, use.password) if ps == False: return JsonResponse({"error": "密码错误"}, status=status.HTTP_400_BAD_REQUEST) auth.login(request, use) except: pass if not use or (use and use.is_superuser == False): # ldap验证 if mode == 1: try: use = User.objects.filter(user_profile__create_source=1).get( username=username) password_t = use.password very = sha.verify(password, password_t) if very == False: return JsonResponse({"error": "密码错误"}, status=status.HTTP_400_BAD_REQUEST) auth.login(request, use) except Exception as e: return JsonResponse({ 'error': '该用户不存在', 'e': str(e) }, status=status.HTTP_400_BAD_REQUEST) # 本地验证 elif mode == 2: try: # daigaigg use = User.objects.filter(user_profile__create_source=2).get( username=username) password_t = use.password very = sha.verify(password, password_t) if very == False: return JsonResponse({"error": "密码错误"}, status=status.HTTP_400_BAD_REQUEST) auth.login(request, use) except Exception as e: return JsonResponse({ 'error': '该用户不存在', 'e': str(e) }, status=status.HTTP_400_BAD_REQUEST) # 本地优先 elif mode == 3: use = User.objects.filter(user_profile__create_source=2).filter( username=username).first() use1 = User.objects.filter(user_profile__create_source=1).filter( username=username).first() try: if use: use = use elif use == None: use = use1 elif use1 == None: return JsonResponse({"error": "该用户不存在"}, status=status.HTTP_400_BAD_REQUEST) password_b = use.password very = sha.verify(password, password_b) if very == False: return JsonResponse({"error": "密码错误"}, status=status.HTTP_400_BAD_REQUEST) auth.login(request, use) except Exception as e: return JsonResponse({"error": "该用户不存在"}, status=status.HTTP_400_BAD_REQUEST) # ldap优先 elif mode == 4: use = User.objects.filter(user_profile__create_source=1).filter( username=username).first() use1 = User.objects.filter(user_profile__create_source=2).filter( username=username).first() try: if use: use = use elif use == None: use = use1 elif use1 == None: return JsonResponse({"error": "该用户不存在"}, status=status.HTTP_400_BAD_REQUEST) password_b = use.password very = sha.verify(password, password_b) if very == False: return JsonResponse({"error": "密码错误"}, status=status.HTTP_400_BAD_REQUEST) auth.login(request, use) except Exception as e: return JsonResponse({"error": "该用户不存在"}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({"id": use.id}, status=status.HTTP_200_OK)