PageRenderTime 39ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/samples/PrecompiledMvcLibrary/Models/AccountModels.cs

http://razorgenerator.codeplex.com
C# | 248 lines | 194 code | 46 blank | 8 comment | 12 complexity | 8441d79809633f3748a0cedf2e1301f8 MD5 | raw file
Possible License(s): Apache-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Globalization;
  5. using System.Web.Mvc;
  6. using System.Web.Security;
  7. namespace MvcSample.Models
  8. {
  9. #region Models
  10. public class ChangePasswordModel
  11. {
  12. [Required]
  13. [DataType(DataType.Password)]
  14. [Display(Name = "Current password")]
  15. public string OldPassword { get; set; }
  16. [Required]
  17. [ValidatePasswordLength]
  18. [DataType(DataType.Password)]
  19. [Display(Name = "New password")]
  20. public string NewPassword { get; set; }
  21. [DataType(DataType.Password)]
  22. [Display(Name = "Confirm new password")]
  23. [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
  24. public string ConfirmPassword { get; set; }
  25. }
  26. public class LogOnModel
  27. {
  28. [Required]
  29. [Display(Name = "User name")]
  30. public string UserName { get; set; }
  31. [Required]
  32. [DataType(DataType.Password)]
  33. [Display(Name = "Password")]
  34. public string Password { get; set; }
  35. [Display(Name = "Remember me?")]
  36. public bool RememberMe { get; set; }
  37. }
  38. public class RegisterModel
  39. {
  40. [Required]
  41. [Display(Name = "User name")]
  42. public string UserName { get; set; }
  43. [Required]
  44. [DataType(DataType.EmailAddress)]
  45. [Display(Name = "Email address")]
  46. public string Email { get; set; }
  47. [Required]
  48. [ValidatePasswordLength]
  49. [DataType(DataType.Password)]
  50. [Display(Name = "Password")]
  51. public string Password { get; set; }
  52. [DataType(DataType.Password)]
  53. [Display(Name = "Confirm password")]
  54. [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
  55. public string ConfirmPassword { get; set; }
  56. }
  57. #endregion
  58. #region Services
  59. // The FormsAuthentication type is sealed and contains static members, so it is difficult to
  60. // unit test code that calls its members. The interface and helper class below demonstrate
  61. // how to create an abstract wrapper around such a type in order to make the AccountController
  62. // code unit testable.
  63. public interface IMembershipService
  64. {
  65. int MinPasswordLength { get; }
  66. bool ValidateUser(string userName, string password);
  67. MembershipCreateStatus CreateUser(string userName, string password, string email);
  68. bool ChangePassword(string userName, string oldPassword, string newPassword);
  69. }
  70. public class AccountMembershipService : IMembershipService
  71. {
  72. private readonly MembershipProvider _provider;
  73. public AccountMembershipService()
  74. : this(null)
  75. {
  76. }
  77. public AccountMembershipService(MembershipProvider provider)
  78. {
  79. _provider = provider ?? Membership.Provider;
  80. }
  81. public int MinPasswordLength
  82. {
  83. get
  84. {
  85. return _provider.MinRequiredPasswordLength;
  86. }
  87. }
  88. public bool ValidateUser(string userName, string password)
  89. {
  90. if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
  91. if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
  92. return _provider.ValidateUser(userName, password);
  93. }
  94. public MembershipCreateStatus CreateUser(string userName, string password, string email)
  95. {
  96. if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
  97. if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
  98. if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
  99. MembershipCreateStatus status;
  100. _provider.CreateUser(userName, password, email, null, null, true, null, out status);
  101. return status;
  102. }
  103. public bool ChangePassword(string userName, string oldPassword, string newPassword)
  104. {
  105. if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
  106. if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
  107. if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
  108. // The underlying ChangePassword() will throw an exception rather
  109. // than return false in certain failure scenarios.
  110. try
  111. {
  112. MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
  113. return currentUser.ChangePassword(oldPassword, newPassword);
  114. }
  115. catch (ArgumentException)
  116. {
  117. return false;
  118. }
  119. catch (MembershipPasswordException)
  120. {
  121. return false;
  122. }
  123. }
  124. }
  125. public interface IFormsAuthenticationService
  126. {
  127. void SignIn(string userName, bool createPersistentCookie);
  128. void SignOut();
  129. }
  130. public class FormsAuthenticationService : IFormsAuthenticationService
  131. {
  132. public void SignIn(string userName, bool createPersistentCookie)
  133. {
  134. if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
  135. FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
  136. }
  137. public void SignOut()
  138. {
  139. FormsAuthentication.SignOut();
  140. }
  141. }
  142. #endregion
  143. #region Validation
  144. public static class AccountValidation
  145. {
  146. public static string ErrorCodeToString(MembershipCreateStatus createStatus)
  147. {
  148. // See http://go.microsoft.com/fwlink/?LinkID=177550 for
  149. // a full list of status codes.
  150. switch (createStatus)
  151. {
  152. case MembershipCreateStatus.DuplicateUserName:
  153. return "Username already exists. Please enter a different user name.";
  154. case MembershipCreateStatus.DuplicateEmail:
  155. return "A username for that e-mail address already exists. Please enter a different e-mail address.";
  156. case MembershipCreateStatus.InvalidPassword:
  157. return "The password provided is invalid. Please enter a valid password value.";
  158. case MembershipCreateStatus.InvalidEmail:
  159. return "The e-mail address provided is invalid. Please check the value and try again.";
  160. case MembershipCreateStatus.InvalidAnswer:
  161. return "The password retrieval answer provided is invalid. Please check the value and try again.";
  162. case MembershipCreateStatus.InvalidQuestion:
  163. return "The password retrieval question provided is invalid. Please check the value and try again.";
  164. case MembershipCreateStatus.InvalidUserName:
  165. return "The user name provided is invalid. Please check the value and try again.";
  166. case MembershipCreateStatus.ProviderError:
  167. return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
  168. case MembershipCreateStatus.UserRejected:
  169. return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
  170. default:
  171. return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
  172. }
  173. }
  174. }
  175. [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
  176. public sealed class ValidatePasswordLengthAttribute : ValidationAttribute, IClientValidatable
  177. {
  178. private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long.";
  179. private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
  180. public ValidatePasswordLengthAttribute()
  181. : base(_defaultErrorMessage)
  182. {
  183. }
  184. public override string FormatErrorMessage(string name)
  185. {
  186. return String.Format(CultureInfo.CurrentCulture, ErrorMessageString,
  187. name, _minCharacters);
  188. }
  189. public override bool IsValid(object value)
  190. {
  191. string valueAsString = value as string;
  192. return (valueAsString != null && valueAsString.Length >= _minCharacters);
  193. }
  194. public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  195. {
  196. return new[]{
  197. new ModelClientValidationStringLengthRule(FormatErrorMessage(metadata.GetDisplayName()), _minCharacters, int.MaxValue)
  198. };
  199. }
  200. }
  201. #endregion
  202. }