Free cookie consent management tool by TermsFeed Policy Generator

source: branches/WebApplication/MVC2/HLWebOKBAdminPlugin/Models/AccountModels.cs @ 10138

Last change on this file since 10138 was 6317, checked in by jwolfing, 14 years ago

#1433 code formatted

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