/// <summary> /// 重置密码 /// </summary> /// <param name="receive"></param> /// <param name="verifycode"></param> /// <returns></returns> public string ResetPwd(string receive, string verifycode) { try { string valid = ValidReceiveVerifyCode(receive, Constants.CodeTypeForgetPwd, verifycode); if (!string.IsNullOrEmpty(valid)) { return(valid); } string password = Rand.Str(8); _sql.OpenDb(); _sql.Execute("UPDATE UserInfo SET Password = @password WHERE Email = @receive", new Dictionary <string, object> { { "@password", WuYao.GetMd5(password + Constants.PasswordSalt) }, { "@receive", receive } }); if (receive.Contains("@")) { EmailHelper.SendEmailByQQ(receive, "淮安市三轮车开黑网站-重置密码", string.Format("重置密码:{0};请尽快登录并修改密码!", password), Constants.CodeTypeForgetPwd); return("重置密码已发送至注册邮箱!"); } else { return(""); } } catch (Exception ex) { _log.Error(ex.Message, ex); throw ex; } finally { _sql.CloseDb(); } }
/// <summary> /// 检测验证码,返回ClientId /// </summary> /// <param name="inputCode"></param> /// <param name="encryptCode"></param> /// <returns></returns> public string CheckVerifyCode(string inputCode, string encryptCode) { string str = WuYao.AesDecrypt(encryptCode); if (string.IsNullOrEmpty(str)) { throw new Exception("你还想不想登录了!"); } string[] stra = str.Split('$'); if (stra == null || stra.Length == 0) { throw new Exception("系统有误!"); } if (WuYao.GetMd5(inputCode.ToUpper()) != stra[1]) { throw new Exception("验证码有误!"); } SqlHelper _sql = new SqlHelper(); DataTable dt = _sql.Query("SELECT * FROM tbl_loginverifycode WITH(nolock) WHERE ClientId = @id", new System.Collections.Generic.Dictionary <string, object> { { "@id", stra[0] } }); if (dt == null || dt.Rows.Count == 0) { throw new Exception("验证码已失效!"); } if (DateTime.UtcNow.Ticks > long.Parse(Cast.ConToString(dt.Rows[0]["Ticks"]))) { throw new Exception("验证码已失效!"); } return(stra[0]); }
/// <summary> /// 登录 /// </summary> /// <param name="clientId"></param> /// <param name="account"></param> /// <param name="password"></param> private void Login(string clientId, string account, string password) { try { var instance = WuYao.GetSubClass(typeof(IAuthHelper)); if (instance != null) { var authInstance = instance as IAuthHelper; authInstance.ValidUser(account, WuYao.RsaDecrypt(password)); } else { ValidUser(account, WuYao.GetPasswordCipher(password)); } } catch (Exception ex) { _sql.OpenDb(); //删除登陆验证码 _sql.Execute("DELETE FROM tbl_loginverifycode WHERE ClientId = @id", new Dictionary <string, object> { { "@id", clientId } }); _sql.CloseDb(); throw ex; } }
/// <summary> /// 加密验证码 /// </summary> /// <param name="text">验证码</param> /// <returns></returns> private static string EncryptVcCode(string text) { string clientId = Guid.NewGuid().ToString(); string code = WuYao.GetMd5(text.ToUpper()); string plainText = clientId + "$" + code + "$" + Rand.Str_char(6); SqlHelper _sql = new SqlHelper(); _sql.OpenDb(); _sql.Execute(string.Format("insert into tbl_loginverifycode values('{0}','{1}',{2})", clientId, text, DateTime.UtcNow.AddMinutes(3).Ticks)); _sql.CloseDb(); return(WuYao.AesEncrypt(plainText)); }
/// <summary> /// 获取授权Token /// </summary> /// <param name="credit">登录信息</param> /// <returns></returns> public AuthToken GetAuthToken(LoginCredit credit) { try { ConfigHelper _s_config = new ConfigHelper(Constants.SecurityCfgPath); AuthToken result = new AuthToken(); if (credit.grant_type == "password") { string clientId = ValidVerifyCode(credit.verifycode1, credit.verifycode2); Login(clientId, credit.username, credit.password); ClaimsIdentity refresh_identity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, credit.username), new Claim(ClaimTypes.AuthenticationMethod, "refresh") }); result.refresh_token = GenerateJwtToken(refresh_identity, _refresh_token_expire_in, _s_config.Token_Key); } else if (credit.grant_type == "refresh_token") { credit.username = CheckRefreshToken(credit.refresh_token); result.refresh_token = credit.refresh_token; } else { throw new Exception("Invalid grant_type !"); } string account = ""; string userId = GetUserIdByAccount(credit.username, out account); ClaimsIdentity access_identity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, account), new Claim(ClaimTypes.Role, GetUserRoles(userId)), new Claim(ClaimTypes.AuthenticationMethod, "access") }); result.access_token = GenerateJwtToken(access_identity, _token_expire_in, _s_config.Token_Key); result.token_type = "Bearer"; result.expires_in = WuYao.ConvertTimeStamp(DateTime.Now.AddMinutes(_token_expire_in)); return(result); } catch (Exception ex) { _log.Error(ex); throw ex; } }
/// <summary> /// 记录Job运行日志 /// </summary> /// <param name="group">Job组</param> /// <param name="name">Job名</param> /// <param name="mssg">Job运行记录信息</param> /// <param name="start">Job开始时间</param> /// <param name="end">Job结束时间</param> /// <param name="status">Job执行状态</param> private void JobLog(string group, string name, string mssg, DateTime start, DateTime end, int status) { SqlHelper sql = new SqlHelper(); if (group.Contains("$$")) { group = group.Split("$$")[0]; } if (name.Contains("$$")) { name = name.Split("$$")[0]; } sql.OpenDb(); sql.Execute(@"INSERT INTO [dbo].[tbl_joblog] ([JobLogId], [JobGroup], [JobName], [StartTime], [EndTime], [Status], [Result], [Host]) VALUES (Newid(), @group, @name, @start, @end, @status, @mssg, @host) ", new Dictionary <string, object> { { "@group", group }, { "@name", name }, { "@start", start }, { "@end", end }, { "@status", status }, { "@mssg", mssg }, { "@host", WuYao.GetIpAddress() }, }); sql.CloseDb(); }
/// <summary> /// 创建账号 /// </summary> /// <param name="receive"></param> /// <param name="verifycode"></param> /// <returns></returns> public string CreateUser(string receive, string verifycode) { try { string valid = ValidReceiveVerifyCode(receive, Constants.CodeTypeRegister, verifycode); if (!string.IsNullOrEmpty(valid)) { return(valid); } string account = string.Empty; string password = Rand.Str(8); DataTable dtEmail = _sql.Query("SELECT UserInfoId FROM UserInfo WHERE Email = @email", new Dictionary <string, object> { { "@email", receive } }); if (dtEmail != null && dtEmail.Rows.Count > 0) { return("当前邮箱账号密码已发送,请检查邮箱!"); } DataTable dtAccount = null; do { account = Rand.Number(8); dtAccount = _sql.Query("SELECT UserInfoId FROM UserInfo WHERE Account = @account", new Dictionary <string, object> { { "@account", account } }); } while (dtAccount != null && dtAccount.Rows.Count > 0); _sql.OpenDb(); UserInfo user = new UserInfo(); user.Account = account; user.Password = WuYao.GetMd5(password + Constants.PasswordSalt); user.Email = receive; Guid userId = _sql.Create(user); DataTable dtRole = _sql.Query("SELECT RoleInfoId FROM RoleInfo WHERE RoleCode = @code", new Dictionary <string, object> { { "@code", RoleKey.JCQX } }); if (dtRole != null && dtRole.Rows.Count > 0) { UserInRole ur = new UserInRole(); ur.UserInfoId = userId; ur.UserCode = account; ur.RoleCode = RoleKey.JCQX; ur.RoleInfoId = Guid.Parse(Cast.ConToString(dtRole.Rows[0]["RoleInfoId"])); _sql.Create(ur); } if (receive.Contains("@")) { EmailHelper.SendEmailByQQ(receive, "淮安市三轮车开黑网站-注册账号", string.Format("账号:{0} \n 密码:{1}", account, password), Constants.CodeTypeRegister); return("账号密码已发送至注册邮箱!"); } else { return(""); } } catch (Exception ex) { _log.Error(ex.Message, ex); throw ex; } finally { _sql.CloseDb(); } }
/// <summary> /// 下载Excel /// </summary> /// <param name="dataTable"></param> /// <returns></returns> public static string DownloadExcel(DataTable dataTable) { if (dataTable == null || dataTable.Rows.Count == 0) { throw new Exception("Data is Null !"); } try { using (MemoryStream ms = new MemoryStream()) { // Create a spreadsheet document by supplying the filepath. // By default, AutoSave = true, Editable = true, and Type = xlsx. using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook)) { // Add a WorkbookPart to the document. WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart(); workbookpart.Workbook = new Workbook(); // Add a WorksheetPart to the WorkbookPart. WorksheetPart worksheetPart = workbookpart.AddNewPart <WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(new SheetData()); // Add Sheets to the Workbook. Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild <Sheets>(new Sheets()); // Append a new worksheet and associate it with the workbook. Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "sheet1" }; sheets.Append(sheet); // Get the sheetData cell table. SheetData sheetData = worksheetPart.Worksheet.GetFirstChild <SheetData>(); UInt32Value rowIndex = 1; Row headerTitle = new Row() { RowIndex = rowIndex }; List <string> columnNames = new List <string>(); foreach (DataColumn dtColumn in dataTable.Columns) { Cell cell = new Cell(); cell.DataType = new EnumValue <CellValues>(CellValues.String); cell.CellValue = new CellValue(dtColumn.ColumnName); headerTitle.Append(cell); columnNames.Add(dtColumn.ColumnName); } sheetData.Append(headerTitle); foreach (DataRow dtRow in dataTable.Rows) { rowIndex++; // Add a row to the sheetData. Row row = new Row() { RowIndex = rowIndex }; foreach (string columnname in columnNames) { Cell cell = new Cell(); cell.DataType = new EnumValue <CellValues>(CellValues.String); if (dataTable.Columns[columnname].Caption == Constants.DecryptColoumn) { cell.CellValue = new CellValue(WuYao.AesDecrypt(Cast.ConToString(dtRow[columnname]))); } else { cell.CellValue = new CellValue(Cast.ConToString(dtRow[columnname])); } row.Append(cell); } sheetData.AppendChild(row); } worksheetPart.Worksheet.Save(); } return(Convert.ToBase64String(ms.GetBuffer())); } } catch (Exception ex) { throw ex; } }
/// <summary> /// DataTable转List /// </summary> /// <typeparam name="T">模板</typeparam> /// <param name="dt">DataTable</param> /// <param name="model">数据</param> /// <returns></returns> public static List <T> ToModelList <T>(this DataTable dt) where T : new () { try { if (dt == null || dt.Rows.Count == 0) { return(new List <T>()); } List <T> ts = new List <T>(); Type type = typeof(T); string tempName = string.Empty; if (dt.Columns.IndexOf("Sno") <= -1) { dt.Columns.Add("Sno", typeof(int)); } int index = 1; foreach (DataRow dr in dt.Rows) { dr["Sno"] = index; T t = new T(); // 获得此模型的公共属性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; if (dt.Columns.Contains(tempName)) { if (!pi.CanWrite) { continue; } object value = dr[tempName]; if (value is DBNull) { continue; } if (pi.PropertyType.Name.ToLower() == "string") { if (value.GetType().Name.ToLower() == "guid") { pi.SetValue(t, value.ToString(), null); } else if (value.GetType().Name.ToLower() == "datetime") { pi.SetValue(t, Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss"), null); } else { if (dt.Columns[tempName].Caption.ToLower() == tempName.ToLower()) { pi.SetValue(t, Convert.ToString(value), null); } else if (dt.Columns[tempName].Caption == Constants.EncryptColoumn) { pi.SetValue(t, WuYao.AesDecrypt(Convert.ToString(value)), null); } else if (dt.Columns[tempName].Caption == Constants.DecryptColoumn) { pi.SetValue(t, WuYao.AesEncrypt(Convert.ToString(value)), null); } else { pi.SetValue(t, Convert.ToString(value), null); } } } else if (pi.PropertyType.Name.ToLower() == "lookupmodel") { if (dt.Columns.Contains(string.Concat(tempName, "Name"))) { object valuename = dr[string.Concat(tempName, "Name")]; LookUpModel lum = new LookUpModel(); if (valuename != DBNull.Value) { lum.Id = Convert.ToString(value); lum.Name = Convert.ToString(valuename); pi.SetValue(t, lum, null); } else { pi.SetValue(t, lum, null); //throw new Exception(string.Format("The value of column '{0}' is null!", string.Concat(tempName, "Name"))); } } else { throw new Exception(string.Format("The column '{0}' dose not exist!", string.Concat(tempName, "Name"))); } } else if (pi.PropertyType.Name.ToLower() == "int32" || pi.PropertyType.Name.ToLower() == "nullable`1") { pi.SetValue(t, Convert.ToInt32(value), null); } else if (pi.PropertyType.Name.ToLower() == "decimal") { pi.SetValue(t, Convert.ToDecimal(value), null); } else if (pi.PropertyType.Name.ToLower() == "datetime") { pi.SetValue(t, Convert.ToDateTime(value), null); } else if (pi.PropertyType.Name.ToLower() == "boolean") { pi.SetValue(t, Convert.ToBoolean(value), null); } else if (pi.PropertyType.Name.ToLower() == "guid") { pi.SetValue(t, Guid.Parse(value.ToString()), null); } } } ts.Add(t); index++; } return(ts); } catch (Exception ex) { throw new Exception(ex.Message, ex); } }