def CheckLogin(ctx, Account, Password): if Account == SystemInfo.CurrentUserName: if Password == SystemInfo.CurrentPassword: imanageuser = UserInfo() imanageuser.Id = 'Administrator' imanageuser.UserName = '******' imanageuser.Code = 'Administrator' imanageuser.CompanyId = '系统' imanageuser.DepartmentId = '系统' imanageuser.IPAddress = ctx.transport.req["REMOTE_ADDR"] imanageuser.IsAdministrator = True # TODO:需要做在线人数统计 user = json.dumps(imanageuser, default=UserInfo.obj_2_json) user = SecretHelper.AESEncrypt(user) Msg = str(user, encoding = "utf8") else: Msg = "['认证失败']" else: returnStatusCode = '' returnStatusCode, userInfo = LogOnService.UserLogOn(Account, Password, '', False, ctx.transport.req["REMOTE_ADDR"]) if returnStatusCode == StatusCode.statusCodeDic.get('OK'): user = json.dumps(userInfo, default=UserInfo.obj_2_json) user = SecretHelper.AESEncrypt(user) Msg = str(user, encoding="utf8") else: Msg = "['认证失败']" yield Msg
def wrapped_function(*args, **kwargs): if ParameterService.GetServiceConfig(None, 'LoginProvider') == 'Cookie': try: user = args[0].get_signed_cookie( ParameterService.GetServiceConfig( None, 'LoginProvider'), salt=ParameterService.GetServiceConfig( None, 'LoginUserKey')) if user: user = SecretHelper.AESDecrypt(user) try: user = json.loads(user, object_hook=UserInfo.json_2_obj) if PublicController.IsAuthorized( HttpResponse(), args[0], code): return func(*args, **kwargs) else: return HttpResponseRedirect('/Admin/Index/') except: return HttpResponseRedirect('/Admin/Index/') else: return HttpResponseRedirect('/Admin/Index/') except Exception as e: print(e) return HttpResponseRedirect('/Admin/Index/') else: try: user = args[0].session.get( ParameterService.GetServiceConfig( None, 'LoginProvider')) if user: user = SecretHelper.AESDecrypt(user) try: user = json.loads(user, object_hook=UserInfo.json_2_obj) if PublicController.IsAuthorized( HttpResponse(), args[0], code): return func(*args, **kwargs) else: return HttpResponseRedirect('/Admin/Index/') except: return HttpResponseRedirect('/Admin/Index/') else: return HttpResponseRedirect('/Admin/Index/') except Exception as e: print(e) return HttpResponseRedirect('/Admin/Index/')
def GetUserListByPage(ctx, userInfo, page=1, rows=50, sort='sortcode', order='asc', filter=''): try: user = SecretHelper.AESDecrypt(userInfo) user = json.loads(user, object_hook=UserInfo.json_2_obj) except: yield "['认证失败']" if PublicController.ApiIsAuthorized( user, "UserManagement.GetUserListByPage"): dtUser = UserSerivce.GetDTByPage( user, SearchFilter.TransfromFilterToSql(filter, False), '', '', rows, sort + ' ' + order) recordCount = dtUser.count pageValue = dtUser.page(page) userTmp = '' for role in pageValue: userTmp = userTmp + ', ' + json.dumps(role, cls=DateEncoder) userTmp = userTmp.strip(',') returnValue = '{"total": ' + str( recordCount) + ', "rows":[' + userTmp + ']}' yield returnValue else: yield "['权限不足']"
def GetUserPageDTByDepartmentId(ctx, userInfo, organizeId, searchValue, page, rows): try: user = SecretHelper.AESDecrypt(userInfo) user = json.loads(user, object_hook=UserInfo.json_2_obj) except: yield "['认证失败']" if PublicController.ApiIsAuthorized( user, "UserManagement.GetUserPageDTByDepartmentId"): searchValue = searchValue if searchValue else '' jsons = "[]" returnValue = '' if organizeId: recordCount = 0 recordCount, dtUser = UserOrganizeService.GetUserPageDTByDepartment( None, user, 'Resource.ManagePermission', searchValue, None, '', None, True, True, page, rows, 'sortcode', organizeId) userTmp = '' for user in dtUser: userTmp = userTmp + ', ' + json.dumps(user, cls=DateEncoder) userTmp = userTmp.strip(',') returnValue = '{"total": ' + str( recordCount) + ', "rows":[' + userTmp + ']}' yield returnValue else: yield jsons else: yield "['权限不足']"
def SetPassword(self, userIds, password): """ 设置用户密码 Args: userIds (string): 用户ID password (string): 密码 Returns: returnValue(int): 大于0操作成功 """ returnValue = 0 returnCode = '' returnMessage = '' enableCheckIPAddress = 0 if not userIds or len(userIds) == 0: returnCode = StatusCode.statusCodeDic['NotFound'] return returnCode,returnValue #设置密码 if SystemInfo.EnableEncryptServerPassword: password = SecretHelper.AESEncrypt(password) if SystemInfo.EnableCheckIPAddress: enableCheckIPAddress = 1 for id in userIds: Piuserlogon.objects.update_or_create(id = id, defaults={'checkipaddress':enableCheckIPAddress, 'userpassword':bytes.decode(password), 'openid':uuid.uuid1(), 'useronline':0, 'createon':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'modifiedon':datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) returnValue = returnValue + 1 returnCode = StatusCode.statusCodeDic['SetPasswordOK'] return returnCode,returnValue
def __call__(self, *args, **kw): if ParameterService.GetServiceConfig(None, 'LoginProvider') == 'Cookie': try: user = args[0].get_signed_cookie( ParameterService.GetServiceConfig(None, 'LoginProvider'), salt=ParameterService.GetServiceConfig( None, 'LoginUserKey')) if user: user = SecretHelper.AESDecrypt(user) try: user = json.loads(user, object_hook=UserInfo.json_2_obj) except: return HttpResponseRedirect('/Admin/Index/') return self.f(*args, **kw) else: return HttpResponseRedirect('/Admin/Index/') except Exception as e: print(e) return HttpResponseRedirect('/Admin/Index/') else: try: user = args[0].session.get( ParameterService.GetServiceConfig(None, 'LoginProvider')) if user: user = SecretHelper.AESDecrypt(user) try: user = json.loads(user, object_hook=UserInfo.json_2_obj) except: return HttpResponseRedirect('/Admin/Index/') return self.f(*args, **kw) else: return HttpResponseRedirect('/Admin/Index/') except Exception as e: print(e) #TODO:这个地方只是暂时用来记录异常信息的代码,应当将不同模块不同方法的异常记录写到各自的代码中,后期此代码要删除 e_out = Ciexception() e_out.id = uuid.uuid4() e_out.createon = datetime.datetime.now() e_out.message = e ExceptionService.Add(None, e_out) return HttpResponseRedirect('/Admin/Index/')
def ChangePassword(self, userId, oldPassword, newPassword): """ 更新密码 Args: userId (string): 用户主键 oldPassword (string): 老密码 newPassword (string): 新密码 Returns: returnValue (string): 影响行数 """ returnValue = 0 statusCode = '' #密码强度检查 if SystemInfo.EnableCheckPasswordStrength: if not newPassword: statusCode = StatusCode.statusCodeDic['PasswordCanNotBeNull'] return statusCode, returnValue #最小长度、字母数字组合等强度检查 if not ValidateUtil.EnableCheckPasswordStrength(self, newPassword): statusCode = StatusCode.statusCodeDic['PasswordNotStrength'] return statusCode, returnValue #加密密码 if SystemInfo.EnableEncryptServerPassword: oldPassword = SecretHelper.AESEncrypt(self, oldPassword) newPassword = SecretHelper.AESEncrypt(self, newPassword) #判断输入原始密码是否正确 try: entity = Piuserlogon.objects.get(id=userId) if not entity.userpassword: entity.userpassword = '' if not entity.userpassword == oldPassword: statusCode = StatusCode.statusCodeDic['OldPasswordError'] return statusCode, returnValue entity.userpassword = newPassword entity.changepassworddate = datetime.datetime.now() entity.save() statusCode = StatusCode.statusCodeDic['ChangePasswordOK'] return statusCode, 1 except Piuserlogon.DoesNotExist as e: pass
def AddCurrent(user, response, request): """ 写入登录信息 Args: user (UserInfo): user Returns: """ try: if ParameterService.GetServiceConfig( CommonUtils.Current(response, request), 'LoginProvider') == 'Cookie': #user = pickle.dumps(user) user = json.dumps(user, default=UserInfo.obj_2_json) #response.set_signed_cookie(ParameterService.GetServiceConfig('LoginProvider'), str(user), max_age=int(ParameterService.GetServiceConfig('CookieMaxAge')), salt=ParameterService.GetServiceConfig('LoginUserKey')) user = SecretHelper.AESEncrypt(user) user = str(user, encoding="utf8") response.set_signed_cookie( ParameterService.GetServiceConfig( CommonUtils.Current(response, request), 'LoginProvider'), user, max_age=int( ParameterService.GetServiceConfig( CommonUtils.Current(response, request), 'CookieMaxAge')), salt=ParameterService.GetServiceConfig( CommonUtils.Current(response, request), 'LoginUserKey')) else: #user = pickle.dumps(user) user = json.dumps(user, default=UserInfo.obj_2_json) user = SecretHelper.AESEncrypt(user) user = str(user, encoding="utf8") request.session[ParameterService.GetServiceConfig( CommonUtils.Current(response, request), 'LoginProvider')] = user request.session.set_expiry( int( ParameterService.GetServiceConfig( CommonUtils.Current(response, request), 'CookieMaxAge'))) except Exception as e: print(e)
def Current(response, request): if ParameterService.GetServiceConfig(None, 'LoginProvider') == 'Cookie': try: user = request.get_signed_cookie( ParameterService.GetServiceConfig(None, 'LoginProvider'), salt=ParameterService.GetServiceConfig( None, 'LoginUserKey')) #user = pickle.loads(user) user = SecretHelper.AESDecrypt(user) user = json.loads(user, object_hook=UserInfo.json_2_obj) return user except Exception as e: return None else: try: user = request.session.get( ParameterService.GetServiceConfig(None, 'LoginProvider')) user = SecretHelper.AESDecrypt(user) user = json.loads(user, object_hook=UserInfo.json_2_obj) return user except Exception as e: print(e) return None
def LogOn(userName, password, openId=None, createNewOpenId=False, ipAddress=None, macAddress=None, checkUserPassword=True): ReturnStatusCode = '' userInfo = UserInfo() realName = '' if UserInfo: realName = userInfo.RealName if ipAddress: #ipAddress = UserInfo.IPAddress userInfo.IPAddress = ipAddress if macAddress: #macAddress = UserInfo.MACAddress userInfo.MACAddress = macAddress #01: 系统是否采用了在线用户的限制 if SystemInfo.OnLineLimit > 0 and LogOnService.CheckOnLineLimit(): ReturnStatusCode = StatusCode.statusCodeDic['ErrorOnLineLimit'] return userInfo #02. 默认为用户没有找到状态,查找用户 #这是为了达到安全要求,不能提示用户未找到,那容易让别人猜测到帐户 if SystemInfo.EnableCheckPasswordStrength: ReturnStatusCode = StatusCode.statusCodeDic['ErrorLogOn'] else: ReturnStatusCode = StatusCode.statusCodeDic['UserNotFound'] #03. 查询数据库中的用户数据?只查询未被删除的 dataTable = Piuser.objects.filter( Q(deletemark=0) & Q(username=userName)) if dataTable.count() == 0: #TODO:若没数据再工号、邮件、手机号等方式登录 pass userEntity = None userLogOnEntity = None if dataTable.count() > 1: ReturnStatusCode = StatusCode.statusCodeDic['UserDuplicate'] elif dataTable.count() == 1: #05. 判断密码,是否允许登录,是否离职是否正确 userEntity = dataTable[0] if userEntity.auditstatus and userEntity.auditstatus.endswith( AuditStatus.WaitForAudit): ReturnStatusCode = AuditStatus.WaitForAudit return ReturnStatusCode, userInfo #用户无效、已离职的 if userEntity.isdimission == 1 or userEntity.enabled == 0: ReturnStatusCode = StatusCode.statusCodeDic['LogOnDeny'] return ReturnStatusCode, userInfo #用户是否有效的 if userEntity.enabled == -1: ReturnStatusCode = StatusCode.statusCodeDic['UserNotActive'] return ReturnStatusCode, userInfo userLogOnEntity = Piuserlogon.objects.get(id=userEntity.id) if (not userEntity.username) or (userEntity.username != 'Administrator'): #06. 允许登录时间是否有限制 if userLogOnEntity.allowendtime: userLogOnEntity.allowendtime = datetime.datetime( datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day, userLogOnEntity.allowendtime.hour, userLogOnEntity.allowendtime.minute, userLogOnEntity.allowendtime.second) if userLogOnEntity.allowstarttime: userLogOnEntity.allowstarttime = datetime.datetime( datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day, userLogOnEntity.allowstarttime.hour, userLogOnEntity.allowstarttime.minute, userLogOnEntity.allowstarttime.second) if datetime.datetime.now( ) < userLogOnEntity.allowstarttime: ReturnStatusCode = StatusCode.statusCodeDic[ 'UserLocked'] return ReturnStatusCode, userInfo if userLogOnEntity.allowendtime: if datetime.datetime.now() > userLogOnEntity.allowendtime: ReturnStatusCode = StatusCode.statusCodeDic[ 'UserLocked'] return ReturnStatusCode, userInfo #07. 锁定日期是否有限制 if userLogOnEntity.lockstartdate and datetime.datetime.now( ) > userLogOnEntity.lockstartdate: if userLogOnEntity.lockenddate or datetime.datetime.now( ) < userLogOnEntity.lockenddate: ReturnStatusCode = StatusCode.statusCodeDic[ 'UserLocked'] return ReturnStatusCode, userInfo #08. 是否检查用户IP地址,是否进行访问限制?管理员不检查IP. && !this.IsAdministrator(userEntity.Id.ToString() if SystemInfo.EnableCheckIPAddress and userLogOnEntity.checkipAddress == 1 and ( userEntity.username != 'Administrator' or userEntity.code == 'Administrator'): if ipAddress: if ParameterService.Exists(userEntity.id, 'IPAddress'): if not CheckIPAddress.CheckIPAddress( ipAddress, userEntity.id): ReturnStatusCode = StatusCode.statusCodeDic[ 'ErrorIPAddress'] return ReturnStatusCode, userInfo #没有设置MAC地址时不检查 if macAddress: if ParameterService.Exists(userEntity.id, 'MacAddress'): if not CheckIPAddress.CheckIPAddress( macAddress, userEntity.id): ReturnStatusCode = StatusCode.statusCodeDic[ 'ErrorMacAddress'] return ReturnStatusCode, userInfo #10. 只允许登录一次,需要检查是否自己重新登录了,或者自己扮演自己了 if UserInfo and UserInfo.Id != userEntity.id: if SystemInfo.CheckOnLine and userLogOnEntity.multiuserlogin == 0 and userLogOnEntity.useronline > 0: isSelf = False if openId: if userLogOnEntity.openid: if userLogOnEntity.openid == openId: isSelf = True if not isSelf: ReturnStatusCode = StatusCode.statusCodeDic['ErrorOnLine'] return ReturnStatusCode, userInfo #04. 系统是否采用了密码加密策略? if checkUserPassword and SystemInfo.EnableEncryptServerPassword: password = SecretHelper.AESEncrypt(password).decode() #11. 密码是否正确(null 与空看成是相等的) if userLogOnEntity.userpassword and password: userPasswordOK = True #用户密码是空的 if not userLogOnEntity.userpassword: #但是输入了不为空的密码 if password: userPasswordOK = False else: #用户的密码不为空,但是用户是输入了密码、 再判断用户的密码与输入的是否相同 userPasswordOK = password and userLogOnEntity.userpassword == password #用户的密码不相等 if not userPasswordOK: userLogOnEntity.passworderrorcount = userLogOnEntity.passworderrorcount + 1 if SystemInfo.PasswordErrorLockLimit > 0 and userLogOnEntity.passworderrorcount >= SystemInfo.PasswordErrorLockLimit: #密码错误锁定周期若为0,直接设帐号无效,需要管理员审核 if SystemInfo.PasswordErrorLockCycle == 0: Piuser.objects.filter(id=userEntity.id).update( enabled=0, auditstatus=AuditStatus.WaitForAudit) else: userLogOnEntity.lockstartdate = datetime.datetime.now() userLogOnEntity.lockenddate = datetime.datetime.now( ) + datetime.timedelta( minutes=SystemInfo.PasswordErrorLockCycle) Piuserlogon.objects.filter(id=userEntity.id).update( lockstartdate=userLogOnEntity.lockstartdate, lockenddate=userLogOnEntity.lockenddate) else: Piuserlogon.objects.filter(id=userEntity.id).update( passworderrorcount=userLogOnEntity.passworderrorcount) ''' 密码错误后处理: 11.1:记录日志 LogManager.Instance.Add(DBProvider, userEntity.Id.ToString(), userEntity.RealName, "LogOn", RDIFrameworkMessage.UserManager, "LogOn", RDIFrameworkMessage.UserManager_LogOn, userEntity.RealName, ipAddress, RDIFrameworkMessage.MSG0088); TODO: 11.2:看当天(24小时内)输入错误密码多少次了? TODO: 11.3:若输错密码数量已经超过了系统限制,则用户被锁定系统设定的小时数。 TODO: 11.4:同时处理返回值,由于输入错误密码次数过多导致被锁定,登录时应读取这个状态比较,时间过期后应处理下状态。 密码强度检查,若是要有安全要求比较高的,返回的提醒消息要进行特殊处理,不能返回非常明确的提示信息。 ''' if SystemInfo.EnableCheckPasswordStrength: ReturnStatusCode = StatusCode.statusCodeDic['ErrorLogOn'] else: ReturnStatusCode = StatusCode.statusCodeDic[ 'PasswordError'] return ReturnStatusCode, userInfo #12. 更新IP地址,更新MAC地址 userLogOnEntity.passworderrorcount = 0 if ipAddress: userLogOnEntity.ipaddress = ipAddress if macAddress: userLogOnEntity.macaddress = macAddress Piuserlogon.objects.filter(id=userEntity.id).update( passworderrorcount=0, ipaddress=ipAddress, macaddress=macAddress) #可以正常登录了 ReturnStatusCode = StatusCode.statusCodeDic['OK'] #13. 登录、重新登录、扮演时的在线状态进行更新 #userLogOnManager.ChangeOnLine(userEntity.Id); userInfo = LogOnService.ConvertToUserInfo(userInfo, userEntity, userLogOnEntity) userInfo.IPAddress = ipAddress userInfo.MACAddress = macAddress userInfo.Password = password #这里是判断用户是否为系统管理员的 userInfo.IsAdministrator = PermissionService.IsAdministrator( userEntity) ''' // 数据找到了,就可以退出循环了 /* // 获得员工的信息 if (userEntity.IsStaff == 1) { PiStaffManager staffManager = new PiStaffManager(DBProvider, UserInfo); //这里需要按 员工的用户ID来进行查找对应的员工-用户关系 PiStaffEntity staffEntity = new PiStaffEntity(staffManager.GetDT(PiStaffTable.FieldUserId, userEntity.Id)); if (!string.IsNullOrEmpty(staffEntity.Id)) { userInfo = staffManager.ConvertToUserInfo(staffEntity, userInfo); } }*/ ''' #记录系统访问日志 if ReturnStatusCode == StatusCode.statusCodeDic['OK']: if not userInfo.OpenId: createNewOpenId = True if createNewOpenId: userInfo.OpenId = LogOnService.UpdateVisitDate( userEntity.id, createNewOpenId) else: LogOnService.UpdateVisitDate(userEntity.id, createNewOpenId) return ReturnStatusCode, userInfo