private bool NeedUpdate(FileUpdateInfo fileUpdateInfo) { FilePath localPath = fileUpdateInfo.LocalFilePath; if (localPath.GetFileExt() == @".zip") { FilePath zipMd5Path = localPath.GetDirPath() + localPath.GetFileNameWithoutExtension() + @".md5"; if (!File.Exists(zipMd5Path)) { // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(fileUpdateInfo.LocalFilePath)); return(true); } var localZipMd5 = zipMd5Path.ReadAsString(); var remoteZipMd5 = fileUpdateInfo.RemoteMD5.Trim().ToLower(); return(localZipMd5 != remoteZipMd5); } if (!File.Exists(fileUpdateInfo.LocalFilePath)) { // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(fileUpdateInfo.LocalFilePath)); return(true); } var localMd5 = Md5Util.CaculateFileMd5(fileUpdateInfo.LocalFilePath).ToLower(); var remoteMd5 = fileUpdateInfo.RemoteMD5.Trim().ToLower(); return(localMd5 != remoteMd5); }
/// <summary> /// DYB 进入游戏上报玩家数据 /// </summary> public void reportDYBUserData() { WWWForm form = new WWWForm(); string userID = Account.Instance.AccountId.ToString(); string playerID = PlayerData.Instance.RoleID.ToString(); string serverID = Account.Instance.ServerId.ToString(); string key = "a0c6739105a24ce9c2c8a3109d6d6c33"; //md5 key值 string md5 = Md5Util.MD5Encrypt(serverID + userID + playerID + key); form.AddField("serverid", serverID); form.AddField("userID", userID); form.AddField("playerID", playerID); form.AddField("token", md5); Dictionary <string, string> data = new Dictionary <string, string>(); data["userID"] = userID; data["playerID"] = playerID; data["serverid"] = serverID; data["servername"] = Account.Instance.ServerName.ToString(); string serverInfo = JsonMapper.ToJson(data); form.AddField("data", serverInfo); Debug.Log("上报信息token: serverID : " + serverID + " userID:" + userID + " playerID:" + playerID + " key:" + key); //进入游戏上报 int sdkType = ClientSetting.Instance.GetIntValue("thirdPartyComponent"); int subChannel = ClientSetting.Instance.GetIntValue("SubChannel"); MonoInstance.Instance.StartCoroutine(PostPhp(GetLoggedUrl(sdkType, subChannel), form)); }
public async Task <JsonModel> ChangePWD(string username, string cur_pwd, string new_pwd) { try { var user = await(from c in _dbContext.Users where c.UserName == username select c).FirstOrDefaultAsync(); if (user == null) { return(new JsonModel(false, "用户不存在", null)); } string cur_md5pwd = Md5Util.Encode(Md5Util.Encode(cur_pwd + _pwd_salt) + username); if (cur_md5pwd != user.Password) { return(new JsonModel(false, "当前密码错误", null)); } string new_md5pwd = Md5Util.Encode(Md5Util.Encode(new_pwd + _pwd_salt) + username); user.Password = new_md5pwd; _dbContext.Users.Update(user); await _dbContext.SaveChangesAsync(); return(new JsonModel(true, "修改成功", null)); } catch (Exception e) { return(new JsonModel(false, "修改失败", e.Message)); } }
private string Sign(string appSecret, SortedDictionary <string, string> param) { param.Remove("sign"); string value = appSecret + string.Join("", param.Select(obj => string.IsNullOrWhiteSpace(obj.Value) ? "" : obj.Key + obj.Value)) + appSecret; return(Md5Util.Md5(value)); }
public void TestInitialize() { userService = new UserService(); SqlConnection connection = null; password = Md5Util.EncryptStringWithMD5("123"); try { string sqlCreateuser = "******" + password + "','male','2016-12-18 20:10:10.223','2016-12-18 20:10:10.223','2016-12-18 20:10:10.223',4,0,'1812312656','*****@*****.**'); select @@IDENTITY as 'id'"; Console.WriteLine(sqlCreateuser); connection = DBUtil.GetSqlConnection(); SqlCommand sqlCommand = connection.CreateCommand(); sqlCommand.CommandType = CommandType.Text; sqlCommand.CommandText = sqlCreateuser; SqlDataReader reader = sqlCommand.ExecuteReader(); while (reader.Read()) { userId = (int)reader[0]; } } finally { DBUtil.ColseSqlConnection(connection); } }
// POST: /Login/ public JsonResult Login(JObject data) { string UserCode = data.Value <string>("user_code"); string Password = data.Value <string>("password"); string IP = data.Value <string>("ip"); string City = data.Value <string>("city"); data["user_code"] = UserCode; data["password"] = Md5Util.MD5(Password); data["LoginIP"] = IP; data["LoginCity"] = City; AppConnectionString = ConfigurationManager.ConnectionStrings["app"].ConnectionString; DataSet dt = base.RunProcedureDataSet(data, "vdp_sys_Login", "app"); //if (dt.Rows.Count > 0) var ResultID = dt.Tables[0].Rows[0]["result_id"]; var ResultMsg = (string)dt.Tables[0].Rows[0]["result_msg"]; //var loginResult = Base_UserService.Instance.Login(UserCode, Md5Util.MD5(Password), IP, City); if (ResultID.ToString() == "0") { Base_User b = new Base_User(); b.city = "";// (string)dt.Rows[0]["city"]; b.RealName = (string)dt.Tables[1].Rows[0]["real_name"]; b.DepartmentID = (int)dt.Tables[1].Rows[0]["department_id"]; b.UserId = (int)dt.Tables[1].Rows[0]["id"]; b.UserCode = (String)dt.Tables[1].Rows[0]["user_code"]; b.RoleIDs = (string)dt.Tables[1].Rows[0]["role_ids"]; b.DepartmentCode = ((int)dt.Tables[1].Rows[0]["department_id"]).ToString(); var loginer = new BaseLoginer { UserId = (int)dt.Tables[1].Rows[0]["id"], //. user.UserId, UserCode = (string)dt.Tables[1].Rows[0]["user_code"], // user.UserCode, // Password = (string)dt.Tables[1].Rows[0]["Password"],// user.Password, UserName = (string)dt.Tables[1].Rows[0]["real_name"], // user.RealName, RoleIDs = (string)dt.Tables[1].Rows[0]["role_ids"], // DepartmentCode =((int)dt.Tables[1].Rows[0]["DepartmentID"]).ToString(), Data = b, IsAdmin = false }; Session["logininfo"] = ""; //set timeout var effectiveHours = Convert.ToInt32(60 * ConfigUtil.GetConfigDecimal("LoginEffectiveHours")); //执行web登录 FormsAuth.SignIn(loginer.UserId.ToString(), loginer, effectiveHours); } else { LogHelper.Write("Login Failed!Account:" + UserCode + ",password:" + Password + "。reason:" + ResultMsg); } return(Json(new { s = ResultID, message = ResultMsg }, JsonRequestBehavior.DenyGet)); }
private string GenarateStreamCode(int userid) { Random random = new Random(); string c = userid + random.Next() + "932qj@dawrr" + DateTime.Now.Ticks.ToString(); string result = Md5Util.Encode(Md5Util.Encode(c) + "th8jusde21@HRFIh"); return(result); }
public static string GenerateKey(string suffix) { var now = DateTime.UtcNow; var random = new Random(RandomSeed++); var pureKeyStr = string.Format("{0}{1}{2}", suffix, now.Ticks, random.Next(int.MinValue, int.MaxValue)); return(Md5Util.String16(pureKeyStr)); }
public void GetMd5Buffer_Test() { var stream = new MemoryStream(Encoding.UTF8.GetBytes("helloworld")); var buffer = Md5Util.GetMd5Buffer(stream); var actual = BitConverter.ToString(buffer).Replace("-", ""); Assert.Equal("FC5E038D38A57032085441E7FE7010B0", actual); }
public ActionResult Login(LoginModel model, string returnUrl) { if (string.IsNullOrEmpty(model.UserName)) { ModelState.AddModelError("", "账号不能为空!"); return(View(model)); } if (string.IsNullOrEmpty(model.Password)) { ModelState.AddModelError("", "密码不能为空!"); return(View(model)); } string errorMessage = string.Empty; var loginSuccessful = Login(model.UserName.Trim(), model.Password.Trim(), out errorMessage); if (loginSuccessful == null) { ModelState.AddModelError("", errorMessage); return(View(model)); } _formsAuthentication.SetAuthCookie(model.UserName, true); _contextService.SetCookie("role", CurrentUser.RoleId.ToString()); _contextService.NickName = CurrentUser.NickName; _contextService.DepId = CurrentUser.DepId.ToString(); _contextService.UserId = CurrentUser.Id.ToString(); _contextService.UserPhoto = ConfigurationManager.AppSettings["USER_AVATAR"] + CurrentUser.UserInfoPhoto; _contextService.SpaceTreeHtml = _spaceService.GetOrSetSpaceTree(_contextService.UserId); HttpCookie cookie = new HttpCookie("USER_COOKIE"); if (model.RememberMe) { //所有的验证信息检测之后,如果用户选择的记住密码,则将用户名和密码写入Cookie里面保存起来。 cookie.Values.Add("UserName", Md5Util.Encrypt(model.UserName.Trim())); cookie.Values.Add("UserPassword", Md5Util.Encrypt(model.Password.Trim())); //这里是设置Cookie的过期时间,这里设置30天的时间,过了时间之后状态保持自动清空。 cookie.Expires = DateTime.Now.AddDays(30); Response.Cookies.Add(cookie); } else { //如果用户没有选择记住密码,那么立即将Cookie里面的信息情况,并且设置状态保持立即过期。 var httpCookie = Response.Cookies["USER_COOKIE"]; if (httpCookie != null) { httpCookie.Value = null; httpCookie.Expires = DateTime.Now; } } _logger.Info("登录成功:user:" + model.UserName); return(loginSuccessful); }
//修改自己密码 //POST /Home/ModifySelfPassword public JsonResult ModifySelfPassword(JObject data) { string UserCode = CurrentUser.UserCode; string Password = data.Value <string>("newpassword"); data["UserCode"] = UserCode; data["Password"] = Md5Util.MD5(Password); base.RunProcedureByName(data, "vdp_reset_pwd", "app"); return(Json(new { s = true, message = GetSysText("success") }, JsonRequestBehavior.DenyGet)); }
/// <summary> /// Generates the key cache. /// </summary> /// <returns></returns> public static string GenerateKeyCache() { var stackTrace = new StackTrace(true); var methodBase = stackTrace.GetFrame(1).GetMethod(); var type = methodBase.ReflectedType; var className = type.Name; var key = string.Format("dbo-{1}_{2}", className, methodBase.Name); return(Md5Util.Md5EnCrypt(key)); }
/// <summary> /// 登录验证 /// </summary> /// <param name="userid"></param> /// <param name="password"></param> /// <returns></returns> private void login() { string userid = textEdit1.Text; string password = textEdit2.Text; string parameters = "userid=" + userid + "&password="******"http://localhost:8080/user/login", parameters, "POST"); XtraMessageBox.Show(userLoginInfo, "userLoginInfo"); }
//动作:添加记录 // POST: /Sys/Base_User/Add public JsonResult Add(JObject data) { var entity = data.ToObject <Base_User>(); entity.Password = Md5Util.MD5(entity.UserCode);//新增用户,密码默认和登录账号一样 int result = Base_UserService.Instance.Insert(entity); CommandResult cmdResult = result > 0 ? CommandResult.Instance_Succeed : CommandResult.Instance_Error; cmdResult.ResultMsg = "保存成功!"; return(JsonNet(cmdResult, JsonRequestBehavior.DenyGet)); }
public JsonResult ResetPasswrod(JObject data) { string Password = data.Value <string>("pwd"); data["pwd"] = Md5Util.MD5(Password); data["add_by"] = CurrentUser.UserId; base.RunProcedureByName(data, "vdp_reset_password", "app"); return(Json(new { s = true, message = GetSysText("success") }, JsonRequestBehavior.DenyGet)); }
/// <summary> /// 使用md5加盐 /// </summary> /// <param name="plainText"></param> public static void EncryptWithSalt(string plainText) { var plainBytes = Encoding.UTF8.GetBytes(plainText); var headSalt = SaltUtil.GenerateSalt(3); //加盐头 var tailSalt = SaltUtil.GenerateSalt(2); //加盐尾 var plainBytesWithSalts = BytesUtil.Combine(headSalt, plainBytes, tailSalt); var encryptedBytes = Md5Util.Encrypt(plainBytesWithSalts); var encryptedText = BytesUtil.ToHex(encryptedBytes); Console.WriteLine("Plain text:{0}, encrypted text:{1}", plainText, encryptedText); }
/// <summary> /// Generates the key cache. /// </summary> /// <returns></returns> public string GenerateKeyCache() { var stackTrace = new StackTrace(true); var methodBase = stackTrace.GetFrame(1).GetMethod(); var type = methodBase.ReflectedType; var className = type.Name; var key = string.Format("{0}-{1}_{2}", _schema, className, methodBase.Name); //var nameSpace = type.Namespace; //var aParams = methodBase.GetParameters(); return(Md5Util.Md5EnCrypt(key)); }
/// <summary> /// 检验密码是否正确 /// </summary> /// <param name="loginName"></param> /// <param name="passWord"></param> /// <returns></returns> public bool ValidataPassWord(int uid, string passWord) { passWord = Md5Util.PwdMd5(passWord); DAO.MemberBase mb = db.MemberBase.Where(m => (m.ID == uid) && m.PassWord == passWord && m.State == 1).FirstOrDefault(); if (mb == null) { return(false); } else { return(true); } }
/// <summary> /// 修改自己的密码 /// </summary> /// <param name="newPassword">新密码,未加密</param> /// <returns>返回CommandResult</returns> public CommandResult ModifySelfPassword(string newPassword, int userid) { CommandResult commandResult = new CommandResult(); var paramUpdate = ParamUpdate.Instance().Update("Base_User") .Column("Password", Md5Util.MD5(newPassword)) .AndWhere("UserId", userid); int n = this.Update(paramUpdate); commandResult.ResultID = n > 0 ? 0 : -1; commandResult.ResultMsg = n > 0 ? "密码修改成功" : "密码修改失败"; LogHelper.Write("修改个人密码。用户:" + this.CurrentBaseLoginer.UserName + "。结果:" + commandResult.ResultMsg); return(commandResult); }
private bool NeedUpdate(FileUpdateInfo fileUpdateInfo) { if (!File.Exists(fileUpdateInfo.LocalFilePath)) { // ReSharper disable once AssignNullToNotNullAttribute Directory.CreateDirectory(Path.GetDirectoryName(fileUpdateInfo.LocalFilePath)); return(true); } string localMd5 = Md5Util.CaculateFileMd5(fileUpdateInfo.LocalFilePath).ToLower(); string remoteMd5 = fileUpdateInfo.RemoteMD5.Trim().ToLower(); return(localMd5 != remoteMd5); }
public async Task <string> Login(string username, string password) { string md5pwd = Md5Util.Encode(Md5Util.Encode(password + _pwd_salt) + username); var linq = from c in _dbContext.Users where c.UserName == username && c.Password == md5pwd select c; User user = await linq.FirstOrDefaultAsync(); if (user == null) { return("用户名或密码不正确"); } UserData userdata = new UserData { UserId = user.Id, UserName = user.UserName, LoginTime = DateTime.Now }; try { var roles = await(from c in _dbContext.UserRoles join cc in _dbContext.Roles on c.UserId equals cc.Id where c.UserId == user.Id select cc).ToListAsync(); userdata.Roles = roles; //角色权限 var per1 = from c in _dbContext.UserPermissions join cc in _dbContext.Permissions on c.PermissionId equals cc.Id where c.UserId == user.Id select cc; //用户权限 var per2 = from c in _dbContext.UserRoles join cc in _dbContext.RolePermissions on c.RoleId equals cc.RoleId join ccc in _dbContext.Permissions on cc.PermissionId equals ccc.Id where c.UserId == user.Id select ccc; var pers = await per1.Union(per2).ToListAsync(); userdata.Permissions = pers; MyHttpContext.Current.Session.Set("UserData", userdata); MyHttpContext.Current.Session.SetString("UserId", user.Id.ToString()); return("true"); } catch (Exception ex) { return(ex.ToString()); } }
// POST: /Login/ public JsonResult Login(JObject data) { string UserCode = data.Value <string>("usercode"); string Password = data.Value <string>("pwd"); string IP = data.Value <string>("ip"); string City = data.Value <string>("city"); var loginResult = Base_UserService.Instance.Login(UserCode, Md5Util.MD5(Password), IP, City); if (loginResult.Succeed) { //登录成功后,查询当前用户数据 var user = Base_UserService.Instance.GetEntity(ParamQuery.Instance() .AndWhere("UserCode", UserCode).AndWhere("Password", Md5Util.MD5(Password)) .AndWhere("Enabled", 1).AndWhere("IsAudit", 1)); //调用框架中的登录机制 var loginer = new BaseLoginer { UserId = user.UserId, UserCode = user.UserCode, Password = user.Password, UserName = user.RealName, Data = user, IsAdmin = user.UserType == 1 //根据用户UserType判断。用户类型:0=未定义 1=超级管理员 2=普通用户 3=其他 }; //读取配置登录默认失效时长:小时 var effectiveHours = Convert.ToInt32(60 * ConfigUtil.GetConfigDecimal("LoginEffectiveHours")); // 无限光年网络科技 //执行web登录 FormsAuth.SignIn(loginer.UserId.ToString(), loginer, effectiveHours); LogHelper.Write("登录成功!用户:" + loginer.UserName + ",账号:" + UserCode + ",密码:" + Password); //设置服务基类中,当前登录用户信息 //this.CurrentBaseLoginer = loginer; //登陆后处理 //更新用户登陆次数及时间(存储过程登录,数据库已经处理) //添加登录日志 string userinfo = string.Format("用户姓名:{0},用户编号:{1},登录账号:{2},登录密码:{3}", loginer.UserName, loginer.UserId, loginer.UserCode, loginer.Password); Base_SysLogService.Instance.AddLoginLog(userinfo, IP, City); //更新其它业务 } else { LogHelper.Write("登录失败!账号:" + UserCode + ",密码:" + Password + "。原因:" + loginResult.ResultMsg); } return(Json(loginResult, JsonRequestBehavior.DenyGet)); }
public bool UpdatePasswordOld(string iphoneNum, string password) { string newPass = Md5Util.PwdMd5(password); string sql = "UPDATE [MemberBase] SET [PassWord] ='{0}' WHERE Mobile={1}"; int i = db.Database.ExecuteSqlCommand(string.Format(sql, newPass, iphoneNum)); if (i > 0) { return(true); } else { return(false); } }
public ActionResult RegMember(RegUserModel model) { if (ModelState.IsValid) { MemberBLL bll = new MemberBLL(); if (bll.VerRegCode(model.PhoneNumber, model.PhoneCode)) { FriendCodeBLL fbll = new FriendCodeBLL(); DAO.MemberLevel levelModel = new DAO.MemberLevel(); DAO.MemberBase m = new DAO.MemberBase(); m.LoginName = model.loginName; m.PassWord = Md5Util.PwdMd5(model.passWord); m.Mobile = model.PhoneNumber; m.Email = model.eMail; m.State = 1; int upUser = fbll.GetUpUser(model.FriendCode); m.UpUser = upUser;//上级用户 m.Levels = 0; m.Integral = 0; m.Source = "self"; m.RegDate = DateTime.Now; DAO.MemberBase u = bll.Reg(m); //注册 Session["memberID"] = u.ID; levelModel = bll.GetLevel(u.ID, upUser); //注册初始化级别 VoucherBus vbll = new VoucherBus(); vbll.RegGiveAVoucher(u.ID); //给一张注册优惠券 u.Levels = levelModel.LevelId; u.Integral = levelModel.MinIntegral; DAO.MemberBase allu = bll.UpdateUser(u); if (allu != null) { //给上级积分 bll.GiveUpUserInt(allu.ID, upUser); } return(RedirectToAction("UserHome")); } else { ViewBag.phoneCodeValid = "手机注册码错误"; return(View("RegView", model)); } } else { return(View("RegView", model)); } }
public ActionResult Reg(string phone, string phonecode, string fcode) { //RegMsg RegUserModel model MemberBLL bll = new MemberBLL(); if (!bll.VerPhone(phone)) { return(Json(new { r = false, msg = "手机号已经被注册!" })); } if (bll.VerRegCode(phone, phonecode)) //验证手机号与手机验证码 { FriendCodeBLL fbll = new FriendCodeBLL(); DAO.MemberLevel levelModel = new DAO.MemberLevel(); DAO.MemberBase m = new DAO.MemberBase(); m.LoginName = phone; m.PassWord = Md5Util.PwdMd5(phone.Substring(5)); m.Mobile = phone; //m.Email = ""; m.State = 1; int upUser = fbll.GetUpUser(fcode); m.UpUser = upUser; //上级用户 m.Levels = 0; m.Integral = 0; m.Source = "self"; m.RegDate = DateTime.Now; DAO.MemberBase u = bll.Reg(m); //注册 Session["memberID"] = u.ID; VoucherBus vbll = new VoucherBus(); vbll.RegGiveAVoucher(u.ID); //给一张注册优惠券 levelModel = bll.GetLevel(u.ID, upUser); //注册初始化级别 u.Levels = levelModel.LevelId; u.Integral = levelModel.MinIntegral; DAO.MemberBase allu = bll.UpdateUser(u); if (allu != null) { //给上级积分 bll.GiveUpUserInt(allu.ID, upUser); } return(Json(new { r = true, msg = "注册成功,初始密码为您手机号后四位!" })); } else { return(Json(new { r = false, msg = "手机验证码错误" })); } }
// // POST: /Account/LogOff //[ValidateAntiForgeryToken] public ActionResult LogOut() { if (CurrentUser != null) { _logger.Info("注销退出:user:" + CurrentUser.UserName); //_userLogService.Log(new UserLogContract() { IpAddress = CerCommon.GetIp(), Message = "注销退出", UserId = CurrentUser.Id, FromClient = "主系统" }); } //WebSecurity.Logout(); HttpCookie cookie = new HttpCookie("USER_COOKIE"); //读取保存的Cookie信息 HttpCookie cookies = Request.Cookies["USER_COOKIE"]; var model = new LoginModel(); if (cookies != null && !string.IsNullOrEmpty(cookies.Value)) { //如果Cookie不为空,则将Cookie里面的用户名和密码读取出来赋值给前台的文本框。 model.UserName = Md5Util.Decrypt(cookies["UserName"]); model.Password = Md5Util.Decrypt(cookies["UserPassword"]); if (!string.IsNullOrEmpty(cookies["AutoLogin"])) { model.AutoLogin = bool.Parse(Md5Util.Decrypt(cookies["AutoLogin"])); } //这里依然把记住密码的选项给选中。 model.RememberMe = true; } if (model.RememberMe) { //所有的验证信息检测之后,如果用户选择的记住密码,则将用户名和密码写入Cookie里面保存起来。 cookie.Values.Add("UserName", Md5Util.Encrypt(model.UserName.Trim())); cookie.Values.Add("UserPassword", Md5Util.Encrypt(model.Password.Trim())); cookie.Values.Add("AutoLogin", Md5Util.Encrypt(false.ToString())); //这里是设置Cookie的过期时间,这里设置7天的时间,过了时间之后状态保持自动清空。 cookie.Expires = DateTime.Now.AddDays(7); Response.Cookies.Add(cookie); } ActionResult logOff = Logout(); _formsAuthentication.SignOut(); _contextService.SetCookie("role", ""); _contextService.NickName = null; _contextService.DepId = string.Empty; return(logOff); }
/// <summary> /// 保存上传的文件 /// </summary> /// <param name="postFileBase"></param> /// <param name="path"></param> /// <returns></returns> private File SaveHttpPostFile(HttpPostedFileBase postFileBase, string path) { System.IO.Stream uploadStream = null; System.IO.FileStream fs = null; File file = new File(); try { uploadStream = postFileBase.InputStream; int bufferLen = 1024; byte[] buffer = new byte[bufferLen]; int contentLen = 0; file.Name = System.IO.Path.GetFileName(postFileBase.FileName); file.ContentType = postFileBase.ContentType; file.RealPath = path + Guid.NewGuid().ToString(); fs = new System.IO.FileStream(file.RealPath, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite); while ((contentLen = uploadStream.Read(buffer, 0, bufferLen)) != 0) { fs.Write(buffer, 0, bufferLen); fs.Flush(); } } catch (Exception ex) { throw ex; } finally { if (null != fs) { fs.Close(); } if (null != uploadStream) { uploadStream.Close(); } } file.Size = GetFileSize(file.RealPath); file.Md5 = Md5Util.GetMD5HashFromFile(file.RealPath); return(file); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { url = Request["returnurl"]; } if (IsPostBack) { string txtName = Request["txtName"]; string txtRealName = Request["txtRealName"]; string txtPwd = Request["txtRealName"]; url = Request["returnurl"]; string txtCode = Request["txtCode"]; m.Users users = new m.Users(); b.Users bll = new b.Users(); int count = 0; if (bll.GetCountByName(txtName) != 0) { count++; } if (txtCode != (string)Session["validate"]) { Session["validate"] = null; count++; } if (String.IsNullOrEmpty(txtPwd)) { count++; } if (count == 0) { users.LoginId = txtName; users.Name = txtRealName; users.LoginPwd = Md5Util.GetMd5(txtPwd); users.UserStateId = 1; bll.Add(users); Session["user"] = users; if (url != null) { Response.Redirect(url); } Response.Redirect("default.aspx"); } } }
private void PublishMongoMessage(Captcha captcha, byte[] binary, string code) { Task.Run(() => { try { string captchaId = captcha.Ticket; if (code.Contains("Ticket") && code.Contains("Id") && code.Contains("Result")) { string nCode = code; captchaId = JsonConvert.DeserializeObject <SharedResult>(nCode).Id; code = JsonConvert.DeserializeObject <SharedResult>(nCode).Result; } MongoDBHelper <Samples> mongoDBHelper = new MongoDBHelper <Samples>(); Samples entity = new Samples() { channel = captcha.Channel, ticket = captcha.Ticket, captchaId = captchaId, code = code.ToUpper(), image = captcha.Binary, md5 = Md5Util.GetMD5Hash(binary), isError = false, createTime = DateTime.Now.AddHours(8) }; mongoDBHelper.Insert(entity); } catch (Exception e) { if (e.Message.Contains("duplicate key error")) { Console.WriteLine("Ignore current captcha, duplicate key error: " + code); return; } else if (e.Message.Contains("System.Net.Sockets.SocketException")) { Console.WriteLine("MongoDB connect timeout"); } else { Console.WriteLine("MongoDB exception: " + e.Message); } } }); }
// // GET: /Account/Login //[AllowAnonymous] public ActionResult Login(string returnUrl) { _logger.Info("登录页面:访问IP:" + CerCommon.GetIp()); if (CurrentUser != null && !(CurrentUser is EmptyUserContract)) { _formsAuthentication.SetAuthCookie(CurrentUser.UserName, false); _contextService.SetCookie("role", CurrentUser.RoleId.ToString()); _contextService.NickName = CurrentUser.NickName; _contextService.DepId = CurrentUser.DepId.ToString(); _contextService.UserPhoto = ConfigurationManager.AppSettings["USER_AVATAR"] + CurrentUser.UserInfoPhoto; _logger.Info(CurrentUser.Id + "登录成功" + "文档管理系统"); return(Redirect("/home/index")); } var model = new LoginModel(); //读取保存的Cookie信息 HttpCookie cookies = Request.Cookies["USER_COOKIE"]; if (cookies != null && !string.IsNullOrEmpty(cookies.Value)) { //如果Cookie不为空,则将Cookie里面的用户名和密码读取出来赋值给前台的文本框。 model.UserName = Md5Util.Decrypt(cookies["UserName"]); model.Password = Md5Util.Decrypt(cookies["UserPassword"]); //这里依然把记住密码的选项给选中。 model.RememberMe = true; ViewBag.ReturnUrl = returnUrl; if (model.AutoLogin) { return(Login(model, returnUrl)); } return(View(model)); } //if (!string.IsNullOrEmpty(returnUrl) && returnUrl.EndsWith("/account/logoff")) //{ // returnUrl = returnUrl.Replace("/account/logoff", "/home/index"); //} ViewBag.ReturnUrl = returnUrl; return(View(model)); }