public async Task <IActionResult> VerifyEmailKey(string key = "") { if (EmailKeyManager.IsValidKey(key)) { string email = EmailKeyManager.GetEmailByKey(key); var user = _context.Users.FirstOrDefault(u => u.Email == email); // 取得隨機字串 string newPassword = Path.GetRandomFileName(); // 修改使用者的密碼 await _userManager.RemovePasswordAsync(user); await _userManager.AddPasswordAsync(user, newPassword); // 令這個 Key 只能使用一次 EmailKeyManager.RemoveKey(key); _logger.LogInformation($"系統將[{user.Email}]的密碼修改為[{newPassword}]"); TempData["ForgotPasswordConfirmation"] = $"您的密碼已經被重設為{newPassword},請盡速登入並修改密碼!"; return(View("~/Areas/Identity/Pages/Account/ForgotPasswordConfirmation.cshtml")); } else { return(NotFound()); } }
public IActionResult SendVerifyEmail(IFormCollection post) { // 檢查這個IP的寄送次數 string ClientIP = HttpContext.Connection.RemoteIpAddress.ToString(); if (EmailKeyManager.GetSendCountByIP(ClientIP) > 2) { TempData["ForgotPasswordConfirmation"] = "您的寄送次數已達上限,請聯絡網站的管理員!"; return(View("~/Areas/Identity/Pages/Account/ForgotPasswordConfirmation.cshtml")); } else { EmailKeyManager.IncrementCount(ClientIP); } // 取出 POST 的資料並轉成字串,避免直接取用使得 LINQ 噴出錯誤 string userEmail = post["email"]; var user = _context.Users.FirstOrDefault(u => u.Email == userEmail); if (user != null) { // 從設定檔取得寄信的相關資訊 Dictionary <string, string> ConfigDict = ConfigManager.GetValueByKey(new List <string> { "SmtpEmail", "SmtpPassword", "SmtpHost", "MyAppDomain" }); string SmtpEmail = ConfigDict["SmtpEmail"]; string SmtpPassword = ConfigDict["SmtpPassword"]; string SmtpHost = ConfigDict["SmtpHost"]; string MyAppDomain = ConfigDict["MyAppDomain"]; // 取得隨機字串並存入記憶體 string emailVerifyKey = Path.GetRandomFileName(); EmailKeyManager.AddKey(emailVerifyKey, user.Email); // 寄信給該郵件 MailMessage message = new MailMessage { From = new MailAddress($"{SmtpEmail}", "阿貓購物網站", Encoding.UTF8), SubjectEncoding = Encoding.UTF8, BodyEncoding = Encoding.UTF8, Subject = "阿貓購物網站-取得新密碼的驗證信", Body = $"請點開此連結以取得新密碼{MyAppDomain}/User/VerifyEmailKey/?key={emailVerifyKey}", IsBodyHtml = true, }; message.To.Add(post["email"]); SmtpClient smtp = new SmtpClient { Port = 587, Host = $"{SmtpHost}", }; try { smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential($"{SmtpEmail}", $"{SmtpPassword}"); smtp.EnableSsl = true; smtp.Send(message); _logger.LogInformation($"系統寄送了新密碼的驗證信給[{userEmail}]"); TempData["ForgotPasswordConfirmation"] = "請查看您的 Email 以取得新密碼!"; } catch (Exception ex) { _logger.LogInformation($"系統寄送驗證信時發生錯誤 : {ex}"); TempData["ForgotPasswordConfirmation"] = "系統寄送驗證信時發生錯誤,請稍後再試QQ"; } } return(View("~/Areas/Identity/Pages/Account/ForgotPasswordConfirmation.cshtml")); }