Sunday 2 August 2015

Form Authentication against User Login in ASP.net

  1. How to authenticate a User using Forms Authentication.
  2. Deny Access to anonymous Users to access certain pages (Home page) and grant      permission to access certain pages (Registration Page, Password Change Page)      in our web application.
  3. How to verify user account using Email
  4. Locking User account if they had entered Wrong Password for 3 times in a row,      this is for high security sites like banking sites to prevent from hackers.
  5. Unlocking Locked User account with Registered Mail id.
  6. Logging Out Users using Logout Button.
  7. Maintaining Separate Session Between Users.



Login.aspx Code


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <style type="text/css">

        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 69px;
        }
        .style3
        {
            width: 335px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <br />
        <h1>Login Page</h1>
        <br />
    
        <table class="style1">
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Name</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox ID="TextBox4" runat="server" Visible="False" Width="2px"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Password</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextBox2_TextChanged" 
                        TextMode="Password"></asp:TextBox>
        <asp:TextBox ID="TextBox3" runat="server" Visible="False" Width="4px"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
        <br />

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Login" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" Text="Clear" onclick="Button2_Click" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button3" runat="server" Text="Forgot Password" Width="122px" 
            onclick="Button3_Click" />
        <br />
        <br />
        <asp:HyperLink ID="HyperLink1" runat="server" 
            NavigateUrl="~/anon/Register.aspx">Not Registered Yet...Please Click Here to Register</asp:HyperLink>
        <br />
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large" 
            ForeColor="#FF3300"></asp:Label>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Size="Large" 
            ForeColor="#FF3300"></asp:Label>
        <br />
        <br />
        <br />
        <br />
    </div>
    </form>
</body>
</html>

Login.aspx.cs Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Configuration;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Text;


namespace Login_Reg_PwdLink_Validation
{
    public partial class Login : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            Label2.Text = "";
            if (checkAccountVerified())
            {
                if (checkuser())
                {

                    string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(cs))
                    {
                        SqlCommand cmd = new SqlCommand("select id,name,Islocked,password from login where name=@1 and password=@2", con);
                        SqlDataReader dr;
                        con.Open();
                        string decrypted = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "SHA1");
                        cmd.Parameters.AddWithValue("@1", TextBox1.Text);
                        cmd.Parameters.AddWithValue("@2", decrypted);
                        dr = cmd.ExecuteReader();

                        if (dr.Read())
                        {
                            Session["id"] = dr[0];
                            Session["name"] = dr[1];
                            TextBox3.Text = dr[2].ToString();
                            if (Convert.ToInt32(TextBox4.Text) >= 3)
                            {
                                lockuseraccount();
                            }
                            else if (Convert.ToInt32(TextBox4.Text) < 3)
                            {

                                updateaftercorrectlogin();
                                FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);

                            }
                            else
                            {
                                Label1.Text = "Your Account is locked !! due to too many invalid login attempts";
                                Label2.Text = "Please reset your password to login";
                            }

                        }

                        else if (Convert.ToInt32(TextBox4.Text) >= 2)
                        {
                            lockuseraccount();
                            lockuser();
                        }
                        else if (Convert.ToInt32(TextBox4.Text) <= 3)
                        {
                            lockuser();
                            // Label1.Text = "Invalid User Name or Password";
                        }

                    }

                }
            }
            else
            {
                Label1.Text = "You Account is not yet verified !! Please Click the Link on Your Mail !!";
            }
        }
        public void lockuser()
        {
            checklockattempts();
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                int total = 2;
                int locked = Convert.ToInt32(TextBox3.Text);
                int remaining = total - locked;
                SqlCommand cmd1 = new SqlCommand("update login set retryattempts=" + locked + "+1 where name=@1", con);
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);
                cmd1.Parameters.AddWithValue("@2",1);
                cmd1.ExecuteNonQuery();

                if (locked >= 3)
                {
                    lockuseraccount();
                }

                else
                {
                    if (remaining == 0)
                    {
                        Label1.Text = "Invalid UserName or Password";
                        checklockattempts();
                        Label2.Text = "Your Account haas been locked!!!";
                    }
                    else
                    {
                        Label1.Text = "Invalid UserName or Password";
                        checklockattempts();
                        Label2.Text = "" + remaining + " Login Attempts Left";
                    }
                }

            }
        }

        public void lockuseraccount()
        { 
        string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd1 = new SqlCommand("update login set Islocked=1,lockeddatetime=getdate() where name=@1", con);
            con.Open();
            cmd1.Parameters.AddWithValue("@1", TextBox1.Text);
            
            cmd1.ExecuteNonQuery();

            Label1.Text = "Your Account is locked !! due to too many invalid login attempts";
            Label2.Text = "Please reset your password to login";
        }
       
        }

        public void updateaftercorrectlogin()
       
        { 
        string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd1 = new SqlCommand("update login set RetryAttempts=0,IsLocked=0,LockedDateTime=null where name=@1", con);
            con.Open();
            cmd1.Parameters.AddWithValue("@1", TextBox1.Text);
            
            cmd1.ExecuteNonQuery();
           
        }
       
        }
        

        public void checklockattempts()
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("select retryattempts from login where name=@1", con);
                SqlDataReader dr;
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {
                    TextBox3.Text = dr[0].ToString();
                    
                }

                else
                {
                    Label1.Text = "User Doesnot Exists";
                   

                }

            }
        }


        public bool checkuser()
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("select name,Retryattempts from login where name=@1", con);
                SqlDataReader dr;
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {
                    TextBox4.Text = dr[1].ToString();
                    return true;

                }

                else
                {
                    Label1.Text = "User Doesnot Exists";
                    return false;
                   
                }

            }
        }

        public bool checkAccountVerified()
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("select accountverified from login where name=@1", con);
                SqlDataReader dr;
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                dr = cmd1.ExecuteReader();

                if (dr.Read() && dr[0].ToString() == "notverified")
                {
                        return false;
                }
                
                else
                {
                    return true;
                }

            }
        }

        protected void TextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            Response.Redirect("anon/ResetPwdbyLink.aspx");
        }

        protected void chkRememberMe_CheckedChanged(object sender, EventArgs e)
        {

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "";
            TextBox2.Text = "";
        }
    }
}



Register.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 103px;
        }
        .style3
        {
            width: 323px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <br />
        <h1>
            User Registeration Page
        </h1>
        <table class="style1">
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Name</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Email</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" ontextchanged="TextBox2_TextChanged"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Password</td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server" TextMode="Password"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Button ID="Button1" runat="server" Text="Register" 
                        onclick="Button1_Click" />
                </td>
                <td>
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Button ID="Button2" runat="server" Text="Clear" onclick="Button2_Click" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
        <br /><asp:Label ID="Label1" runat="server" Font-Bold="True" ForeColor="#FF3300" 
            Font-Size="X-Large"></asp:Label>
    </div>
    </form>
</body>
</html>

Register.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Net;
using System.Web.Security;

namespace Login_Reg_PwdLink_Validation
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void TextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkifusernameExists())
                {
                    Label1.Text = "UserName Already Exists...";
                }
                else {
                    string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(cs))
                    {
                        SqlCommand cmd = new SqlCommand("INSERT INTO login (name,email,password) values (@1,@2,@3)", con);
                        con.Open();
                        string encrypted = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox3.Text, "SHA1");
                        cmd.Parameters.AddWithValue("@1", TextBox1.Text);
                        cmd.Parameters.AddWithValue("@2", TextBox2.Text);
                        cmd.Parameters.AddWithValue("@3", encrypted);
                        cmd.ExecuteNonQuery();
                        sendmailtoverifyaccount();

                    }
                }
            }
            catch (Exception)
            {
                Label1.Text = "Registeration Failed";
            }
        }

        public void sendmailtoverifyaccount()
        {
            generateuid();
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("select name,email,uid from login where name=@1", con);
                SqlDataReader dr;
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {

                    sendpasswordresetmail(dr["email"].ToString(), TextBox1.Text, dr["uid"].ToString());
                 
                    string message = "A reset password link has been sent to your registered mail id. Please click on that link to Verify Your Account";
                    string url = "http://www.gmail.com/";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
                }

                else
                {
                    Label1.Text = "User Name doesnot Exists";


                }
            }
        }

        public void generateuid()
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("update login set uid=NEWID() where name=@1", con);
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                cmd1.ExecuteNonQuery();
            }
        }
        private void sendpasswordresetmail(string tomail, string username, string uniqueid)
        {
            MailMessage mailmsg = new MailMessage("govindrajaram93@gmail.com", tomail);

            StringBuilder sbmailbody = new StringBuilder();
            sbmailbody.Append("Hi " + username + ",<br/><br/>");
            sbmailbody.Append("Please click on following link to reset your password");
            sbmailbody.Append("<br/>");
            sbmailbody.Append("http://localhost:49364/anon/accountactivated.aspx?uid=" + uniqueid);
            sbmailbody.Append("<br/><br/>");
            sbmailbody.Append("<b>Pageone Technolgies</b>");

            mailmsg.IsBodyHtml = true;

            mailmsg.Body = sbmailbody.ToString();
            mailmsg.Subject = "Reset Your Password";

            SmtpClient smtpclient = new SmtpClient("smtp.gmail.com", 587);

            smtpclient.Credentials = new NetworkCredential()
            {
                UserName = "govindrajaram93@gmail.com",
                Password = "9952012073"
            };

            smtpclient.EnableSsl = true;//this is for enable the https
            smtpclient.Send(mailmsg);
        }

        public bool checkifusernameExists()
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("select name from login where name=@1", con);
                SqlDataReader dr;
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {
                    return true;
                }

                else
                {
                    return false;
                }

            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "";
            TextBox2.Text = "";
            TextBox3.Text = "";      
        }
    }
}

Home.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            color: #9999FF;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Welcome...............<asp:Label ID="Label1" runat="server" 
            style="font-weight: 700"></asp:Label>
&nbsp;
        <asp:Button ID="Button1" runat="server" style="font-weight: 700" 
            Text="Logout" />
     
        <h1>
<span class="style1">User Home Page</span></h1>
        
    </div>
    </form>
</body>
</html>


Home.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Login_Reg_PwdLink_Validation
{
    public partial class Home : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                if (Session["name"] != null)
                {
                    Label1.Text = Session["name"].ToString();
                }
                else
                {
                    Response.Redirect("Login.aspx");
                }
            }
            catch
            {
                Response.Redirect("Login.aspx");

            }

        }

        public void killsession()
        {
            Session["name"] = null;        
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Session["name"] = null;
            Response.Redirect("Login.aspx");
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("anon/changepassword.aspx");
        }
    }
}

Web.config 
<?xml version="1.0"?>
<configuration>
<connectionStrings>
    
    <add name="connectstr" connectionString="Data Source=GOKUL-PC\GOKULSQL;Initial Catalog=test;Integrated Security=True"/>
  </connectionStrings>
</configuration>

<system.web>
<authentication mode="Forms" >
          <forms loginUrl="Login.aspx" defaultUrl="Home.aspx">
            <credentials passwordFormat="Clear"></credentials>
            
          </forms>
      </authentication >
      <authorization>
        <deny users="?"/>
      </authorization>
</system.web>

Web.config to allow anonomous users
<?xml version="1.0"?>
<configuration>
    <system.web>

      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
</configuration>

accountactivated.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="XX-Large" 
            style="font-weight: 700"></asp:Label>
    </div>
    </form>
</body>
</html>

accountactivated.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;

namespace Login_Reg_PwdLink_Validation.anon
{
    public partial class accountactivated : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (checkpwdlinkvalid())
                {
                    mailverified();
                }
                else
                {
                    Label1.Text = " You have clicked a Invalid Link or expired link";
                    Label1.ForeColor = System.Drawing.Color.Red;

                }
            }
            catch(Exception) { }
        }

        private void mailverified()
        {
           try
            {
                string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd1 = new SqlCommand("update login set uid=null,accountverified='Verified' where uid='" + Request.QueryString["uid"] + "'", con);
                    con.Open();
                   
                    cmd1.ExecuteNonQuery();
                    string message = "Email Verified.... We Redirecting you to login page";
                    string url = "http://localhost:49364/Login.aspx";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
                }

            }
            catch (Exception)
            {
                Label1.Text = "";
            }
        }
        

        public bool checkpwdlinkvalid()
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {

                SqlCommand cmd1 = new SqlCommand("select uid from login where uid='" + Request.QueryString["uid"] + "'", con);
                SqlDataReader dr;
                con.Open();
               
                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {
                    return true;

                }

                else
                {
                    Label1.ForeColor = System.Drawing.Color.Red;
                    Label1.Text = "The Link has been Expired.. !!";
                    return false;

                }

            }
        }
    }
}

changepassword.aspx

<!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">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 162px;
        }
        .style3
        {
            width: 272px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Welcome.....<asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <table class="style1">
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Enter Current Password</td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server" Width="149px" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                        ControlToValidate="TextBox1" ErrorMessage="Enter your password"></asp:RequiredFieldValidator>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Enter New Password</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server" Width="152px" TextMode="Password"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                        ControlToValidate="TextBox1" ErrorMessage="Please Enter Password"></asp:RequiredFieldValidator>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    Retype New Password</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Width="155px" TextMode="Password"></asp:TextBox>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" 
                        ControlToCompare="TextBox1" ControlToValidate="TextBox2" 
                        ErrorMessage="Both Passwords Should Match"></asp:CompareValidator>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;</td>
                <td class="style2">
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Save" 
                        Width="88px" />
                </td>
                <td>
                    <asp:Button ID="Button2" runat="server" Text="Clear" Width="87px" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
        <br />
        <asp:Label ID="Label2" runat="server" Font-Bold="True" ForeColor="#FF3300"></asp:Label>
        <br />
        <br />
        <br />
    
    </div>
    </form>
</body>
</html>

Changepassword.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Configuration;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Text;


namespace Login_Reg_PwdLink_Validation
{
    public partial class changepassword : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["name"] != null)
                {
                    Label1.Text = Session["name"].ToString();
                }
                else
                {
                    Response.Redirect("Login.aspx");
                }
            }
            catch
            {
                Response.Redirect("Login.aspx");

            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (checkcurrentpwd())
            {
                string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd = new SqlCommand("update login set password=@1 where id=" + Session["id"].ToString() + "", con);
                    string encrypted = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, "SHA1");
                    cmd.Parameters.AddWithValue("@1", encrypted);
                    con.Open();
                    cmd.ExecuteNonQuery();
                    string message = "Password Changed Successfully !!";
                    string url = "http://localhost:49364/home.aspx";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);

                }
            }
        }
        public bool checkcurrentpwd() 
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("select password from login where password=@1", con);
                SqlDataReader dr;
                con.Open();
                string decrypted = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox3.Text, "SHA1");

                cmd1.Parameters.AddWithValue("@1", decrypted);

                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {
                    return true;

                }

                else
                {
                    Label2.Text = "Current Password is not Valid";
                    return false;

                }

            }
        }
    }
}

changepwd.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 156px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table style="width: 677px">
            <tr>
                <td colspan="2"> <asp:Label ID="Label4" runat="server" Font-Bold="True" ForeColor="#0033CC" 
                        Text="Change Password "></asp:Label>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    <asp:Label ID="Label2" runat="server" Text="New Password "></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server" TextMode="Password" Width="150px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                        ControlToValidate="TextBox1" ErrorMessage="Password Required" ForeColor="Red" 
                        Text="Password Required"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td class="style1">
&nbsp;<asp:Label ID="Label3" runat="server" Text="Confirm New Password"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" style="margin-left: 1px" 
                        TextMode="Password" Width="150px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                        ControlToValidate="TextBox2" Display="Dynamic" 
                        ErrorMessage="Confirm password Required" ForeColor="Red" 
                        Text="Confirm password Required"></asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" 
                        ControlToCompare="TextBox1" ControlToValidate="TextBox2" Display="Dynamic" 
                        ErrorMessage="Password and Confirm Password must match" ForeColor="Red" 
                        Operator="Equal" Text="Password and Confirm Password must match" Type="String"></asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Button1" runat="server" OnClick="btnSave_Click" Text="Save" 
                        Width="70px" />
                </td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;</td>
            </tr>
        </table>
        <b>
        <asp:Label ID="Label1" runat="server"></asp:Label>
        </div>
    </form>
</body>
</html>

changepwd.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;

namespace Login_Reg_PwdLink_Validation
{
    public partial class changepwd : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (checkpwdlinkvalid())
            {
            }
            else
            {
                Label1.Text = " You have clicked a Invalid Link or expired link";
                Label1.ForeColor = System.Drawing.Color.Red;
                TextBox1.Visible = false;
                TextBox2.Visible = false;
                Button1.Visible = false;
                Label2.Visible = false;
                Label3.Visible = false;
                Label4.Visible = false;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            changepasswordandUpdateuserdata();
           
        }


        public void changepasswordandUpdateuserdata()
        {
            try
            {
                string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    SqlCommand cmd1 = new SqlCommand("update login set password=@1,uid=null,RetryAttempts=0,IsLocked=0,LockedDateTime=null where uid='" + Request.QueryString["uid"] + "'", con);
                    con.Open();
                    string encrypted = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text, "SHA1");
                    cmd1.Parameters.AddWithValue("@1", encrypted);

                    cmd1.ExecuteNonQuery();
                    string message = "Password has been changed successfull,You will now be redirected to Login Page.";
                    string url = "http://localhost:49364/Login.aspx";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
                }

            }
            catch (Exception ex)
            {
                Label1.Text = "Error Changing Password , Please Try again";
            }
        }

        public bool checkpwdlinkvalid()
        {
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {

                SqlCommand cmd1 = new SqlCommand("select uid from login where uid='" + Request.QueryString["uid"] + "'", con);
                SqlDataReader dr;
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {
                    return true;

                }

                else
                {
                    Label1.ForeColor = System.Drawing.Color.Red;
                    Label1.Text = "The Link has been Expired.. !!";
                    return false;

                }

            }

        }
    }
}

ResetPwdbyLink.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table style="width: 319px">
            <tr>
                <td colspan="2">
                    <b>Reset My Password</b>
                </td>
            </tr>
            <tr>
                <td>
                    User Name
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server" Width="150px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Visible="False" Width="51px"></asp:TextBox>
                </td>
                <td>
                    <asp:Button ID="Button1" runat="server" OnClick="btnResetPassword_Click" 
                        Text="Reset Password" />
                </td>
            </tr>
            <tr>
                <td align="left" valign="top">
                    &nbsp;</td>
            </tr>
        </table>
        <asp:Label ID="Label1" runat="server" Font-Bold="True"></asp:Label>
    </div>
    </form>
</body>
</html>

ResetPwdbyLink.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Net;

namespace Login_Reg_PwdLink_Validation
{
    public partial class ResetPwdbyLink : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnResetPassword_Click(object sender, EventArgs e)
        {
            generateuid();
            string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd1 = new SqlCommand("select name,email,uid from login where name=@1", con);
                SqlDataReader dr;
                con.Open();
                cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                dr = cmd1.ExecuteReader();

                if (dr.Read())
                {

                    sendpasswordresetmail(dr["email"].ToString(), TextBox1.Text, dr["uid"].ToString());
                    //Label1.ForeColor = System.Drawing.Color.Green;
                    //Label1.Text = "reset password link is sent to your registered email";
                    string message = "A reset password link has been sent to your registered mail id. Please click on that link to change your password.You Will now be redirected to gmail";
                    string url = "http://www.gmail.com/";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
                }

                else
                {
                    Label1.Text = "User Name doesnot Exists";


                }
            }
        }

        public void generateuid()
        { 
              string cs = ConfigurationManager.ConnectionStrings["connectstr"].ConnectionString;
              using (SqlConnection con = new SqlConnection(cs))
              {
                  SqlCommand cmd1 = new SqlCommand("update login set uid=NEWID() where name=@1", con);
                  con.Open();
                  cmd1.Parameters.AddWithValue("@1", TextBox1.Text);

                  cmd1.ExecuteNonQuery();
              }
        }
        private void sendpasswordresetmail(string tomail, string username, string uniqueid)
        {
            MailMessage mailmsg = new MailMessage("Your Email iD here", tomail);
          
            StringBuilder sbmailbody = new StringBuilder();
            sbmailbody.Append("Hi " + username + ",<br/><br/>");
            sbmailbody.Append("Please click on following link to reset your password");
            sbmailbody.Append("<br/>");
            sbmailbody.Append("http://localhost:49364/anon/changepwd.aspx?uid=" + uniqueid);
            sbmailbody.Append("<br/><br/>");
            sbmailbody.Append("<b>EGN Solutions</b>");

            mailmsg.IsBodyHtml = true;

            mailmsg.Body = sbmailbody.ToString();
            mailmsg.Subject = "Reset Your Password";

            SmtpClient smtpclient = new SmtpClient("smtp.gmail.com", 587);

            smtpclient.Credentials = new NetworkCredential()
            {
                UserName = "Input Your Email Id",
                Password = "Input Password"
            };

            smtpclient.EnableSsl = true;//this is for enable the https 
            smtpclient.Send(mailmsg);
        }
    }
}

No comments:

Post a Comment