Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Changing password by providing current password - Part 97

Suggested Videos
Part 94 - Unlocking the locked user accounts
Part 95 - Implementing password reset link
Part 96 - Implementing change password page

In this video we will discuss about, Changing password by providing current password. In real time, users can change their password any time, by providing their current password.



Stored procedure to change password, using their current password
Create Proc spChangePasswordUsingCurrentPassword
@UserName nvarchar(100),
@CurrentPassword nvarchar(100),
@NewPassword nvarchar(100)
as
Begin
if(Exists(Select Id from tblUsers 
 where UserName = @UserName
 and [Password] = @CurrentPassword))
Begin
Update tblUsers
Set [Password] = @NewPassword
where UserName = @UserName

Select 1 as IsPasswordChanged
End
Else
Begin
Select 0 as IsPasswordChanged
End
End



ChangePassword.aspx HTML
<div style="font-family: Arial">
<table style="border: 1px solid black">
    <tr>
        <td colspan="2">
            <b>Change Password</b>
        </td>
    </tr>
    <tr id="trCurrentPassword" runat="server">
        <td>
            Current Password
        </td>
        <td>
            :<asp:TextBox ID="txtCurrentPassword" TextMode="Password" 
            runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorCurrentPassword" 
                runat="server" ErrorMessage="Current Password required"
                Text="*" ControlToValidate="txtCurrentPassword" ForeColor="Red">
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            New Password
        </td>
        <td>
            :<asp:TextBox ID="txtNewPassword" TextMode="Password" 
            runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorNewPassword" 
                runat="server" ErrorMessage="New Password required"
                Text="*" ControlToValidate="txtNewPassword" ForeColor="Red">
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            Confirm New Password
        </td>
        <td>
            :<asp:TextBox ID="txtConfirmNewPassword" TextMode="Password" runat="server">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorConfirmNewPassword" 
                runat="server" ErrorMessage="Confirm New Password required" Text="*" 
                ControlToValidate="txtConfirmNewPassword"
                ForeColor="Red" Display="Dynamic"></asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidatorPassword" runat="server" 
                ErrorMessage="New Password and Confirm New Password must match"
                ControlToValidate="txtConfirmNewPassword" ForeColor="Red" 
                ControlToCompare="txtNewPassword"
                Display="Dynamic" Type="String" Operator="Equal" Text="*">
            </asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td>
                    
        </td>
        <td>
            &nbsp;<asp:Button ID="btnSave" runat="server" 
            Text="Save" onclick="btnSave_Click" Width="70px" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblMessage" runat="server">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:ValidationSummary ID="ValidationSummary1" 
            ForeColor="Red" runat="server" />
        </td>
    </tr>
</table>
</div>

ChangePassword.aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["uid"] == null && User.Identity.Name == "")
    {
        Response.Redirect("~/Login.aspx");
    }
    if (!IsPostBack)
    {
        if (Request.QueryString["uid"] != null)
        {
            if (!IsPasswordResetLinkValid())
            {
                lblMessage.ForeColor = System.Drawing.Color.Red;
                lblMessage.Text = "Password Reset link has expired or is invalid";
            }
            trCurrentPassword.Visible = false;
        }
        else if (User.Identity.Name != "")
        {
            trCurrentPassword.Visible = true;
        }
    }
}

protected void btnSave_Click(object sender, EventArgs e)
{
    if ((Request.QueryString["uid"] != null && ChangeUserPassword()) || 
        (User.Identity.Name != "" && ChangeUserPasswordUsingCurrentPassword()))
    {
        lblMessage.Text = "Password Changed Successfully!";
    }
    else
    {
        lblMessage.ForeColor = System.Drawing.Color.Red;
        if (trCurrentPassword.Visible)
        {
            lblMessage.Text = "Invalid Current Password!";
        }
        else
        {
            lblMessage.Text = "Password Reset link has expired or is invalid";
        }
    }
}

private bool ExecuteSP(string SPName, List<SqlParameter> SPParameters)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand(SPName, con);
        cmd.CommandType = CommandType.StoredProcedure;

        foreach (SqlParameter parameter in SPParameters)
        {
            cmd.Parameters.Add(parameter);
        }

        con.Open();
        return Convert.ToBoolean(cmd.ExecuteScalar());
    }
}

private bool IsPasswordResetLinkValid()
{
    List<SqlParameter> paramList = new List<SqlParameter>()
    {
        new SqlParameter()
        {
            ParameterName = "@GUID",
            Value = Request.QueryString["uid"]
        }
    };

    return ExecuteSP("spIsPasswordResetLinkValid", paramList);
}

private bool ChangeUserPassword()
{
    List<SqlParameter> paramList = new List<SqlParameter>()
    {
        new SqlParameter()
        {
            ParameterName = "@GUID",
            Value = Request.QueryString["uid"]
        },
        new SqlParameter()
        {
            ParameterName = "@Password",
            Value = FormsAuthentication.HashPasswordForStoringInConfigFile(txtNewPassword.Text, "SHA1")
        }
    };

    return ExecuteSP("spChangePassword", paramList);
}

private bool ChangeUserPasswordUsingCurrentPassword()
{
    List<SqlParameter> paramList = new List<SqlParameter>()
    {
        new SqlParameter()
        {
            ParameterName = "@UserName",
            Value = User.Identity.Name
        },
        new SqlParameter()
        {
            ParameterName = "@CurrentPassword",
            Value = FormsAuthentication.HashPasswordForStoringInConfigFile(txtCurrentPassword.Text, "SHA1")
        },
        new SqlParameter()
        {
            ParameterName = "@NewPassword",
            Value = FormsAuthentication.HashPasswordForStoringInConfigFile(txtNewPassword.Text, "SHA1")
        }
    };

    return ExecuteSP("spChangePasswordUsingCurrentPassword", paramList);
}

1 comment:

  1. spIsPasswordResetLinkValid pls provide this store procedure

    ReplyDelete

It would be great if you can help share these free resources