找回密码
登陸功能中有一項(xiàng)是當(dāng)用戶忘記密碼后需要找回密碼
1、當(dāng)用戶點(diǎn)忘記密碼后我們呈現(xiàn)的是一個(gè)表單,要求用戶輸入用戶名和郵箱號(hào),輸完信息后點(diǎn)擊發(fā)送郵件,發(fā)郵件的代碼如下:
public string SendMail(string userid, string email){if(string.IsNullOrEmpty(userid))return "請(qǐng)輸入用戶登錄名!";if (string.IsNullOrEmpty(email))return "請(qǐng)輸入郵箱地址!";MembershipUser user = Membership.GetUser(userid, false);if (user == null){return string.Format("找不到用戶:{0}!", userid);}ProfileBase profile = ProfileBase.Create(userid);if (profile.GetPropertyValue("EmailAddresses") != null){bool IsApprovaled = user.IsApproved;bool IsLocked = user.IsLockedOut;if (!IsApprovaled){return string.Format("用戶:{0}已被禁用,無法登錄,請(qǐng)聯(lián)系管理員!", userid);}if (IsLocked){return string.Format("用戶:{0}已被鎖定,無法登錄,請(qǐng)聯(lián)系管理員!", userid);}string myemail = profile.GetPropertyValue("EmailAddresses").ToString();if (myemail.ToUpper().Trim() != email.ToUpper().Trim()){return string.Format("用戶:{0}對(duì)應(yīng)的郵箱:{1}不存在,請(qǐng)重新輸入郵箱!", userid, email);}else{string unitname = string.Empty;try{string unitcode = profile.GetPropertyValue("UnitCode").ToString();unitname = UnitService.GetUnitByCode(unitcode).Name;}catch (Exception ep){}string username = profile.GetPropertyValue("Name").ToString();string userinfo = string.Format("{0}您好!<br/>姓名:{1}<br/>單位:{2}<br/>", user.UserName, username, unitname);string paramuid = DESHelper.Encrypt(string.Format("{0}|{1}", user.UserName, DateTime.Now), "findpassword");string callbackUrl =string.Format("admin/resetpassword.aspx?userid={0}",paramuid);string content = userinfo + "請(qǐng)通過單擊 <a href=\"" + ConfigHelper.CurrentConfig.FindpasswordUrl + callbackUrl + "\">此處</a>來重置你的密碼";new MailService().SendMail(email, "中石油出國系統(tǒng)系統(tǒng):找回密碼", content, null, null,true);return "";}}else{return string.Format("用戶:{0}郵箱不存在,請(qǐng)重新輸入郵箱!", userid);}}注:new MailService().SendMail(email, "中石油出國系統(tǒng)系統(tǒng):找回密碼", content, null, null,true);這個(gè)方法是我項(xiàng)目中已有的發(fā)送郵件的方法。DESHelper也是我項(xiàng)目中封裝好的類,在后面會(huì)全部給出
2、郵件發(fā)送后用戶需要進(jìn)入郵箱點(diǎn)擊進(jìn)行驗(yàn)證,點(diǎn)擊后訪問系統(tǒng)中?resetpassword.aspx 頁面,該頁面有一個(gè)密碼重置按鈕,我們來看看這個(gè)頁面的后臺(tái)代碼
protected void Page_Load(object sender, EventArgs e){string userid = GetStringPara("userid", "");string encodeuserid = DESHelper.Decrypt(userid, "findpassword");string[] stringuid = encodeuserid.Split('|');string userId = stringuid[0];DateTime logtime = DateTime.Parse(stringuid[1]);if (logtime >= DateTime.Now.AddMinutes(-30)){lbUserId.Text = userId;}elseResponse.Redirect("FindPassword.aspx");}注:在這個(gè)頁面的后臺(tái)我們將用戶的數(shù)據(jù)進(jìn)行解密,存入到一個(gè)服務(wù)端控件中去
3、點(diǎn)擊重置密碼后用戶的密碼被重置成了默認(rèn)的值、看下面的方法
protected void btReset_Click(object sender, EventArgs e){string userid = lbUserId.Text;MembershipUser user = Membership.GetUser(userid, false);if (user == null){ShowInfo(string.Format("用戶:{0}不存在,無法重置密碼,請(qǐng)聯(lián)系管理員!", userid));return;}bool IsApprovaled = user.IsApproved;bool IsLocked = user.IsLockedOut;if (!IsApprovaled){ShowInfo(string.Format("用戶:{0}已被禁用,無法登錄,請(qǐng)聯(lián)系管理員!", userid));return;}if (IsLocked){ShowInfo(string.Format("用戶:{0}已被鎖定,無法登錄,請(qǐng)聯(lián)系管理員!", userid));return;}string newPassword = user.ResetPassword();user.ChangePassword(newPassword, tbPassword.Text);Response.Write(string.Format("<script language='JavaScript'>alert('重置密碼成功,請(qǐng)重新登錄!');window.location='{0}';</script>",ConfigHelper.CurrentConfig.ShowNewsUrl));}注:項(xiàng)目中用的?Membership 框架,重置和改變密碼都是用了框架中的方法
至此密碼重置完成了,最后貼上我們項(xiàng)目中已有的類的方法:
?MailService類
public class MailService{public static MailMessage mailMessage = new MailMessage();public static string AttachmentPath;public List<Attachment> attchments;/// <summary>/// 發(fā)送郵件的方法/// </summary>/// <param name="toMail">目的郵件地址</param>/// <param name="title">發(fā)送郵件的標(biāo)題</param>/// <param name="content">發(fā)送郵件的內(nèi)容</param>/// <param name="CopytoMail">抄送郵件地址</param>/// <param name="FilePath">附件路徑,附件之間以"|"相間隔</param>public void SendMail(string toMail, string title, string content, string CopyMail, string FilePath, bool isBodyHtml){try{mailMessage.To.Clear();mailMessage.CC.Clear();mailMessage.AlternateViews.Clear();mailMessage.Headers.Clear();Encoding chtEnc = Encoding.BigEndianUnicode;//Encoding.UTF8AttachmentPath = FilePath;AddMailTo(toMail, chtEnc);AddCopyTo(CopyMail, chtEnc);//郵件標(biāo)題編碼mailMessage.SubjectEncoding = chtEnc;//郵件主題mailMessage.Subject = string.IsNullOrEmpty(title) ? "No Subject".ToString() : title.ToString();mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//郵件內(nèi)容mailMessage.Body = string.IsNullOrEmpty(content) ? "No Content".ToString() : content.ToString();//郵件內(nèi)容編碼mailMessage.BodyEncoding = System.Text.Encoding.UTF8;mailMessage.IsBodyHtml = isBodyHtml;//是否允許內(nèi)容為 HTML 格式 AddAttach(FilePath);//添加多個(gè)附件 //如果發(fā)送失敗,SMTP 服務(wù)器將發(fā)送失敗郵件告訴我mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;//發(fā)送郵件的優(yōu)先等級(jí)(有效值為High,Low,Normal)mailMessage.Priority = MailPriority.Normal;mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;SmtpClient client = new SmtpClient();client.Timeout = 120000;//異步發(fā)送完成時(shí)的處理事件client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);//發(fā)送郵件client.Send(mailMessage); //同步發(fā)送//client.SendAsync(mailMessage, mailMessage.To); //異步發(fā)送 (異步發(fā)送時(shí)頁面上要加上Async="true" ) }catch (Exception ep){ throw new ApplicationException(string.Format("發(fā)送郵件失敗:\r\n {0}",ep.Message));}}/// <summary>/// 增加抄送人(支持多個(gè))/// </summary>/// <param name="CopyMail">抄送人地址列表</param>/// <param name="chtEnc">編碼</param>private void AddCopyTo(string CopyMail, Encoding chtEnc){if (!string.IsNullOrEmpty(CopyMail)){string strCopyMail = CopyMail.Replace(";", ";");if (strCopyMail.Contains(";")){string[] mails = strCopyMail.Split(';');foreach (string mail in mails){if (!string.IsNullOrEmpty(mail))mailMessage.CC.Add(new MailAddress(mail, mail.ToString(), chtEnc));}}else{mailMessage.CC.Add(new MailAddress(CopyMail, CopyMail.ToString(), chtEnc));}}}//<summary>//增加收件人(支持多個(gè))//</summary>//<param name="toMail">收件人地址列表</param>//<param name="chtEnc">編碼</param>private void AddMailTo(string toMail, Encoding chtEnc){string strToMail = toMail.Replace(";", ";");if (strToMail.Contains(";")){string[] mails = strToMail.Split(';');foreach (string mail in mails){if (!string .IsNullOrEmpty(mail))mailMessage.To.Add(new MailAddress(mail, mail.ToString(), chtEnc));}}else{mailMessage.To.Add(new MailAddress(toMail, toMail.ToString(), chtEnc)); }}/// <summary>/// 添加附件/// </summary>/// <param name="FilePath">文件路徑</param>private void AddAttach(string FilePath){attchments = GetAttachByPath(FilePath);if (attchments.Count > 0){if (mailMessage.Attachments.Count > 0)mailMessage.Attachments.Clear();foreach (Attachment item in attchments){mailMessage.Attachments.Add(item);}}}/// <summary>/// 根據(jù)文件路徑獲得要添加的附件文件列表/// </summary>/// <param name="FilePath">文件路徑</param>/// <returns>附件文件列表</returns>private List<Attachment> GetAttachByPath(string FilePath){List<Attachment> attachs = new List<Attachment>();//校驗(yàn)if (string.IsNullOrEmpty(FilePath)) { return new List<Attachment>(); }if (!FilePath.Contains("|")) { return new List<Attachment>(); }//去掉路徑最后一位的"|"List<string> paths = GetPaths(ref FilePath);foreach (string path in paths){attachs.Add(new Attachment(path, MediaTypeNames.Application.Octet));}return attachs;}/// <summary>/// 獲得附件文件路徑列表/// </summary>/// <param name="FilePath"></param>/// <returns></returns>private static List<string> GetPaths(ref string FilePath){FilePath = FilePath.Remove(FilePath.Length - 1);string[] filepaths = FilePath.Split('|');List<string> paths=new List<string>();foreach (string path in filepaths){paths.Add(path);}return paths;}//發(fā)送完畢后的事件void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e){if (e.Cancelled){System.Web.HttpContext.Current.Response.Write("發(fā)送的郵件已被取消!");}if (e.Error == null){System.Web.HttpContext.Current.Response.Write("郵件已成功發(fā)送!");////釋放資源//mailMessage.Dispose();mailMessage.Attachments.Clear(); //郵件發(fā)送完畢,釋放對(duì)附件的鎖定(這種方式會(huì)有問題,如果第二次發(fā)同一個(gè)文件,會(huì)報(bào)異常)DisposeAttchment();//郵件發(fā)送完畢,釋放對(duì)附件的鎖定//DeleteAttachFile(); }else{System.Web.HttpContext.Current.Response.Write(e.Error.Message + " 原因是:" + e.Error.InnerException);}}/// <summary>/// 刪除附件的源文件/// </summary>private static void DeleteAttachFile(){List<string> paths = GetPaths(ref AttachmentPath);foreach (string path in paths){if (System.IO.File.Exists(path)){System.IO.File.Delete(path);}}}/// <summary>/// 郵件發(fā)送完畢,釋放對(duì)附件的鎖定/// </summary>private void DisposeAttchment(){if(attchments.Count>0){foreach (Attachment attach in attchments){attach.Dispose();}}}}DESHelper類
/// <summary>/// DES對(duì)稱加密/// </summary>public static class DESHelper{/// <summary>/// 根據(jù)用戶名解密/// </summary>/// <param name="val"></param>/// <param name="userid"></param>/// <returns></returns>public static string Decrypt(string val, string userid = ""){var key = GetKey(userid);var iv = GetDefaultIV();return Decrypt(val, key, iv);}/// <summary>/// 根據(jù)用戶名加密/// </summary>/// <param name="val"></param>/// <param name="userid"></param>/// <returns></returns>public static string Encrypt(string val, string userid = ""){var key = GetKey(userid);var iv = GetDefaultIV();return Encrypt(val, key, iv);}/// <summary>/// Des加密方法/// </summary>/// <param name="val"></param>/// <param name="key"></param>/// <param name="IV"></param>/// <returns></returns>public static string Encrypt(string val, string key, string IV, CipherMode cipherMode = CipherMode.ECB){try{if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(key)){throw new Exception("密鑰和偏移向量不足8位");}if (key.Length > 8) key = key.Substring(0, 8);if (IV.Length > 8) IV = IV.Substring(0, 8);DESCryptoServiceProvider des = new DESCryptoServiceProvider();byte[] btKey = Encoding.Default.GetBytes(key);byte[] btIV = Encoding.Default.GetBytes(IV);StringBuilder builder = new StringBuilder();using (MemoryStream ms = new MemoryStream()){byte[] inData = Encoding.Default.GetBytes(val);using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write)){cs.Write(inData, 0, inData.Length);cs.FlushFinalBlock();}foreach (byte num in ms.ToArray()){builder.AppendFormat("{0:X2}", num);}} return builder.ToString();}catch // (Exception ex) {return "";}}/// <summary>/// Des解密方法/// cbc模式:(key值和iv值一致)/// </summary>/// <param name="val"></param>/// <param name="key"></param>/// <param name="IV"></param>/// <returns></returns>public static string Decrypt(string val, string key, string IV, CipherMode cipherMode = CipherMode.ECB){try{if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(key)){throw new Exception("密鑰和偏移向量不足8位");}if (key.Length > 8) key = key.Substring(0, 8);if (IV.Length > 8) IV = IV.Substring(0, 8);DESCryptoServiceProvider des = new DESCryptoServiceProvider();byte[] btKey = Encoding.Default.GetBytes(key);byte[] btIV = Encoding.Default.GetBytes(IV);using (MemoryStream ms = new MemoryStream()){byte[] inData = new byte[val.Length / 2];for (int i = 0; i < (val.Length / 2); i++){int num2 = Convert.ToInt32(val.Substring(i * 2, 2), 0x10);inData[i] = (byte)num2;}using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write)){cs.Write(inData, 0, inData.Length);cs.FlushFinalBlock();}return Encoding.Default.GetString(ms.ToArray());}}catch // (System.Exception ex) {return "";}}/// <summary>/// Md5加密/// </summary>/// <param name="str"></param>/// <returns></returns>public static string MD5(string str){if (string.IsNullOrEmpty(str)) return str;System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();string encoded = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", "");return encoded;}private static string GetKey(string key){string defaultKey = "C560F02F693B4A0BA62D2B3B5FB74534";string sTemp = defaultKey;if (!string.IsNullOrEmpty(key)){sTemp = string.Concat(key, defaultKey.Substring(key.Length, 32 - key.Length));}return MD5(sTemp).Substring(0, 8);}/// <summary> /// 獲得初始向量IV /// </summary> /// <returns>初試向量IV</returns> private static string GetDefaultIV(){string sTemp = "87DE696F56DE49C0B96EB85139A48805";return MD5(sTemp).Substring(0, 8);}}?
轉(zhuǎn)載于:https://www.cnblogs.com/zhengwei-cq/p/8946987.html
總結(jié)
- 上一篇: 写了这么久前端,你知道浏览器原理吗?
- 下一篇: C++ 外部函数通过指针修改类成员的值