I have been lately developing a small website where I used the ASP.NET 2.0 Membership API to manage my users, create new users, etc ...
I decided however, not to use any of the built-in controls present on the VS 2005 toolbox to create new users, login, etc ... But, I made use of the Membership API instead. So everything was done programmatically using the Membership API to create new user, password recovery, login, etc ...
One thing I noticed that the Membership API has so many methods that come handy in such a solution except a PasswordRecovery method. There is GetPassword() method, however, so many other checking need to be done for example, does the current Membership Provider allow Password Retreival? Do retreiving a password requires a Question/Answer?
I found myself writing a small utility method that does all this checking and can be added to the Membership API methods to help you create a user management system programmtically, where alll functionalities are present!
Have a look at the code with the comments inside.
/// <summary>
/// Recovers a password given the username, secret question/answer.
/// It can be used to recover password programmatically
/// </summary>
/// <param name="userName">UserName to which to recover the password</param>
/// <param name="answer">The Secret Answer</param>
/// <param name="status">Holds any messages of failure</param>
/// <returns>Password to be recovered</returns>
public static string PasswordRecovery(string userName, string answer, out string status)
{
// Initialize the status
status = "";
string pwd = "";
// If the current provider configuration does not
// allow password retrieval, go back
if (!Membership.EnablePasswordRetrieval) {
status = "Current Membership provider configuration doesn't allow password retrieval";
return "";
}
// Check if the current provider requires question/answer
// and check if the corresponding inputs are ok
if (Membership.RequiresQuestionAndAnswer)
{
if (string.IsNullOrEmpty(answer)) {
status = "Secret answer is missing";
}
if (status != "")
return "";
}
// Validate the input
if (string.IsNullOrEmpty(userName)) {
status = "UserName is empty or null";
return "";
}
// Get the user with the above username
MembershipUser user = Membership.GetUser(userName);
if (user == null)
{
status = "UserName doesn't exist in the database";
return "";
}
else {
// If provider is configured to use Secret question/answer
// use the overloaded version of the GetPassword to pass in
// the secret answer
if (Membership.RequiresQuestionAndAnswer)
{
try
{
pwd = user.GetPassword(answer);
}
// If answer is wrong, usually a MembershipPasswordException
// is usually thrown.
catch (MembershipPasswordException ex)
{
status = "Secret answer is wrong";
return "";
}
}
else {
// Retrieve the password without the secret answer
pwd = user.GetPassword();
}
// Password is OK
status = "";
return pwd;
}
}
Hope this code helps!
Regards
Tags: