/// <summary> /// 数据库连接,根据数据库类型自动识别,类型区分用配置名称是否包含主要关键字 /// MSSQL、MYSQL、ORACLE、SQLITE、MEMORY、NPGSQL /// </summary> /// <returns></returns> public DbConnection OpenSharedConnection() { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); object connCode = yuebonCacheHelper.Get("CodeGeneratorDbConn"); DbConnectionOptions dbConnectionOptions = DBServerProvider.GeDbConnectionOptions(); DatabaseType dbType = DatabaseType.SqlServer; if (connCode != null) { defaultSqlConnectionString = connCode.ToString(); string dbTypeCache = yuebonCacheHelper.Get("CodeGeneratorDbType").ToString(); dbType = (DatabaseType)Enum.Parse(typeof(DatabaseType), dbTypeCache); } else { defaultSqlConnectionString = dbConnectionOptions.ConnectionString; dbType = dbConnectionOptions.DatabaseType; TimeSpan expiresSliding = DateTime.Now.AddMinutes(30) - DateTime.Now; yuebonCacheHelper.Add("CodeGeneratorDbConn", defaultSqlConnectionString, expiresSliding, false); yuebonCacheHelper.Add("CodeGeneratorDbType", dbType, expiresSliding, false); } if (dbType == DatabaseType.SqlServer) { dbConnection = new SqlConnection(defaultSqlConnectionString); } else if (dbType == DatabaseType.MySql) { dbConnection = new MySqlConnection(defaultSqlConnectionString); } else if (dbType == DatabaseType.Oracle) { dbConnection = new OracleConnection(defaultSqlConnectionString); } else if (dbType == DatabaseType.SQLite) { dbConnection = new SqliteConnection(defaultSqlConnectionString); } else if (dbType == DatabaseType.Npgsql) { dbConnection = new NpgsqlConnection(defaultSqlConnectionString); } else { throw new NotSupportedException("The database is not supported"); } if (dbConnection.State != ConnectionState.Open) { dbConnection.Open(); } return(dbConnection); }
public async Task <IActionResult> GetListByParentEnCode(string enCode) { CommonResult result = new CommonResult(); try { if (CurrentUser != null) { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); List <MenuOutputDto> functions = new List <MenuOutputDto>(); functions = yuebonCacheHelper.Get("User_Function_" + CurrentUser.UserId).ToJson().ToObject <List <MenuOutputDto> >(); MenuOutputDto functionOutputDto = functions.Find(s => s.EnCode == enCode); List <MenuOutputDto> nowFunList = new List <MenuOutputDto>(); if (functionOutputDto != null) { nowFunList = functions.FindAll(s => s.ParentId == functionOutputDto.Id && s.IsShow && s.MenuType.Equals("F")).OrderBy(s => s.SortCode).ToList(); } result.ErrCode = ErrCode.successCode; result.ResData = nowFunList; } else { result.ErrCode = "40008"; result.ErrMsg = ErrCode.err40008; } } catch (Exception ex) { Log4NetHelper.Error("根据父级功能编码查询所有子集功能,主要用于页面操作按钮权限,代码生成异常", ex); result.ErrCode = ErrCode.failCode; result.ErrMsg = "获取模块功能异常"; } return(ToJsonContent(result)); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="mailBodyEntity">邮件基础信息</param> public static SendResultEntity SendMail(MailBodyEntity mailBodyEntity) { var sendResultEntity = new SendResultEntity(); if (mailBodyEntity == null) { throw new ArgumentNullException(); } SendServerConfigurationEntity sendServerConfiguration = new SendServerConfigurationEntity(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); AppSetting sysSetting = yuebonCacheHelper.Get <AppSetting>("SysSetting"); if (sysSetting != null) { sendServerConfiguration.SmtpHost = DEncrypt.Decrypt(sysSetting.Emailsmtp); sendServerConfiguration.SenderAccount = sysSetting.Emailusername; sendServerConfiguration.SenderPassword = DEncrypt.Decrypt(sysSetting.Emailpassword); sendServerConfiguration.SmtpPort = sysSetting.Emailport.ToInt(); sendServerConfiguration.IsSsl = sysSetting.Emailssl.ToBool(); sendServerConfiguration.MailEncoding = "utf-8"; mailBodyEntity.Sender = sysSetting.Emailnickname; mailBodyEntity.SenderAddress = sysSetting.Emailusername; } else { sendResultEntity.ResultInformation = "邮件服务器未配置"; sendResultEntity.ResultStatus = false; throw new ArgumentNullException(); } sendResultEntity = SendMail(mailBodyEntity, sendServerConfiguration); return(sendResultEntity); }
/// <summary> /// 获取当前登录用户的数据访问权限 /// </summary> /// <param name="blDeptCondition">是否开启,默认开启</param> /// <returns></returns> protected virtual string GetDataPrivilege(bool blDeptCondition = true) { string where = "1=1"; //开权限数据过滤 if (blDeptCondition) { var identities = HttpContextHelper.HttpContext.User.Identities; var claimsIdentity = identities.First <ClaimsIdentity>(); List <Claim> claimlist = claimsIdentity.Claims as List <Claim>; YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); if (claimlist[1].Value != "admin") { //如果公司过滤条件不为空,那么需要进行过滤 List <String> list = JsonSerializer.Deserialize <List <String> >(yuebonCacheHelper.Get("User_RoleData_" + claimlist[0].Value).ToJson()); if (list.Count() > 0) { string DataFilterCondition = String.Join(",", list.ToArray()); if (!string.IsNullOrEmpty(DataFilterCondition)) { where += string.Format(" and (DeptId in ('{0}') or CreatorUserId='{1}')", DataFilterCondition.Replace(",", "','"), claimlist[0].Value); } } else { where += string.Format(" and CreatorUserId='{0}'", claimlist[0].Value); } bool isMultiTenant = Configs.GetConfigurationValue("AppSetting", "IsMultiTenant").ToBool(); if (isMultiTenant) { where += string.Format(" and TenantId='{0}'", claimlist[3].Value); } } } return(where); }
public DbExtractor() { MssqlExtractor mssqlExtractor = new MssqlExtractor(); mssqlExtractor.OpenSharedConnection(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); string dbTypeCache = yuebonCacheHelper.Get("CodeGeneratorDbType").ToString(); if (dbTypeCache != null) { dbType = (DatabaseType)Enum.Parse(typeof(DatabaseType), dbTypeCache); } object odbn = yuebonCacheHelper.Get("CodeGeneratorDbName"); if (odbn != null) { dbName = odbn.ToString(); } }
/// <summary> /// 根据相关信息,写入用户的操作日志记录 /// </summary> /// <param name="tableName">操作表名称</param> /// <param name="operationType">操作类型</param> /// <param name="note">操作详细表述</param> /// <returns></returns> public bool OnOperationLog(string tableName, string operationType, string note) { try { //虽然实现了这个事件,但是我们还需要判断该表是否在配置表里面,如果不在,则不记录操作日志。 //var identities = _httpContextAccessor.HttpContext.User.Identities; if (HttpContextHelper.HttpContext == null) { return(false); } var identities = HttpContextHelper.HttpContext.User.Identities; var claimsIdentity = identities.First <ClaimsIdentity>(); List <Claim> claimlist = claimsIdentity.Claims as List <Claim>; string userId = claimlist[0].Value; YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); YuebonCurrentUser CurrentUser = new YuebonCurrentUser(); var user = yuebonCacheHelper.Get("login_user_" + userId).ToJson().ToObject <YuebonCurrentUser>(); if (user != null) { CurrentUser = user; bool insert = operationType == DbLogType.Create.ToString();; //&& settingInfo.InsertLog; bool update = operationType == DbLogType.Update.ToString(); // && settingInfo.UpdateLog; bool delete = operationType == DbLogType.Delete.ToString(); // && settingInfo.DeleteLog; bool deletesoft = operationType == DbLogType.DeleteSoft.ToString(); // && settingInfo.DeleteLog; bool exception = operationType == DbLogType.Exception.ToString(); // && settingInfo.DeleteLog; bool sql = operationType == DbLogType.SQL.ToString(); // && settingInfo.DeleteLog; if (insert || update || delete || deletesoft || exception || sql) { Log info = new Log(); info.ModuleName = tableName; info.Type = operationType; info.Description = note; info.Date = info.CreatorTime = DateTime.Now; info.CreatorUserId = CurrentUser.UserId; info.Account = CurrentUser.Account; info.NickName = CurrentUser.NickName; info.OrganizeId = CurrentUser.OrganizeId; info.IPAddress = CurrentUser.CurrentLoginIP; info.IPAddressName = CurrentUser.IPAddressName; info.Result = true; long lg = _iLogRepository.Insert(info); if (lg > 0) { return(true); } } } }catch (Exception ex) { Log4NetHelper.Error("", ex); return(false); } return(false); }
public AliYunSMS() { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); AppSetting sysSetting = yuebonCacheHelper.Get <AppSetting>("SysSetting"); if (sysSetting != null) { this.Appkey = DEncrypt.Decrypt(sysSetting.Smsusername); this.Appsecret = DEncrypt.Decrypt(sysSetting.Smspassword); this.SignName = sysSetting.SmsSignName; } }
/// <summary> /// 获取所有可用的地区,用于uniapp下拉选项 /// </summary> /// <returns></returns> public List <AreaPickerOutputDto> GetAllByEnable() { List <AreaPickerOutputDto> list = new List <AreaPickerOutputDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject <List <AreaPickerOutputDto> >(yuebonCacheHelper.Get("Area_Enable_Uniapp").ToJson()); if (list == null || list.Count <= 0) { List <Area> listFunction = _repository.GetAllByIsNotDeleteAndEnabledMark("Layers in (0,1,2)").OrderBy(t => t.SortCode).ToList(); list = UniappViewJson(listFunction, ""); yuebonCacheHelper.Add("Area_Enable_Uniapp", list); } return(list); }
/// <summary> /// 获取省可用的地区,用于select2下拉选项 /// </summary> /// <returns></returns> public List <AreaSelect2OutDto> GetProvinceAll() { List <AreaSelect2OutDto> list = new List <AreaSelect2OutDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject <List <AreaSelect2OutDto> >(yuebonCacheHelper.Get("Area_ProvinceToArea_Select2").ToJson()); if (list == null || list.Count <= 0) { list = service.GetAllByIsNotDeleteAndEnabledMark("Layers =1").OrderBy(t => t.Id).ToList().MapTo <AreaSelect2OutDto>(); yuebonCacheHelper.Add("Area_ProvinceToArea_Select2", list); } return(list); }
public override async Task <IActionResult> DeleteBatchAsync(DeletesInputDto info) { CommonResult result = new CommonResult(); string where = string.Empty; where = "id in ('" + info.Ids.Join(",").Trim(',').Replace(",", "','") + "')"; if (!string.IsNullOrEmpty(where)) { dynamic[] jobsId = info.Ids; foreach (var item in jobsId) { if (string.IsNullOrEmpty(item.ToString())) { continue; } UploadFile uploadFile = new UploadFileApp().Get(item.ToString()); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); if (uploadFile != null) { if (System.IO.File.Exists(sysSetting.LocalPath + "/" + uploadFile.FilePath)) { System.IO.File.Delete(sysSetting.LocalPath + "/" + uploadFile.FilePath); } if (!string.IsNullOrEmpty(uploadFile.Thumbnail)) { if (System.IO.File.Exists(sysSetting.LocalPath + "/" + uploadFile.Thumbnail)) { System.IO.File.Delete(sysSetting.LocalPath + "/" + uploadFile.Thumbnail); } } } } bool bl = await iService.DeleteBatchWhereAsync(where).ConfigureAwait(false); if (bl) { result.ErrCode = ErrCode.successCode; result.ErrMsg = ErrCode.err0; } else { result.ErrMsg = ErrCode.err43003; result.ErrCode = "43003"; } } return(ToJsonContent(result)); }
/// <summary> /// 获取县区,用于select2下拉选项 /// </summary> /// <param name="id">城市Id</param> /// <returns></returns> public List <AreaSelect2OutDto> GetDistrictByCityId(string id) { List <AreaSelect2OutDto> list = new List <AreaSelect2OutDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject <List <AreaSelect2OutDto> >(yuebonCacheHelper.Get("Area_DistrictToArea_Enable_Select2" + id).ToJson()); if (list == null || list.Count <= 0) { string sqlWhere = string.Format("ParentId='{0}'", id); list = service.GetAllByIsNotDeleteAndEnabledMark(sqlWhere).OrderBy(t => t.Id).ToList().MapTo <AreaSelect2OutDto>(); yuebonCacheHelper.Add("Area_DistrictToArea_Enable_Select2" + id, list); } return(list); }
public IActionResult GetAllInfo() { CommonResult result = new CommonResult(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); SysSettingOutputDto sysSettingOutputDto = new SysSettingOutputDto(); if (sysSetting == null) { sysSetting = XmlConverter.Deserialize <SysSetting>("xmlconfig/sys.config"); } //对关键信息解密 if (!string.IsNullOrEmpty(sysSetting.Email)) { sysSetting.Email = DEncrypt.Decrypt(sysSetting.Email); } if (!string.IsNullOrEmpty(sysSetting.Emailsmtp)) { sysSetting.Emailsmtp = DEncrypt.Decrypt(sysSetting.Emailsmtp); } if (!string.IsNullOrEmpty(sysSetting.Emailpassword)) { sysSetting.Emailpassword = DEncrypt.Decrypt(sysSetting.Emailpassword); } if (!string.IsNullOrEmpty(sysSetting.Smspassword)) { sysSetting.Smspassword = DEncrypt.Decrypt(sysSetting.Smspassword); } if (!string.IsNullOrEmpty(sysSetting.Smsusername)) { sysSetting.Smsusername = DEncrypt.Decrypt(sysSetting.Smsusername); } sysSettingOutputDto = sysSetting.MapTo <SysSettingOutputDto>(); if (sysSettingOutputDto != null) { sysSettingOutputDto.CopyRight = UIConstants.CopyRight; result.ResData = sysSettingOutputDto; result.Success = true; result.ErrCode = ErrCode.successCode; } else { result.ErrMsg = ErrCode.err60001; result.ErrCode = "60001"; } return(ToJsonContent(result)); }
public CommonResult <PageResult <DbTableInfo> > FindListTable(SearchModel search) { CommonResult <PageResult <DbTableInfo> > result = new CommonResult <PageResult <DbTableInfo> >(); if (!string.IsNullOrEmpty(search.EnCode)) { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); object connCode = yuebonCacheHelper.Get("CodeGeneratorDbConn"); if (connCode != null) { string SqlConnectionString = connCode.ToString(); string[] sqlconn = SqlConnectionString.Split(";"); string[] dataName = sqlconn[1].Split("="); dataName[1] = search.EnCode; sqlconn[1] = dataName.Join("="); string newConnStr = sqlconn.Join(";"); TimeSpan expiresSliding = DateTime.Now.AddMinutes(30) - DateTime.Now; yuebonCacheHelper.Add("CodeGeneratorDbConn", newConnStr, expiresSliding, false); yuebonCacheHelper.Add("CodeGeneratorDbName", search.EnCode, expiresSliding, false); } } string orderByDir = search.Order; string orderFlied = string.IsNullOrEmpty(search.Sort)? "TableName": search.Sort; bool order = orderByDir == "asc" ? false : true; string where = "1=1"; if (!string.IsNullOrEmpty(search.Keywords)) { where += " and TableName like '%" + search.Keywords + "%'"; } PagerInfo pagerInfo = new PagerInfo { PageSize = search.PageSize, CurrenetPageIndex = search.CurrenetPageIndex }; DbExtractor dbExtractor = new DbExtractor(); List <DbTableInfo> listTable = dbExtractor.GetTablesWithPage(search.Keywords, orderFlied, order, pagerInfo); PageResult <DbTableInfo> pageResult = new PageResult <DbTableInfo>(); pageResult.CurrentPage = pagerInfo.CurrenetPageIndex; pageResult.Items = listTable; pageResult.ItemsPerPage = pagerInfo.PageSize; pageResult.TotalItems = pagerInfo.RecordCount; result.ResData = pageResult; result.ErrCode = ErrCode.successCode; return(result); }
/// <summary> /// 验证appId是否被允许 /// </summary> /// <param name="appId"></param> /// <returns></returns> private static AllowCacheApp VerifyAppId(string appId) { AllowCacheApp allowCacheApp = new AllowCacheApp(); if (string.IsNullOrEmpty(appId)) { return(allowCacheApp); } YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); List <AllowCacheApp> list = yuebonCacheHelper.Get("AllowAppId").ToJson().ToList <AllowCacheApp>(); if (list.Count > 0) { allowCacheApp = list.Where(s => s.AppId == appId).FirstOrDefault(); } return(allowCacheApp); }
public IActionResult DeleteFile(string id) { CommonResult result = new CommonResult(); try { UploadFile uploadFile = new UploadFileApp().Get(id); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); string localpath = _hostingEnvironment.WebRootPath; if (uploadFile != null) { string filepath = (localpath + "/" + uploadFile.FilePath).ToFilePath(); if (System.IO.File.Exists(filepath)) { System.IO.File.Delete(filepath); } string filepathThu = (localpath + "/" + uploadFile.Thumbnail).ToFilePath(); if (System.IO.File.Exists(filepathThu)) { System.IO.File.Delete(filepathThu); } result.ErrCode = ErrCode.successCode; result.Success = true; } else { result.ErrCode = ErrCode.failCode; result.Success = false; } } catch (Exception ex) { Log4NetHelper.Error("", ex); result.ErrCode = "500"; result.ErrMsg = ex.Message; } return(ToJsonContent(result)); }
public IActionResult GetInfo() { CommonResult result = new CommonResult(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); SysSettingOutputDto sysSettingOutputDto = new SysSettingOutputDto(); if (sysSetting == null) { sysSetting = XmlConverter.Deserialize <SysSetting>("xmlconfig/sys.config"); } sysSetting.Email = ""; sysSetting.Emailsmtp = ""; sysSetting.Emailpassword = ""; sysSetting.Smspassword = ""; sysSetting.SmsSignName = ""; sysSetting.Smsusername = ""; sysSettingOutputDto = sysSetting.MapTo <SysSettingOutputDto>(); if (sysSettingOutputDto != null) { sysSettingOutputDto.CopyRight = UIConstants.CopyRight; result.ResData = sysSettingOutputDto; result.Success = true; result.ErrCode = ErrCode.successCode; } else { result.ErrMsg = ErrCode.err60001; result.ErrCode = "60001"; } IEnumerable <APP> appList = aPPService.GetAllByIsNotDeleteAndEnabledMark(); yuebonCacheHelper.Add("AllowAppId", appList); return(ToJsonContent(result)); }
/// <summary> /// 获取省、市、县/区三级可用的地区,用于uniapp下拉选项 /// </summary> /// <returns></returns> public List <AreaPickerOutputDto> GetProvinceToAreaByEnable() { List <AreaPickerOutputDto> list = new List <AreaPickerOutputDto>(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); list = JsonConvert.DeserializeObject <List <AreaPickerOutputDto> >(yuebonCacheHelper.Get("Area_ProvinceToArea_Enable_Uniapp").ToJson()); if (list == null || list.Count <= 0) { List <Area> listFunctionTemp = _repository.GetAllByIsNotDeleteAndEnabledMark("Layers in (1,2,3)").OrderBy(t => t.Id).ToList(); List <Area> listFunction = new List <Area>(); foreach (Area item in listFunctionTemp) { if (item.Layers == 1) { item.ParentId = ""; } listFunction.Add(item); } list = UniappViewJson(listFunction, ""); yuebonCacheHelper.Add("Area_ProvinceToArea_Enable_Uniapp", list); } return(list); }
public Task Execute(IJobExecutionContext context) { DateTime dateTime = DateTime.Now; YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger; string sqlWhere = string.Format("Id='{0}' and GroupName='{1}'", trigger.Name, trigger.Group); TaskManager taskManager = iService.GetWhere(sqlWhere); if (taskManager == null) { FileQuartz.WriteErrorLog($"任务不存在"); return(Task.Delay(1)); } try { string msg = $"开始时间:{dateTime.ToString("yyyy-MM-dd HH:mm:ss ffff")}"; //记录任务执行记录 iService.RecordRun(taskManager.Id, JobAction.开始, true, msg); //初始化任务日志 FileQuartz.InitTaskJobLogPath(taskManager.Id); var jobId = context.MergedJobDataMap.GetString("OpenJob"); //todo:这里可以加入自己的自动任务逻辑 Log4NetHelper.Info(DateTime.Now.ToString() + "执行任务"); stopwatch.Stop(); string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n"; iService.RecordRun(taskManager.Id, JobAction.结束, true, content); if ((MsgType)taskManager.SendMail == MsgType.All) { string emailAddress = sysSetting.Email; if (!string.IsNullOrEmpty(taskManager.EmailAddress)) { emailAddress = taskManager.EmailAddress; } List <string> recipients = new List <string>(); recipients = emailAddress.Split(",").ToList(); var mailBodyEntity = new MailBodyEntity() { Body = msg + content + ",请勿回复本邮件", Recipients = recipients, Subject = taskManager.TaskName }; SendMailHelper.SendMail(mailBodyEntity); } } catch (Exception ex) { stopwatch.Stop(); string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n"; iService.RecordRun(taskManager.Id, JobAction.结束, false, content + ex.Message); FileQuartz.WriteErrorLog(ex.Message); if ((MsgType)taskManager.SendMail == MsgType.Error || (MsgType)taskManager.SendMail == MsgType.All) { string emailAddress = sysSetting.Email; if (!string.IsNullOrEmpty(taskManager.EmailAddress)) { emailAddress = taskManager.EmailAddress; } List <string> recipients = new List <string>(); recipients = emailAddress.Split(",").ToList(); var mailBodyEntity = new MailBodyEntity() { Body = "处理失败," + ex.Message + ",请勿回复本邮件", Recipients = recipients, Subject = taskManager.TaskName }; SendMailHelper.SendMail(mailBodyEntity); } } return(Task.Delay(1)); }
public IActionResult OnLogin(string code) { CommonResult result = new CommonResult(); try { var jsonResult = SnsApi.JsCode2Json(WxOpenAppId, WxOpenAppSecret, code); if (jsonResult.errcode == ReturnCode.请求成功) { //使用SessionContainer管理登录信息(推荐) var unionId = jsonResult.unionid; var sessionBag = SessionContainer.UpdateSession(null, jsonResult.openid, jsonResult.session_key, unionId); //注意:生产环境下SessionKey属于敏感信息,不能进行传输! //return Json(new { success = true, msg = "OK", sessionId = sessionBag.Key, sessionKey = sessionBag.SessionKey }); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); //User user = userApp.GetUserByUnionId(unionId); User user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid); if (user == null) { UserInputDto userInput = new UserInputDto(); userInput.OpenId = jsonResult.openid; user.UnionId = jsonResult.unionid; userInput.OpenIdType = "yuebon.openid.wxapplet"; userInput.NickName = "游客"; userInput.UnionId = jsonResult.unionid; result.Success = userService.CreateUserByWxOpenId(userInput); } //针对老用户更新UnionId if (user != null && string.IsNullOrEmpty(user.UnionId)) { user.UnionId = jsonResult.unionid; result.Success = userService.Update(user, user.Id); } string userId = string.Empty; if (result.ResData != null) { userId = result.ResData.ToString(); } if (user == null) { user = userService.GetUserByOpenId("yuebon.openid.wxapplet", jsonResult.openid); } var currentSession = (YuebonCurrentUser)(yuebonCacheHelper.Get("login_user_" + userId)); if (currentSession == null || string.IsNullOrWhiteSpace(currentSession.AccessToken)) { JwtOption jwtModel = App.GetService <JwtOption>(); TokenProvider tokenProvider = new TokenProvider(jwtModel); TokenResult tokenResult = tokenProvider.LoginToken(user, "wxapplet"); currentSession = new YuebonCurrentUser { UserId = user.Id, Account = user.Account, Name = user.RealName, NickName = user.NickName, AccessToken = tokenResult.AccessToken, AppKey = "wxapplet", CreateTime = DateTime.Now, HeadIcon = user.HeadIcon, Gender = user.Gender, ReferralUserId = user.ReferralUserId, MemberGradeId = user.MemberGradeId, Role = roleService.GetRoleEnCode(user.RoleId), MobilePhone = user.MobilePhone, WxSessionId = sessionBag.Key }; TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now; yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true); } CurrentUser = currentSession; result.ResData = currentSession; //new AuthorizeApp().GetAccessedControls(user.Account); result.ErrCode = ErrCode.successCode; result.Success = true; } else { result.ErrCode = ErrCode.failCode; result.ErrMsg = jsonResult.errmsg; } } catch (Exception ex) { result.ErrMsg = ex.Message; } return(ToJsonContent(result)); }
/// <summary> /// 执行远程接口url的定时任务 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task Execute(IJobExecutionContext context) { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger; string sqlWhere = string.Format("Id='{0}' and GroupName='{1}'", trigger.Name, trigger.Group); TaskManager taskManager = iService.GetWhere(sqlWhere); string httpMessage = ""; if (taskManager == null) { FileQuartz.WriteErrorLog($"任务不存在"); return(Task.Delay(1)); } FileQuartz.InitTaskJobLogPath(taskManager.Id); string msg = $"开始时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}"; //记录任务执行记录 iService.RecordRun(taskManager.Id, JobAction.开始, true, msg); if (string.IsNullOrEmpty(taskManager.JobCallAddress) || taskManager.JobCallAddress == "/") { FileQuartz.WriteErrorLog($"{ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}未配置任务地址,"); iService.RecordRun(taskManager.Id, JobAction.结束, false, "未配置任务地址"); return(Task.Delay(1)); } try { Dictionary <string, string> header = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(taskManager.JobCallParams)) { httpMessage = HttpRequestHelper.HttpPost(taskManager.JobCallAddress, taskManager.JobCallParams, null, header); } else { httpMessage = HttpRequestHelper.HttpGet(taskManager.JobCallAddress); } stopwatch.Stop(); string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒,消息:{httpMessage??"OK"}\r\n"; iService.RecordRun(taskManager.Id, JobAction.结束, true, content); if ((MsgType)taskManager.SendMail == MsgType.All) { string emailAddress = sysSetting.Email; if (!string.IsNullOrEmpty(taskManager.EmailAddress)) { emailAddress = taskManager.EmailAddress; } List <string> recipients = new List <string>(); recipients = taskManager.EmailAddress.Split(",").ToList(); //recipients.Add(taskManager.EmailAddress); var mailBodyEntity = new MailBodyEntity() { Body = content + "\n\r请勿直接回复本邮件!", Recipients = recipients, Subject = taskManager.TaskName, }; SendMailHelper.SendMail(mailBodyEntity); } } catch (Exception ex) { stopwatch.Stop(); string content = $"结束时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")} 共耗时{stopwatch.ElapsedMilliseconds} 毫秒\r\n"; iService.RecordRun(taskManager.Id, JobAction.结束, false, content + ex.Message); FileQuartz.WriteErrorLog(ex.Message); if ((MsgType)taskManager.SendMail == MsgType.Error || (MsgType)taskManager.SendMail == MsgType.All) { string emailAddress = sysSetting.Email; if (!string.IsNullOrEmpty(taskManager.EmailAddress)) { emailAddress = taskManager.EmailAddress; } List <string> recipients = new List <string>(); recipients = emailAddress.Split(",").ToList(); var mailBodyEntity = new MailBodyEntity() { Body = ex.Message + "\n\r请勿直接回复本邮件!", Recipients = recipients, Subject = taskManager.TaskName, }; SendMailHelper.SendMail(mailBodyEntity); } } return(Task.Delay(1)); }
public IActionResult LoginByOpenId(string openId) { CommonResult result = new CommonResult(); try { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); User user = userService.GetUserByOpenId("yuebon.openid.wxapplet", openId); if (user == null) { UserInputDto userInput = new UserInputDto(); userInput.OpenId = openId; userInput.OpenIdType = "yuebon.openid.wxapplet"; userInput.NickName = "游客"; result.Success = userService.CreateUserByWxOpenId(userInput); } string userId = string.Empty; if (result.ResData != null) { userId = result.ResData.ToString(); } if (user == null) { user = userService.GetUserByOpenId("yuebon.openid.wxapplet", openId); } var currentSession = (YuebonCurrentUser)yuebonCacheHelper.Get("login_user_" + user.Id); if (currentSession == null || string.IsNullOrWhiteSpace(currentSession.AccessToken)) { JwtOption jwtModel = App.GetService <JwtOption>(); TokenProvider tokenProvider = new TokenProvider(jwtModel); TokenResult tokenResult = tokenProvider.LoginToken(user, "wxapplet"); currentSession = new YuebonCurrentUser { UserId = user.Id, Account = user.Account, Name = user.RealName, NickName = user.NickName, AccessToken = tokenResult.AccessToken, AppKey = "wxapplet", CreateTime = DateTime.Now, HeadIcon = user.HeadIcon, Gender = user.Gender, ReferralUserId = user.ReferralUserId, MemberGradeId = user.MemberGradeId, Role = roleService.GetRoleEnCode(user.RoleId), MobilePhone = user.MobilePhone }; TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now; yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true); } CurrentUser = currentSession; result.ErrCode = ErrCode.successCode; result.Success = true; result.ResData = currentSession; //new AuthorizeApp().GetAccessedControls(user.Account); } catch (Exception ex) { Log4NetHelper.Error("微信登录异常 LoginByOpenId", ex); result.ErrMsg = "微信登录异常:" + ex.Message; result.ErrCode = ErrCode.successCode; } return(ToJsonContent(result)); }
/// <summary> /// 实现文件上传到服务器保存,并生成缩略图 /// </summary> /// <param name="fileName">文件名称</param> /// <param name="fileBuffers">文件字节流</param> private void UploadFile(string fileName, byte[] fileBuffers) { //判断文件是否为空 if (string.IsNullOrEmpty(fileName)) { Log4NetHelper.Info("文件名不能为空"); throw new Exception("文件名不能为空"); } //判断文件是否为空 if (fileBuffers.Length < 1) { Log4NetHelper.Info("文件不能为空"); throw new Exception("文件不能为空"); } YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); SysSetting sysSetting = yuebonCacheHelper.Get("SysSetting").ToJson().ToObject <SysSetting>(); string folder = DateTime.Now.ToString("yyyyMMdd"); _filePath = _hostingEnvironment.WebRootPath; var _tempfilepath = sysSetting.Filepath; if (!string.IsNullOrEmpty(_belongApp)) { _tempfilepath += "/" + _belongApp; } if (!string.IsNullOrEmpty(_belongAppId)) { _tempfilepath += "/" + _belongAppId; } if (sysSetting.Filesave == "1") { _tempfilepath = _tempfilepath + "/" + folder + "/"; } if (sysSetting.Filesave == "2") { DateTime date = DateTime.Now; _tempfilepath = _tempfilepath + "/" + date.Year + "/" + date.Month + "/" + date.Day + "/"; } var uploadPath = _filePath + "/" + _tempfilepath; if (sysSetting.Fileserver == "localhost") { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } } string ext = Path.GetExtension(fileName).ToLower(); string newName = GuidUtils.CreateNo(); string newfileName = newName + ext; using (var fs = new FileStream(uploadPath + newfileName, FileMode.Create)) { fs.Write(fileBuffers, 0, fileBuffers.Length); fs.Close(); //生成缩略图 if (ext.Contains(".jpg") || ext.Contains(".jpeg") || ext.Contains(".png") || ext.Contains(".bmp") || ext.Contains(".gif")) { string thumbnailName = newName + "_" + sysSetting.Thumbnailwidth + "x" + sysSetting.Thumbnailheight + ext; ImgHelper.MakeThumbnail(uploadPath + newfileName, uploadPath + thumbnailName, sysSetting.Thumbnailwidth.ToInt(), sysSetting.Thumbnailheight.ToInt()); _dbThumbnail = _tempfilepath + thumbnailName; } _dbFilePath = _tempfilepath + newfileName; } }
/// <summary> /// 重写基类在Action执行之前的事情 /// 根据token获得当前用户,允许匿名的不需要获取用户 /// </summary> /// <param name="context">重写方法的参数</param> public override void OnActionExecuting(ActionExecutingContext context) { try { var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor; //匿名访问,不需要token认证、签名和登录 var allowanyone = controllerActionDescriptor.MethodInfo.GetCustomAttribute(typeof(AllowAnonymousAttribute), true); if (allowanyone != null) { return; } CommonResult result = new CommonResult(); //需要token认证 string authHeader = context.HttpContext.Request.Headers["Authorization"];//Header中的token if (string.IsNullOrEmpty(authHeader)) { result.ErrCode = "40004"; result.ErrMsg = ErrCode.err40004; context.Result = ToJsonContent(result); return; } else { string token = string.Empty; if (authHeader != null && authHeader.StartsWith("Bearer ", StringComparison.Ordinal)) { token = authHeader.Substring(7); } TokenProvider tokenProvider = new TokenProvider(); result = tokenProvider.ValidateToken(token); //token验证失败 if (!result.Success) { context.Result = ToJsonContent(result); } else { #region 签名验证 bool boolSign = context.HttpContext.Request.Headers["sign"].SingleOrDefault().ToBool(true); var isSign = controllerActionDescriptor.MethodInfo.GetCustomAttribute(typeof(NoSignRequiredAttribute), true); //需要签名验证 if (isSign == null && boolSign) { CommonResult resultSign = SignHelper.CheckSign(context.HttpContext); if (!resultSign.Success) { context.Result = ToJsonContent(resultSign); return; } } #endregion #region 是否需要验证用户登录以及相关的功能权限 //是否需要用户登录 var isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttribute(typeof(NoPermissionRequiredAttribute)); //不需要登录 if (isDefined != null) { return; } //需要登录和验证功能权限 if (result.ResData != null) { List <Claim> claimlist = result.ResData as List <Claim>; string userId = claimlist[3].Value; var claims = new[] { new Claim(YuebonClaimTypes.UserId, userId), new Claim(YuebonClaimTypes.UserName, claimlist[2].Value), new Claim(YuebonClaimTypes.Role, claimlist[4].Value) }; var identity = new ClaimsIdentity(claims); var principal = new ClaimsPrincipal(identity); context.HttpContext.User = principal; YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); var user = yuebonCacheHelper.Get <YuebonCurrentUser>("login_user_" + userId); if (user != null) { CurrentUser = user; } bool isAdmin = Permission.IsAdmin(user); if (!isAdmin) { var authorizeAttributes = controllerActionDescriptor.MethodInfo.GetCustomAttributes(typeof(YuebonAuthorizeAttribute), true).OfType <YuebonAuthorizeAttribute>(); if (authorizeAttributes.FirstOrDefault() != null) { string function = authorizeAttributes.First().Function; if (!string.IsNullOrEmpty(function)) { string functionCode = controllerActionDescriptor.ControllerName + "/" + function; bool bl = Permission.HasFunction(functionCode, userId); if (!bl) { result.ErrCode = "40006"; result.ErrMsg = ErrCode.err40006; context.Result = ToJsonContent(result); } } } } return; } else { result.ErrCode = "40008"; result.ErrMsg = ErrCode.err40008; context.Result = ToJsonContent(result); } #endregion } return; } } catch (Exception ex) { Log4NetHelper.Error("", ex); } }
public async Task <IActionResult> GetCheckUser(string username, string password, string vcode, string vkey, string appId, string systemCode) { CommonResult result = new CommonResult(); RemoteIpParser remoteIpParser = new RemoteIpParser(); string strIp = remoteIpParser.GetClientIp(HttpContext).MapToIPv4().ToString(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); var vCode = yuebonCacheHelper.Get("ValidateCode" + vkey); string code = vCode != null?vCode.ToString() : "11"; if (vcode.ToUpper() != code) { result.ErrMsg = "验证码错误"; return(ToJsonContent(result)); } Log logEntity = new Log(); bool blIp = _filterIPService.ValidateIP(strIp); if (blIp) { result.ErrMsg = strIp + "该IP已被管理员禁止登录!"; } else { if (string.IsNullOrEmpty(username)) { result.ErrMsg = "用户名不能为空!"; } else if (string.IsNullOrEmpty(password)) { result.ErrMsg = "密码不能为空!"; } if (string.IsNullOrEmpty(systemCode)) { result.ErrMsg = ErrCode.err40006; } else { string strHost = Request.Host.ToString(); APP app = _appService.GetAPP(appId); if (app == null) { result.ErrCode = "40001"; result.ErrMsg = ErrCode.err40001; } else { if (!app.RequestUrl.Contains(strHost, StringComparison.Ordinal) && !strHost.Contains("localhost", StringComparison.Ordinal)) { result.ErrCode = "40002"; result.ErrMsg = ErrCode.err40002 + ",你当前请求主机:" + strHost; } else { SystemType systemType = _systemTypeService.GetByCode(systemCode); if (systemType == null) { result.ErrMsg = ErrCode.err40006; } else { Tuple <User, string> userLogin = await this._userService.Validate(username, password); if (userLogin != null) { string ipAddressName = IpAddressUtil.GetCityByIp(strIp); if (userLogin.Item1 != null) { result.Success = true; User user = userLogin.Item1; JwtOption jwtModel = App.GetService <JwtOption>(); TokenProvider tokenProvider = new TokenProvider(jwtModel); TokenResult tokenResult = tokenProvider.LoginToken(user, appId); YuebonCurrentUser currentSession = new YuebonCurrentUser { UserId = user.Id, Name = user.RealName, AccessToken = tokenResult.AccessToken, AppKey = appId, CreateTime = DateTime.Now, Role = _roleService.GetRoleEnCode(user.RoleId), ActiveSystemId = systemType.Id, CurrentLoginIP = strIp, IPAddressName = ipAddressName }; TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now; yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true); List <AllowCacheApp> list = yuebonCacheHelper.Get("AllowAppId").ToJson().ToList <AllowCacheApp>(); if (list.Count == 0) { IEnumerable <APP> appList = _appService.GetAllByIsNotDeleteAndEnabledMark(); yuebonCacheHelper.Add("AllowAppId", appList); } CurrentUser = currentSession; result.ResData = currentSession; result.ErrCode = ErrCode.successCode; result.Success = true; logEntity.Account = user.Account; logEntity.NickName = user.NickName; logEntity.Date = logEntity.CreatorTime = DateTime.Now; logEntity.IPAddress = CurrentUser.CurrentLoginIP; logEntity.IPAddressName = CurrentUser.IPAddressName; logEntity.Result = true; logEntity.ModuleName = "登录"; logEntity.Description = "登录成功"; logEntity.Type = "Login"; _logService.Insert(logEntity); } else { result.ErrCode = ErrCode.failCode; result.ErrMsg = userLogin.Item2; logEntity.Account = username; logEntity.Date = logEntity.CreatorTime = DateTime.Now; logEntity.IPAddress = strIp; logEntity.IPAddressName = ipAddressName; logEntity.Result = false; logEntity.ModuleName = "登录"; logEntity.Type = "Login"; logEntity.Description = "登录失败," + userLogin.Item2; _logService.Insert(logEntity); } } } } } } } yuebonCacheHelper.Remove("LoginValidateCode"); return(ToJsonContent(result, true)); }
public async Task <IActionResult> RegisterAsync(RegisterViewModel info) { CommonResult result = new CommonResult(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); var vCode = yuebonCacheHelper.Get("ValidateCode" + info.VerifyCodeKey); string code = vCode != null?vCode.ToString() : "11"; if (code != info.VerificationCode.ToUpper()) { result.ErrMsg = "验证码错误"; return(ToJsonContent(result)); } if (!string.IsNullOrEmpty(info.Account)) { if (string.IsNullOrEmpty(info.Password) || info.Password.Length < 6) { result.ErrMsg = "密码不能为空或小于6位"; return(ToJsonContent(result)); } Tenant user = await iService.GetByUserName(info.Account); if (user != null) { result.ErrMsg = "登录账号不能重复"; return(ToJsonContent(result)); } } else { result.ErrMsg = "登录账号不能为空"; return(ToJsonContent(result)); } Tenant tenant = new Tenant(); tenant.Id = GuidUtils.CreateNo(); tenant.TenantName = info.Account; tenant.Email = info.Email; tenant.CreatorTime = DateTime.Now; tenant.EnabledMark = true; tenant.DeleteMark = false; TenantLogon tenantLogon = new TenantLogon(); tenantLogon.TenantPassword = info.Password; tenantLogon.AllowStartTime = tenantLogon.LockEndDate = tenantLogon.LockStartDate = tenantLogon.ChangePasswordDate = DateTime.Now; tenantLogon.AllowEndTime = DateTime.Now.AddYears(100); tenantLogon.MultiUserLogin = tenantLogon.CheckIPAddress = false; tenantLogon.LogOnCount = 0; result.Success = await iService.InsertAsync(tenant, tenantLogon); if (result.Success) { yuebonCacheHelper.Remove("ValidateCode"); result.ErrCode = ErrCode.successCode; result.ErrMsg = ErrCode.err0; } else { result.ErrMsg = ErrCode.err43001; result.ErrCode = "43001"; } return(ToJsonContent(result)); }
public IActionResult SysConnect(string openmf, string appId, string systemCode) { CommonResult result = new CommonResult(); RemoteIpParser remoteIpParser = new RemoteIpParser(); string strIp = remoteIpParser.GetClientIp(HttpContext).MapToIPv4().ToString(); if (string.IsNullOrEmpty(openmf)) { result.ErrMsg = "切换参数错误!"; } bool blIp = _filterIPService.ValidateIP(strIp); if (blIp) { result.ErrMsg = strIp + "该IP已被管理员禁止登录!"; } else { string ipAddressName = IpAddressUtil.GetCityByIp(strIp); if (string.IsNullOrEmpty(systemCode)) { result.ErrMsg = ErrCode.err40006; } else { string strHost = Request.Host.ToString(); APP app = _appService.GetAPP(appId); if (app == null) { result.ErrCode = "40001"; result.ErrMsg = ErrCode.err40001; } else { if (!app.RequestUrl.Contains(strHost, StringComparison.Ordinal) && !strHost.Contains("localhost", StringComparison.Ordinal)) { result.ErrCode = "40002"; result.ErrMsg = ErrCode.err40002 + ",你当前请求主机:" + strHost; } else { SystemType systemType = _systemTypeService.GetByCode(systemCode); if (systemType == null) { result.ErrMsg = ErrCode.err40006; } else { YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); object cacheOpenmf = yuebonCacheHelper.Get("openmf" + openmf); yuebonCacheHelper.Remove("openmf" + openmf); if (cacheOpenmf == null) { result.ErrCode = "40007"; result.ErrMsg = ErrCode.err40007; } else { User user = _userService.Get(cacheOpenmf.ToString()); if (user != null) { result.Success = true; JwtOption jwtModel = App.GetService <JwtOption>(); TokenProvider tokenProvider = new TokenProvider(jwtModel); TokenResult tokenResult = tokenProvider.LoginToken(user, appId); YuebonCurrentUser currentSession = new YuebonCurrentUser { UserId = user.Id, Name = user.RealName, AccessToken = tokenResult.AccessToken, AppKey = appId, CreateTime = DateTime.Now, Role = _roleService.GetRoleEnCode(user.RoleId), ActiveSystemId = systemType.Id, CurrentLoginIP = strIp, IPAddressName = ipAddressName, ActiveSystemUrl = systemType.Url }; TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now; yuebonCacheHelper.Add("login_user_" + user.Id, currentSession, expiresSliding, true); CurrentUser = currentSession; result.ResData = currentSession; result.ErrCode = ErrCode.successCode; result.Success = true; } else { result.ErrCode = ErrCode.failCode; } } } } } } } return(ToJsonContent(result)); }
/// <summary> /// 全局过滤器验证签名 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> public static CommonResult CheckSign(HttpContext httpContext) { CommonResult result = new CommonResult(); //从http请求的头里面获取参数 var request = httpContext.Request; var appId = ""; //客户端应用唯一标识 string nonce = ""; //随机字符串 var signature = ""; //参数签名,去除空参数,按字母倒序排序进行Md5签名 为了提高传参过程中,防止参数被恶意修改,在请求接口的时候加上sign可以有效防止参数被篡改 long timeStamp; //时间戳, 校验5分钟内有效 try { appId = request.Headers["appId"].SingleOrDefault(); nonce = request.Headers["nonce"].SingleOrDefault(); timeStamp = Convert.ToInt64(request.Headers["timeStamp"].SingleOrDefault()); signature = request.Headers["signature"].SingleOrDefault(); } catch (Exception ex) { result.ErrCode = "40004"; result.ErrMsg = "签名参数异常:" + ex.Message; return(result); } //appId是否为可用的 AllowCacheApp allowCacheApp = VerifyAppId(appId); if (allowCacheApp == null) { result.ErrCode = "40004"; result.ErrMsg = "AppId不被允许访问:" + appId; return(result); } //判断timespan是否有效,请求是否超时 DateTime tonow = timeStamp.UnixTimeToDateTime(); var expires_minute = tonow.Minute - DateTime.Now.Minute; if (expires_minute > 5 || expires_minute < -5) { result.ErrCode = "40004"; result.ErrMsg = "接口请求超时"; return(result); } //根据请求类型拼接参数 NameValueCollection form = HttpUtility.ParseQueryString(request.QueryString.ToString()); var data = string.Empty; if (form.Count > 0) { data = GetQueryString(form); } else { //request.EnableBuffering(); request.Body.Seek(0, SeekOrigin.Begin); Stream stream = request.Body; StreamReader streamReader = new StreamReader(stream); data = streamReader.ReadToEndAsync().Result; request.Body.Seek(0, SeekOrigin.Begin); } YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); object reqtimeStampCache = yuebonCacheHelper.Get("request_" + timeStamp + nonce); if (reqtimeStampCache != null) { result.ErrCode = "40004"; result.ErrMsg = "无效签名"; return(result); } TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now; yuebonCacheHelper.Add("request_" + timeStamp + nonce, timeStamp + nonce, expiresSliding); bool blValidate = Validate(timeStamp.ToString(), nonce, allowCacheApp.AppSecret, data, signature); if (!blValidate) { result.ErrCode = "40004"; result.ErrMsg = "无效签名"; return(result); } else { result.ErrCode = "0"; result.Success = true; return(result); } }
public async Task <IActionResult> RegisterAsync(RegisterViewModel tinfo) { CommonResult result = new CommonResult(); YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); var vCode = yuebonCacheHelper.Get("ValidateCode" + tinfo.VerifyCodeKey); string code = vCode != null?vCode.ToString() : "11"; if (code != tinfo.VerificationCode.ToUpper()) { result.ErrMsg = "验证码错误"; return(ToJsonContent(result)); } if (!string.IsNullOrEmpty(tinfo.Account)) { if (string.IsNullOrEmpty(tinfo.Password) || tinfo.Password.Length < 6) { result.ErrMsg = "密码不能为空或小于6位"; return(ToJsonContent(result)); } User user = await iService.GetByUserName(tinfo.Account); if (user != null) { result.ErrMsg = "登录账号不能重复"; return(ToJsonContent(result)); } } else { result.ErrMsg = "登录账号不能为空"; return(ToJsonContent(result)); } User info = new User(); info.Id = GuidUtils.CreateNo(); info.Account = tinfo.Account; info.Email = tinfo.Email; info.CreatorTime = DateTime.Now; info.CreatorUserId = info.Id; info.OrganizeId = ""; info.EnabledMark = true; info.IsAdministrator = false; info.IsMember = true; info.RoleId = roleService.GetRole("usermember").Id; info.DeleteMark = false; info.SortCode = 99; UserLogOn userLogOn = new UserLogOn(); userLogOn.UserPassword = tinfo.Password; userLogOn.AllowStartTime = userLogOn.LockEndDate = userLogOn.LockStartDate = userLogOn.ChangePasswordDate = DateTime.Now; userLogOn.AllowEndTime = DateTime.Now.AddYears(100); userLogOn.MultiUserLogin = userLogOn.CheckIPAddress = false; userLogOn.LogOnCount = 0; result.Success = await iService.InsertAsync(info, userLogOn); if (result.Success) { yuebonCacheHelper.Remove("ValidateCode"); result.ErrCode = ErrCode.successCode; result.ErrMsg = ErrCode.err0; } else { result.ErrMsg = ErrCode.err43001; result.ErrCode = "43001"; } return(ToJsonContent(result)); }
/// <summary> /// /// </summary> /// <param name="context"></param> public override void OnException(ExceptionContext context) { var exception = context.Exception; YuebonCurrentUser currentUser = new YuebonCurrentUser(); string requestPath = context.HttpContext.Request.Path.ToString(); string queryString = context.HttpContext.Request.QueryString.ToString(); var type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType; string exDesc = requestPath + queryString; Log4NetHelper.Error(type, "全局捕获程序运行异常信息\n\r" + exDesc, context.Exception); CommonResult result = new CommonResult(); if (exception is MyApiException myApiex) { context.HttpContext.Response.StatusCode = 200; context.ExceptionHandled = true; result.ErrMsg = myApiex.Msg; result.ErrCode = myApiex.ErrCode; } else { result.ErrMsg = "程序异常,服务端出现异常![异常消息]" + exception.Message; result.ErrCode = "500"; } JsonSerializerOptions options = new JsonSerializerOptions() { WriteIndented = true, //格式化json字符串 AllowTrailingCommas = true, //可以结尾有逗号 //IgnoreNullValues = true, //可以有空值,转换json去除空值属性 IgnoreReadOnlyProperties = true, //忽略只读属性 PropertyNameCaseInsensitive = true, //忽略大小写 //PropertyNamingPolicy = JsonNamingPolicy.CamelCase //命名方式是默认还是CamelCase Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) }; options.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss")); context.Result = new JsonResult(result, options); Log logEntity = new Log(); var identities = context.HttpContext.User.Identities; var claimsIdentity = identities.First <ClaimsIdentity>(); if (claimsIdentity != null) { List <Claim> claimlist = claimsIdentity.Claims as List <Claim>; if (claimlist.Count > 0) { string userId = claimlist[0].Value; YuebonCacheHelper yuebonCacheHelper = new YuebonCacheHelper(); var user = yuebonCacheHelper.Get("login_user_" + userId).ToJson().ToObject <YuebonCurrentUser>(); if (user != null) { currentUser = user; } } } logEntity.Account = currentUser.Account; logEntity.NickName = currentUser.NickName; logEntity.Date = logEntity.CreatorTime = DateTime.Now; logEntity.IPAddress = currentUser.CurrentLoginIP; logEntity.IPAddressName = currentUser.IPAddressName; logEntity.Result = false; logEntity.Description = $"请求:{exDesc}\r\n异常类型:{exception.GetType().Name} \r\n异常信息:{exception.Message} \r\n【堆栈调用】:\r\n{exception.StackTrace}"; logEntity.Type = "Exception"; service.Insert(logEntity); }