eCommerce Website Part 18 Forgot Password

 eCommerce Website  Part 18 Forgot Password

Hi, Dear's here we learn how to implement eCommerce Website in Visual Studio using C# ASP.NET MVC. Ilyasoft software company provide full project step by step training on our YouTube Channel ilyasoft software company so now subscribe, share and like for more project base tutorials



In this video we are going to implement Forgot Password | Reset Password for more details click here: watch vedio

First we are going to add Password Recovery Table in Database.

 > PasswordRecoveryTable Code : 

 CREATE TABLE [dbo].[PasswordRecoveryTable](
 [PasswordRecoveryID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[UserID] [int] NOT NULL,
[RecoveryCode] [nvarchar](500) NOT NULL,
[RecoveryCodeExpiryDateTime] [datetime] NOT NULL,
[RecoveryStatus] [bit] NULL,
[OldPassword] [nvarchar](300) NULL)



Once Password Recovery Table add in Database then update Database Model. 
Next Add Model View of PasswordRecovery and ForgotPassword in Model Folder(eCommerceUI)
 
> PasswordRecoveryMV Code : 

public class AccountRecoveryMV
    {
        [Required(ErrorMessage="UserName is Required*")]
        public string UserName { get; set; }
    }

> ForgotPasswordMV Code : 

public class ForgotPasswordMV
    {
        public int UserID { get; set; }
        [Required(ErrorMessage = "Enter UserName")]
        public string UserName { get; set; }
        public string EmailAddress { get; set; }
        [Required(ErrorMessage = "Enter New Password")]
        public string NewPassword { get; set; }
        [Required(ErrorMessage = "Confirm Password")]
        public string ConfirmPassword { get; set; }
    }

Next Create CommonCode Folder in eCommerceUI and then create Email Class inside in CommonCode Folder, add below code(use for sending email) in Email Class. 

public class Send
        {
            public static bool EmailSend(string SenderEmail, string Subject, string Message, bool IsBodyHtml = false)
            {
                bool status = false;
                try
                {
                    string HostAddress = ConfigurationManager.AppSettings["Host"].ToString();
                    string FormEmailId = ConfigurationManager.AppSettings["MailFrom"].ToString();
                    string Password = ConfigurationManager.AppSettings["Password"].ToString();
                    string Port = ConfigurationManager.AppSettings["Port"].ToString();
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From = new MailAddress(FormEmailId);
                    mailMessage.Subject = Subject;
                    mailMessage.Body = Message;
                    mailMessage.IsBodyHtml = IsBodyHtml;
                    mailMessage.To.Add(new MailAddress(SenderEmail));
                    SmtpClient smtp = new SmtpClient();
                    smtp.Host = HostAddress;
                    smtp.UseDefaultCredentials = false;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    NetworkCredential networkCredential = new NetworkCredential();
                    networkCredential.UserName = mailMessage.From.Address;
                    networkCredential.Password = Password;
                    smtp.Credentials = networkCredential;
                    smtp.Port = Convert.ToInt32(Port);
                    smtp.EnableSsl = false;
                    smtp.Send(mailMessage);
                    status = true;
                    return status;
                }
                catch (Exception e)
                {
                    return status;
                }
            }
        }
  
Next add From email credential in web.config show below in code: 
 <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="Host" value="199.168.188.194" />
    <add key="Port" value="587" />
    <add key="MailFrom" value=" non-replay@ilyassoft.com" />
    <add key="Password" value="fj13T6d%8" />
  </appSettings>

Next add PasswordRecoveryController and add ForgotPassword & ResetPassword method in Password Controller, show in below code:

 > AccountRecovery Action Code : 

 public class PasswordRecoveryController : Controller
    {
        // GET: PasswordRecovery
        private Pro_EcommerceDbEntities DB = new Pro_EcommerceDbEntities();
        // GET: PasswordRecovery
        public ActionResult AccountRecovery()
        {

            var accountRecoveryMV = new AccountRecoveryMV();
            return View(accountRecoveryMV);
        }

        [HttpPost]
        public ActionResult AccountRecovery(AccountRecoveryMV accountRecoveryMV)
        {
            using (var transaction = DB.Database.BeginTransaction())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        var user = DB.UserTables.Where(u => u.UserName.Trim() == accountRecoveryMV.UserName || u.EmailAddress == accountRecoveryMV.UserName.Trim()).FirstOrDefault();
                        if (user != null)
                        {
                            string code = DateTime.Now.ToString("yyyyMMddHHmmssmm") + accountRecoveryMV.UserName;
                            var accountrecoverydetails = new PasswordRecoveryTable();
                            accountrecoverydetails.UserID = user.UserID;
                            accountrecoverydetails.OldPassword = user.Password;
                            accountrecoverydetails.RecoveryCode = code;
                            accountrecoverydetails.RecoveryCodeExpiryDateTime = DateTime.Now.AddDays(1);
                            accountrecoverydetails.RecoveryStatus = true;
                            DB.PasswordRecoveryTables.Add(accountrecoverydetails);
                            DB.SaveChanges();

                            var callbackUrl = Url.Action("ResetPassword", "User", new { recoverycode = code }, protocol: Request.Url.Scheme);
                            // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                            string body = string.Empty;
                            using (StreamReader reader = new StreamReader(Server.MapPath("~/MailTemplates/ForgotPasswordConfirmation.html")))
                            {
                                body = reader.ReadToEnd();
                            }
                            body = body.Replace("{ConfirmationLink}", callbackUrl);
                            body = body.Replace("{UserName}", user.EmailAddress);
                            bool IsSendEmail = Common.Email.Send.EmailSend(user.EmailAddress, "Reset Password", body, true);
                            if (IsSendEmail)
                            {
                                transaction.Commit();
                                ModelState.AddModelError(string.Empty, "Recovery Link Sent on your email address(" + user.EmailAddress + ")");
                            }
                            else
                            {
                                transaction.Rollback();
                                ModelState.AddModelError(string.Empty, "Some Issue is Occure! Please Try Again later.");
                            }
                        }
                        else
                        {
                            transaction.Rollback();
                            ModelState.AddModelError("UserName", "Not Found!");
                        }
                    }

                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    ModelState.AddModelError(string.Empty, "Some Issue is Occure! Please Try Again later.");
                }
            }
            return View(accountRecoveryMV);
        }
    }

AccountRecovery View Code : 

@model eCommerceUI.Models.AccountRecoveryMV
@{
    ViewBag.Title = "Account";
}
<div class="breadcrumbs mt-15">
    <div class="container">
        <ul class="list-unstyled d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
            <li><a href="@Url.Content("~/Home/Index")">Home</a></li>
            <li><span>Account Recovery</span></li>
        </ul>
    </div>
</div>
<div class="login mb-60">
    <div class="container">
        <div id="CustomerLoginForm">
            <h1 class="h3 mt-30 mb-40 text-center">Forgot Password</h1>
            @using (Html.BeginForm("AccountRecovery", "PasswordRecovery", FormMethod.Post))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                <div class="form-group">
                    @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control", id = "newpassword", placeholder = "Enter UserName or EmailAddress", type = "text", required = "required" } })
                    @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })
                    <i class="far fa-unlock"></i>
                </div>
                <button class="btn btn-filled" type="submit">Recovery Password</button>
            }
        </div>
        <div class="pt-35 mt-35 border-top">
            <h2 class="h3 text-center">Login</h2>
            <div class="mb-35">
                <p class="h6 mb-15">Enjoy The Benefits Of Registering:</p>
                <ul class="mb-0">
                    <li>Order: view Order History, track and manage purchases and returns.</li>
                    <li>
                        Address Book and Card Wallet: safely store delivery and payment details for faster
                        checkout
                    </li>
                    <li>Saved for later: wish list your preferred items and track their availability</li>
                </ul>
            </div>
            <a href="@Url.Content("~/User/Login")" class="btn btn--full">LOGIN</a>
        </div>
    </div>
</div>

  
> Send Email Html Page Code : (Create Template Folder in eCommereceUI Layer, create html page (ForgotPasswordConfirmation.html) and add this below code) : 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
<head>
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Account</title>
    <style type="text/css">
        img {
            max-width: 100%;
        }
        body {
            -webkit-font-smoothing: antialiased;
            -webkit-text-size-adjust: none;
            width: 100% !important;
            height: 100%;
            line-height: 1.6em;
        }
        body {
            background-color: #f6f6f6;
        }
        @media only screen and (max-width: 640px) {
            body {
                padding: 0 !important;
            }

            h1 {
                font-weight: 800 !important;
                margin: 20px 0 5px !important;
            }

            h2 {
                font-weight: 800 !important;
                margin: 20px 0 5px !important;
            }

            h3 {
                font-weight: 800 !important;
                margin: 20px 0 5px !important;
            }

            h4 {
                font-weight: 800 !important;
                margin: 20px 0 5px !important;
            }

            h1 {
                font-size: 22px !important;
            }

            h2 {
                font-size: 18px !important;
            }

            h3 {
                font-size: 16px !important;
            }

            .container {
                padding: 0 !important;
                width: 100% !important;
            }

            .content {
                padding: 0 !important;
            }

            .content-wrap {
                padding: 10px !important;
            }

            .invoice {
                width: 100% !important;
            }
        }
    </style>
</head>
<body itemscope itemtype="http://schema.org/EmailMessage" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; width: 100% !important; height: 100%; line-height: 1.6em; background-color: #f6f6f6; margin: 0;" bgcolor="#f6f6f6">
    <table class="body-wrap" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; width: 100%; background-color: #f6f6f6; margin: 0;" bgcolor="#f6f6f6">
        <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
            <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0;" valign="top"></td>
            <td class="container" width="600" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; display: block !important; max-width: 600px !important; clear: both !important; margin: 0 auto;" valign="top">
                <div class="content" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; max-width: 600px; display: block; margin: 0 auto; padding: 20px;">
                    <table class="main" width="100%" cellpadding="0" cellspacing="0" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; border-radius: 3px; background-color: #fff; margin: 0; border: 1px solid #e9e9e9;" bgcolor="#fff">
                        <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                            <td class="alert alert-warning" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 16px; vertical-align: top; color: #fff; font-weight: 500; text-align: center; border-radius: 3px 3px 0 0; background-color: #3c8dbc; margin: 0; padding: 20px;" align="center" bgcolor="#FF9F00" valign="top">
                                Reset Password
                            </td>
                        </tr>
                        <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                            <td class="content-wrap" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 20px;" valign="top">
                                <table width="100%" cellpadding="0" cellspacing="0" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                                    <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                                        <td class="content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
                                            Hello, <strong style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">{UserName}</strong>
                                        </td>
                                    </tr>
                                    <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                                        <td class="content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
                                            Please click bellow button for create new password.
                                        </td>
                                    </tr>
                                    <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                                        <td class="content-block" style="">
                                            <a href="{ConfirmationLink}" class="btn btn-primary" style="background-color: #3c8dbc; border: none;color: white; padding: 10px 41px;text-align: center;text-decoration: none;display: inline-block; font-size: 16px;margin: 4px 2px;cursor: pointer;">Reset Password Link </a>
                                        </td>
                                    </tr>
                                    <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                                        <td class="content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">
                                            <br /><b>Thanks & Regards,</b><br />
                                            Ilyasoft Store<br />
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table><div class="footer" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; width: 100%; clear: both; color: #999; margin: 0; padding: 20px;">
                        <table width="100%" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                            <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">
                                <td class="aligncenter content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: top; color: #999; text-align: center; margin: 0; padding: 0 0 20px;" align="center" valign="top"></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </td>
            <td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0;" valign="top"></td>
        </tr>
    </table>
</body>
</html>



Next add ResetPassword method in user Controller, show in below code:

 > Reset Password Action Code : 
public ActionResult ResetPassword(string recoverycode)
        {

            var forgotpassword = new ForgotPasswordMV();
            var userrecovery = DB.PasswordRecoveryTables.Where(p => p.RecoveryCode == recoverycode && p.RecoveryCodeExpiryDateTime > DateTime.Now && p.RecoveryStatus == true).FirstOrDefault();
            if (userrecovery == null)
            {
                return RedirectToAction("Login");
            }
            var user = DB.UserTables.Find(userrecovery.UserID);
            forgotpassword.UserID = userrecovery.UserID;
            forgotpassword.UserName = user.UserName;
            forgotpassword.EmailAddress = user.EmailAddress;
            return View(forgotpassword);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ResetPassword(ForgotPasswordMV forgotPasswordMV)
        {
            using (var transaction = DB.Database.BeginTransaction())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        var user = DB.UserTables.Find(forgotPasswordMV.UserID);
                        if (user != null)
                        {
                            if (forgotPasswordMV.NewPassword != forgotPasswordMV.ConfirmPassword)
                            {
                                ModelState.AddModelError("ConfirmPassword", "Not Match!");
                                return View(forgotPasswordMV);
                            }

                            var userrecovery = DB.PasswordRecoveryTables.Where(u => u.UserID == forgotPasswordMV.UserID && u.RecoveryStatus == true);
                            foreach (var item in userrecovery)
                            {
                                item.RecoveryStatus = false;
                                item.OldPassword = user.Password;
                                DB.Entry(item).State = System.Data.Entity.EntityState.Modified;
                                DB.SaveChanges();
                            }
                            user.Password = forgotPasswordMV.NewPassword;
                            DB.Entry(user).State = System.Data.Entity.EntityState.Modified;
                            DB.SaveChanges();
                            transaction.Commit();
                            return RedirectToAction("Login");
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Please Try-Again!");
                            return View(forgotPasswordMV);
                        }
                    }
                    ModelState.AddModelError(string.Empty, "Fill Field's Properly!");
                }
                catch
                {
                    ModelState.AddModelError(string.Empty, "Please Try Again later.");
                }
            }
            return View(forgotPasswordMV);
        }

 ResetPassword View Code : 
@model eCommerceUI.Models.ForgotPasswordMV

@{
    ViewBag.Title = "Login";
}
<div class="breadcrumbs mt-15">
    <div class="container">
        <ul class="list-unstyled d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
            <li><a href="@Url.Content("~/Home/Index")">Home</a></li>
            <li><span>Account Recovery</span></li>
        </ul>
    </div>
</div>
<div class="login mb-60">
    <div class="container">
        <div id="CustomerLoginForm">
            <h1 class="h3 mt-30 mb-40 text-center">Enter New Password</h1>
            @using (Html.BeginForm("ForgotPassword", "User", FormMethod.Post))
            {
                @Html.AntiForgeryToken()
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                @Html.HiddenFor(model => model.UserID)
                @Html.HiddenFor(model => model.UserName)
                @Html.HiddenFor(model => model.EmailAddress)

                <div class="form-group">
                    @Html.EditorFor(model => model.NewPassword, new { htmlAttributes = new { @class = "form-control", id = "newpassword", placeholder = "Enter New Password", type = "password", required = "required" } })
                    @Html.ValidationMessageFor(model => model.NewPassword, "", new { @class = "text-danger" })
                    <i class="far fa-unlock"></i>
                </div>

                <div class="form-group">
                    @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control", id = "confirmpassword", placeholder = "Confirm New Password", type = "password", required = "required" } })
                    @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
                    <i class="far fa-unlock"></i>
                </div>
                <button class="btn btn-filled" type="submit">Create Password</button>
            }
        </div>
        <div class="pt-35 mt-35 border-top">
            <h2 class="h3 text-center">Sign Up</h2>
            <div class="mb-35">
                <p class="h6 mb-15">Enjoy The Benefits Of Registering:</p>
                <ul class="mb-0">
                    <li>Order: view Order History, track and manage purchases and returns.</li>
                    <li>
                        Address Book and Card Wallet: safely store delivery and payment details for faster
                        checkout
                    </li>
                    <li>Saved for later: wish list your preferred items and track their availability</li>
                </ul>
            </div>
            <a href="@Url.Content("~/User/CustomerRegister")" class="btn btn--full">SIGN UP NOW!</a>
        </div>
    </div>
</div>



Comments