PageRenderTime 47ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Resources/Companion/AdminRole/Models/AccountModels.cs

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