File: MembershipPasswordAttribute.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (311 lines) | stat: -rw-r--r-- 16,894 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
namespace System.Web.Security {
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Linq;
    using System.Text.RegularExpressions;
    using  System.Web.Util;

    /// <summary>
    /// Validates whether a password field meets the current Membership Provider's password requirements.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    [SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "This attribute is designed to be a base class for other attributes which further want to customize password validation.")]
    public class MembershipPasswordAttribute : ValidationAttribute {

        #region Fields
        private int? _minRequiredPasswordLength;
        private int? _minRequiredNonAlphanumericCharacters;
        private string _passwordStrengthRegularExpression;

        private Type _resourceType;
        private LocalizableString _minPasswordLengthError = new LocalizableString("MinPasswordLengthError");
        private LocalizableString _minNonAlphanumericCharactersError = new LocalizableString("MinNonAlphanumericCharactersError");
        private LocalizableString _passwordStrengthError = new LocalizableString("PasswordStrengthError");
        #endregion

        #region Properties
        /// <summary>
        /// Minimum required password length this attribute uses for validation.
        /// If not explicitly set, defaults to <see cref="Membership.Provider.MinRequiredPasswordLength"/>.
        /// </summary>
        public int MinRequiredPasswordLength {
            get {
                return _minRequiredPasswordLength != null ? (int)_minRequiredPasswordLength : Membership.Provider.MinRequiredPasswordLength;
            }
            set {
                _minRequiredPasswordLength = value;
            }
        }

        /// <summary>
        /// Minimum required non-alpha numeric characters this attribute uses for validation.
        /// If not explicitly set, defaults to <see cref="Membership.Provider.MinRequiredNonAlphanumericCharacters"/>.
        /// </summary>
        public int MinRequiredNonAlphanumericCharacters {
            get {
                return _minRequiredNonAlphanumericCharacters != null ? (int)_minRequiredNonAlphanumericCharacters : Membership.Provider.MinRequiredNonAlphanumericCharacters;
            }
            set {
                _minRequiredNonAlphanumericCharacters = value;
            }
        }

        /// <summary>
        /// Regular expression string representing the password strength this attribute uses for validation.
        /// If not explicitly set, defaults to <see cref="Membership.Provider.PasswordStrengthRegularExpression"/>.
        /// </summary>
        public string PasswordStrengthRegularExpression {
            get {
                return _passwordStrengthRegularExpression ?? Membership.Provider.PasswordStrengthRegularExpression;
            }
            set {
                _passwordStrengthRegularExpression = value;
            }
        }

        /// <summary>
        /// Gets or sets the <see cref="System.Type"/> that contains the resources for <see cref="MinPasswordLengthError"/>,
        /// <see cref="MinNonAlphanumericCharactersError"/>, and <see cref="PasswordStrengthError"/>.
        /// </summary>
        public Type ResourceType {
            get {
                return this._resourceType;
            }
            set {
                if (this._resourceType != value) {
                    this._resourceType = value;

                    this._minPasswordLengthError.ResourceType = value;
                    this._minNonAlphanumericCharactersError.ResourceType = value;
                    this._passwordStrengthError.ResourceType = value;
                }
            }
        }

        /// <summary>
        /// Gets or sets the MinPasswordLengthError attribute property, which may be a resource key string.
        /// </summary>
        /// <remarks>
        /// The property contains either the literal, non-localized string or the resource key
        /// to be used in conjunction with <see cref="ResourceType"/> to configure the localized
        /// error message displayed when the provided password is shorter than <see cref="Membership.Provider.MinRequiredPasswordLength"/>.
        /// </remarks>
        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The property and method are a matched pair")]
        public string MinPasswordLengthError {
            get {
                return this._minPasswordLengthError.Value;
            }
            set {
                if (this._minPasswordLengthError.Value != value) {
                    this._minPasswordLengthError.Value = value;
                }
            }
        }

        /// <summary>
        /// Gets or sets the MinNonAlphanumericCharactersError attribute property, which may be a resource key string.
        /// </summary>
        /// <remarks>
        /// The property contains either the literal, non-localized string or the resource key
        /// to be used in conjunction with <see cref="ResourceType"/> to configure the localized
        /// error message displayed when the provided password contains less number of non-alphanumeric characters than 
        /// <see cref="Membership.Provider.MinRequiredNonAlphanumericCharacters"/>
        /// </remarks>
        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The property and method are a matched pair")]
        public string MinNonAlphanumericCharactersError {
            get {
                return this._minNonAlphanumericCharactersError.Value;
            }
            set {
                if (this._minNonAlphanumericCharactersError.Value != value) {
                    this._minNonAlphanumericCharactersError.Value = value;
                }
            }
        }

        /// <summary>
        /// Gets or sets the PasswordStrengthError attribute property, which may be a resource key string.
        /// </summary>
        /// <remarks>
        /// The property contains either the literal, non-localized string or the resource key
        /// to be used in conjunction with <see cref="ResourceType"/> to configure the localized
        /// error message displayed when the provided password is shorter than <see cref="Membership.Provider.MinRequiredPasswordLength"/>.
        /// </remarks>
        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "The property and method are a matched pair")]
        public string PasswordStrengthError {
            get {
                return this._passwordStrengthError.Value;
            }
            set {
                if (this._passwordStrengthError.Value != value) {
                    this._passwordStrengthError.Value = value;
                }
            }
        }

        // The timeout for the regex we use to check password strength
        public int? PasswordStrengthRegexTimeout { get; set; }
        #endregion

        #region Overriden Methods
        /// <summary>
        /// Overrider of <see cref="ValidationAttribute.IsValid(object,validationContext)"/>.
        /// </summary>
        /// <remarks>
        /// Checks if the given value meets the password requirements such as minimum length, minimum number of non-alpha numeric characters
        /// and password strength regular expression set in current <see cref="Membership.Provider"/>
        /// </remarks>
        /// <param name="value">The value to validate.</param>
        /// <param name="validationContext">A <see cref="ValidationContext"/> instance that provides
        /// context about the validation operation, such as the object and member being validated.</param>
        /// <returns>
        /// When validation is valid, <see cref="ValidationResult.Success"/>.
        /// <para>
        /// When validation is invalid, an instance of <see cref="ValidationResult"/>.
        /// </para>
        /// </returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
            string valueAsString = value as string;

            string name = (validationContext != null) ? validationContext.DisplayName : String.Empty;
            string[] memberNames = (validationContext != null) ? new[] { validationContext.MemberName } : null;
            string errorMessage;

            if (String.IsNullOrEmpty(valueAsString)) {
                return ValidationResult.Success;
            }

            if (valueAsString.Length < MinRequiredPasswordLength) {
                errorMessage = GetMinPasswordLengthError();
                return new ValidationResult(FormatErrorMessage(errorMessage, name, MinRequiredPasswordLength), memberNames);
            }

            int nonAlphanumericCharacters = valueAsString.Count(c => !Char.IsLetterOrDigit(c));
            if (nonAlphanumericCharacters < MinRequiredNonAlphanumericCharacters) {
                errorMessage = GetMinNonAlphanumericCharactersError();
                return new ValidationResult(FormatErrorMessage(errorMessage, name, MinRequiredNonAlphanumericCharacters), memberNames);
            }

            string passwordStrengthRegularExpression = PasswordStrengthRegularExpression;
            if (passwordStrengthRegularExpression != null) {

                Regex passwordStrengthRegex;
                try {
                    // Adding timeout for Regex in case of malicious string causing DoS
                    passwordStrengthRegex = RegexUtil.CreateRegex(passwordStrengthRegularExpression, RegexOptions.None, PasswordStrengthRegexTimeout);
                }
                catch (ArgumentException ex) {
                    throw new InvalidOperationException(SR.GetString(SR.MembershipPasswordAttribute_InvalidRegularExpression), ex);
                }

                if (!passwordStrengthRegex.IsMatch(valueAsString)) {
                    errorMessage = GetPasswordStrengthError();
                    return new ValidationResult(FormatErrorMessage(errorMessage, name, additionalArgument: String.Empty), memberNames);
                }
            }

            return ValidationResult.Success;
        }

        public override string FormatErrorMessage(string name) {
            return FormatErrorMessage(errorMessageString: ErrorMessageString, name: name, additionalArgument: String.Empty);
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Gets the error message string shown when the provided password is shorter than <see cref="Membership.Provider.MinRequiredPasswordLength"/>.
        /// <para>
        /// This can be either a literal, non-localized string provided to <see cref="MinPasswordLengthError"/> or the
        /// localized string found when <see cref="ResourceType"/> has been specified and <see cref="MinPasswordLengthError"/>
        /// represents a resource key within that resource type.
        /// </para>
        /// </summary>
        /// <returns>
        /// When <see cref="ResourceType"/> has not been specified, the value of
        /// <see cref="MinPasswordLengthError"/> will be returned.
        /// <para>
        /// When <see cref="ResourceType"/> has been specified and <see cref="MinPasswordLengthError"/>
        /// represents a resource key within that resource type, then the localized value will be returned.
        /// </para>
        /// <para>
        /// When <see cref="MinPasswordLengthError"/> has not been specified, a default error message will be returned.
        /// </para>
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// After setting both the <see cref="ResourceType"/> property and the <see cref="MinPasswordLengthError"/> property,
        /// but a public static property with a name matching the <see cref="MinPasswordLengthError"/> value couldn't be found
        /// on the <see cref="ResourceType"/>.
        /// </exception>
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method does work using a property of the same name")]
        private string GetMinPasswordLengthError() {
            return this._minPasswordLengthError.GetLocalizableValue() ?? SR.GetString(SR.MembershipPasswordAttribute_InvalidPasswordLength);
        }

        /// <summary>
        /// Gets the error message string shown when the provided password contains less number of non-alphanumeric characters than 
        /// <see cref="Membership.Provider.MinRequiredNonAlphanumericCharacters"/>
        /// <para>
        /// This can be either a literal, non-localized string provided to <see cref="MinNonAlphanumericCharactersError"/> or the
        /// localized string found when <see cref="ResourceType"/> has been specified and <see cref="MinNonAlphanumericCharactersError"/>
        /// represents a resource key within that resource type.
        /// </para>
        /// </summary>
        /// <returns>
        /// When <see cref="ResourceType"/> has not been specified, the value of
        /// <see cref="MinNonAlphanumericCharactersError"/> will be returned.
        /// <para>
        /// When <see cref="ResourceType"/> has been specified and <see cref="MinNonAlphanumericCharactersError"/>
        /// represents a resource key within that resource type, then the localized value will be returned.
        /// </para>
        /// <para>
        /// When <see cref="MinNonAlphanumericCharactersError"/> has not been specified, a default error message will be returned.
        /// </para>
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// After setting both the <see cref="ResourceType"/> property and the <see cref="MinNonAlphanumericCharactersError"/> property,
        /// but a public static property with a name matching the <see cref="MinNonAlphanumericCharactersError"/> value couldn't be found
        /// on the <see cref="ResourceType"/>.
        /// </exception>
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method does work using a property of the same name")]
        private string GetMinNonAlphanumericCharactersError() {
            return this._minNonAlphanumericCharactersError.GetLocalizableValue() ?? SR.GetString(SR.MembershipPasswordAttribute_InvalidPasswordNonAlphanumericCharacters);
        }

        /// <summary>
        /// Gets the error message string shown when the provided password is shorter than <see cref="Membership.Provider.MinRequiredPasswordLength"/>.
        /// <para>
        /// This can be either a literal, non-localized string provided to <see cref="PasswordStrengthError"/> or the
        /// localized string found when <see cref="ResourceType"/> has been specified and <see cref="PasswordStrengthError"/>
        /// represents a resource key within that resource type.
        /// </para>
        /// </summary>
        /// <returns>
        /// When <see cref="ResourceType"/> has not been specified, the value of
        /// <see cref="PasswordStrengthError"/> will be returned.
        /// <para>
        /// When <see cref="ResourceType"/> has been specified and <see cref="PasswordStrengthError"/>
        /// represents a resource key within that resource type, then the localized value will be returned.
        /// </para>
        /// <para>
        /// When <see cref="PasswordStrengthError"/> has not been specified, a default error message will be returned.
        /// </para>
        /// </returns>
        /// <exception cref="System.InvalidOperationException">
        /// After setting both the <see cref="ResourceType"/> property and the <see cref="PasswordStrengthError"/> property,
        /// but a public static property with a name matching the <see cref="PasswordStrengthError"/> value couldn't be found
        /// on the <see cref="ResourceType"/>.
        /// </exception>
        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method does work using a property of the same name")]
        private string GetPasswordStrengthError() {
            return this._passwordStrengthError.GetLocalizableValue() ?? SR.GetString(SR.MembershipPasswordAttribute_InvalidPasswordStrength);
        }

        private string FormatErrorMessage(string errorMessageString, string name, object additionalArgument) {
            return String.Format(CultureInfo.CurrentCulture, errorMessageString, name, additionalArgument);
        }
        #endregion
    }
}