The next component is a user management class that allows us
to validate the users, retrieve their verification codes from data store, and
store the generated codes into the data store. For this example, I use a very
simple XML storage and apply LINQ to XML to have access to my data, but a real
world implementation should be much more sophisticated than this.
I assume that an ASP.NET developer is already familiar with
LINQ to XML and finds the code in Listing 3 self-explanatory, so I don’t
explain it in here.
Listing 3: User management
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace AspNetPhoneVerificationSample.Models
{
public static class Users
{
public static bool ValidateUser(string username, string password)
{
// This is a simple single-user system
if (username == "keyvan" && password == "pas$word")
return true;
return false;
}
public static string GetUserPhone(string username)
{
// This is a simple single-user system
if (username == "keyvan")
return "+1YOURPHONE”;
return string.Empty;
}
public static string ReadValidationCode(string username)
{
string path = HttpContext.Current.Server.MapPath("~/App_Data/usercodes.xml");
XDocument doc = XDocument.Load(path);
string code = (from u in doc.Element("Users").Descendants("User")
where u.Attribute("name").Value == username
select u.Attribute("code").Value).SingleOrDefault();
return code;
}
public static void StoreValidationCode(string username, string code)
{
string path = HttpContext.Current
.Server.MapPath("~/App_Data/usercodes.xml");
XDocument doc = XDocument.Load(path);
XElement user = (from u in doc.Element("Users").Descendants("User")
where u.Attribute("name").Value == username
select u).SingleOrDefault();
if (user != null)
{
user.Attribute("code").SetValue(code);
}
else
{
XElement newUser = new XElement("User");
newUser.SetAttributeValue("name", username);
newUser.SetAttributeValue("code", code);
doc.Element("Users").Add(newUser);
}
doc.Save(path);
}
}
}
You also need to alter account models a little bit to have a
new property for LogOnModel for verification code
(Listing 4).
Listing 4: LogOn model
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Verification code")]
public string VerificationCode { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}