From 3ddb38839ac07de4edf071faeb753b62acb0bed1 Mon Sep 17 00:00:00 2001 From: 杨宇千 Date: Tue, 22 Oct 2019 20:49:52 +0800 Subject: ... --- Timeline/Models/Validation/UsernameValidator.cs | 37 +++--- Timeline/Models/Validation/Validator.cs | 58 ++++----- .../Validation/UsernameValidator.Designer.cs | 90 ++++++++++++++ .../Models/Validation/UsernameValidator.en.resx | 129 +++++++++++++++++++++ .../Models/Validation/UsernameValidator.resx | 129 +++++++++++++++++++++ .../Models/Validation/UsernameValidator.zh.resx | 129 +++++++++++++++++++++ .../Models/Validation/Validator.Designer.cs | 27 +++++ .../Resources/Models/Validation/Validator.resx | 9 ++ Timeline/Services/UserService.cs | 18 +-- Timeline/Timeline.csproj | 12 ++ 10 files changed, 580 insertions(+), 58 deletions(-) create mode 100644 Timeline/Resources/Models/Validation/UsernameValidator.Designer.cs create mode 100644 Timeline/Resources/Models/Validation/UsernameValidator.en.resx create mode 100644 Timeline/Resources/Models/Validation/UsernameValidator.resx create mode 100644 Timeline/Resources/Models/Validation/UsernameValidator.zh.resx (limited to 'Timeline') diff --git a/Timeline/Models/Validation/UsernameValidator.cs b/Timeline/Models/Validation/UsernameValidator.cs index ecc3b5b3..65d4da71 100644 --- a/Timeline/Models/Validation/UsernameValidator.cs +++ b/Timeline/Models/Validation/UsernameValidator.cs @@ -1,46 +1,39 @@ -using Microsoft.Extensions.Localization; -using System.Linq; -using System.Text.RegularExpressions; +using System.Linq; namespace Timeline.Models.Validation { public class UsernameValidator : Validator { public const int MaxLength = 26; - public const string RegexPattern = @"^[a-zA-Z0-9_][a-zA-Z0-9-_]*$"; - private readonly Regex _regex = new Regex(RegexPattern); - - protected override bool DoValidate(string value, IStringLocalizerFactory localizerFactory, out string message) + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "Already checked in base class.")] + protected override (bool, ValidationMessageGenerator) DoValidate(string value) { if (value.Length == 0) { - message = "An empty string is not permitted."; - return false; + return (false, factory => + factory?.Create(typeof(UsernameValidator))?["ValidationMessageEmptyString"] + ?? Resources.Models.Validation.UsernameValidator.InvariantValidationMessageEmptyString); } if (value.Length > 26) { - message = $"Too long, more than 26 characters is not premitted, found {value.Length}."; - return false; + return (false, factory => + factory?.Create(typeof(UsernameValidator))?["ValidationMessageTooLong"] + ?? Resources.Models.Validation.UsernameValidator.InvariantValidationMessageTooLong); } foreach ((char c, int i) in value.Select((c, i) => (c, i))) - if (char.IsWhiteSpace(c)) + { + if (!(char.IsLetterOrDigit(c) || c == '-' || c == '_')) { - message = $"A whitespace is found at {i} . Whitespace is not permited."; - return false; + return (false, factory => + factory?.Create(typeof(UsernameValidator))?["ValidationMessageInvalidChar"] + ?? Resources.Models.Validation.UsernameValidator.InvariantValidationMessageInvalidChar); } - - var match = _regex.Match(value); - if (!match.Success) - { - message = "Regex match failed."; - return false; } - message = ValidationConstants.SuccessMessage; - return true; + return (true, SuccessMessageGenerator); } } } diff --git a/Timeline/Models/Validation/Validator.cs b/Timeline/Models/Validation/Validator.cs index a3800b71..606ba7b4 100644 --- a/Timeline/Models/Validation/Validator.cs +++ b/Timeline/Models/Validation/Validator.cs @@ -6,9 +6,16 @@ using Timeline.Helpers; namespace Timeline.Models.Validation { + /// + /// Generate a message from a localizer factory. + /// If localizerFactory is null, it should return a neutral-cultural message. + /// + /// The localizer factory. Could be null. + /// The message. + public delegate string ValidationMessageGenerator(IStringLocalizerFactory? localizerFactory); + /// /// A validator to validate value. - /// See . /// public interface IValidator { @@ -16,14 +23,8 @@ namespace Timeline.Models.Validation /// Validate given value. /// /// The value to validate. - /// The validation message. - /// True if validation passed. Otherwise false. - bool Validate(object? value, IStringLocalizerFactory localizerFactory, out string message); - } - - public static class ValidationConstants - { - public const string SuccessMessage = "Validation succeeded."; + /// Validation success or not and the message generator. + (bool, ValidationMessageGenerator) Validate(object? value); } /// @@ -39,36 +40,32 @@ namespace Timeline.Models.Validation /// public abstract class Validator : IValidator { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "")] - public bool Validate(object? value, IStringLocalizerFactory localizerFactory, out string message) + public (bool, ValidationMessageGenerator) Validate(object? value) { if (value == null) { - var localizer = localizerFactory.Create("Models.Validation.Validator"); - message = localizer["ValidatorMessageNull"]; - return false; + return (false, factory => + factory?.Create("Models.Validation.Validator")?["ValidatorMessageNull"] + ?? Resources.Models.Validation.Validator.InvariantValidatorMessageNull + ); } if (value is T v) { - return DoValidate(v, localizerFactory, out message); + return DoValidate(v); } else { - var localizer = localizerFactory.Create("Models.Validation.Validator"); - message = localizer["ValidatorMessageBadType", typeof(T).FullName]; - return false; + return (false, factory => + factory?.Create("Models.Validation.Validator")?["ValidatorMessageBadType", typeof(T).FullName] + ?? Resources.Models.Validation.Validator.InvariantValidatorMessageBadType); } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods")] - protected static string GetSuccessMessage(IStringLocalizerFactory factory) - { - var localizer = factory.Create("Models.Validation.Validator"); - return localizer["ValidatorMessageSuccess"]; - } + protected static ValidationMessageGenerator SuccessMessageGenerator { get; } = factory => + factory?.Create("Models.Validation.Validator")?["ValidatorMessageSuccess"] ?? Resources.Models.Validation.Validator.InvariantValidatorMessageSuccess; - protected abstract bool DoValidate(T value, IStringLocalizerFactory localizerFactory, out string message); + protected abstract (bool, ValidationMessageGenerator) DoValidate(T value); } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, @@ -113,11 +110,16 @@ namespace Timeline.Models.Validation protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - var localizerFactory = validationContext.GetRequiredService(); - if (_validator.Validate(value, localizerFactory, out var message)) + var (result, messageGenerator) = _validator.Validate(value); + if (result) + { return ValidationResult.Success; + } else - return new ValidationResult(message); + { + var localizerFactory = validationContext.GetRequiredService(); + return new ValidationResult(messageGenerator(localizerFactory)); + } } } } diff --git a/Timeline/Resources/Models/Validation/UsernameValidator.Designer.cs b/Timeline/Resources/Models/Validation/UsernameValidator.Designer.cs new file mode 100644 index 00000000..a4c35326 --- /dev/null +++ b/Timeline/Resources/Models/Validation/UsernameValidator.Designer.cs @@ -0,0 +1,90 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Timeline.Resources.Models.Validation { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class UsernameValidator { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal UsernameValidator() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Resources.Models.Validation.UsernameValidator", typeof(UsernameValidator).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to An empty string is not allowed.. + /// + internal static string InvariantValidationMessageEmptyString { + get { + return ResourceManager.GetString("InvariantValidationMessageEmptyString", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid character, only alphabet, digit, underscore and hyphen are allowed. . + /// + internal static string InvariantValidationMessageInvalidChar { + get { + return ResourceManager.GetString("InvariantValidationMessageInvalidChar", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Too long, more than 26 characters is not premitted.. + /// + internal static string InvariantValidationMessageTooLong { + get { + return ResourceManager.GetString("InvariantValidationMessageTooLong", resourceCulture); + } + } + } +} diff --git a/Timeline/Resources/Models/Validation/UsernameValidator.en.resx b/Timeline/Resources/Models/Validation/UsernameValidator.en.resx new file mode 100644 index 00000000..9171b856 --- /dev/null +++ b/Timeline/Resources/Models/Validation/UsernameValidator.en.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + An empty string is not allowed. + + + Invalid character, only alphabet, digit, underscore and hyphen are allowed. + + + Too long, more than 26 characters is not premitted. + + \ No newline at end of file diff --git a/Timeline/Resources/Models/Validation/UsernameValidator.resx b/Timeline/Resources/Models/Validation/UsernameValidator.resx new file mode 100644 index 00000000..80cae2d5 --- /dev/null +++ b/Timeline/Resources/Models/Validation/UsernameValidator.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + An empty string is not allowed. + + + Invalid character, only alphabet, digit, underscore and hyphen are allowed. + + + Too long, more than 26 characters is not premitted. + + \ No newline at end of file diff --git a/Timeline/Resources/Models/Validation/UsernameValidator.zh.resx b/Timeline/Resources/Models/Validation/UsernameValidator.zh.resx new file mode 100644 index 00000000..1c8a936c --- /dev/null +++ b/Timeline/Resources/Models/Validation/UsernameValidator.zh.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 空字符串是不允许的。 + + + 无效的字符,只能使用字母、数字、下划线和连字符。 + + + 太长了,不能大于26个字符。 + + \ No newline at end of file diff --git a/Timeline/Resources/Models/Validation/Validator.Designer.cs b/Timeline/Resources/Models/Validation/Validator.Designer.cs index f2532af3..4cbc13de 100644 --- a/Timeline/Resources/Models/Validation/Validator.Designer.cs +++ b/Timeline/Resources/Models/Validation/Validator.Designer.cs @@ -60,6 +60,33 @@ namespace Timeline.Resources.Models.Validation { } } + /// + /// Looks up a localized string similar to Value is not of type {0}.. + /// + internal static string InvariantValidatorMessageBadType { + get { + return ResourceManager.GetString("InvariantValidatorMessageBadType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value can't be null.. + /// + internal static string InvariantValidatorMessageNull { + get { + return ResourceManager.GetString("InvariantValidatorMessageNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Validation succeeded.. + /// + internal static string InvariantValidatorMessageSuccess { + get { + return ResourceManager.GetString("InvariantValidatorMessageSuccess", resourceCulture); + } + } + /// /// Looks up a localized string similar to Failed to create a validator instance from default constructor. See inner exception.. /// diff --git a/Timeline/Resources/Models/Validation/Validator.resx b/Timeline/Resources/Models/Validation/Validator.resx index 8843dc42..0e8f53a6 100644 --- a/Timeline/Resources/Models/Validation/Validator.resx +++ b/Timeline/Resources/Models/Validation/Validator.resx @@ -117,6 +117,15 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + Value is not of type {0}. + + + Value can't be null. + + + Validation succeeded. + Failed to create a validator instance from default constructor. See inner exception. diff --git a/Timeline/Services/UserService.cs b/Timeline/Services/UserService.cs index aad4a806..45ef8a5c 100644 --- a/Timeline/Services/UserService.cs +++ b/Timeline/Services/UserService.cs @@ -140,16 +140,13 @@ namespace Timeline.Services private readonly UsernameValidator _usernameValidator; - private readonly IStringLocalizerFactory _localizerFactory; - - public UserService(ILogger logger, IMemoryCache memoryCache, IStringLocalizerFactory localizerFactory, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService) + public UserService(ILogger logger, IMemoryCache memoryCache, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService) { _logger = logger; _memoryCache = memoryCache; _databaseContext = databaseContext; _jwtService = jwtService; _passwordService = passwordService; - _localizerFactory = localizerFactory; _usernameValidator = new UsernameValidator(); } @@ -244,9 +241,10 @@ namespace Timeline.Services if (password == null) throw new ArgumentNullException(nameof(password)); - if (!_usernameValidator.Validate(username, _localizerFactory, out var message)) + var (result, messageGenerator) = _usernameValidator.Validate(username); + if (!result) { - throw new UsernameBadFormatException(username, message); + throw new UsernameBadFormatException(username, messageGenerator(null)); } var user = await _databaseContext.Users.Where(u => u.Name == username).SingleOrDefaultAsync(); @@ -353,8 +351,12 @@ namespace Timeline.Services if (string.IsNullOrEmpty(newUsername)) throw new ArgumentException("New username is null or empty", nameof(newUsername)); - if (!_usernameValidator.Validate(newUsername, _localizerFactory, out var message)) - throw new UsernameBadFormatException(newUsername, $"New username is of bad format. {message}"); + + var (result, messageGenerator) = _usernameValidator.Validate(newUsername); + if (!result) + { + throw new UsernameBadFormatException(newUsername, $"New username is of bad format. {messageGenerator(null)}"); + } var user = await _databaseContext.Users.Where(u => u.Name == oldUsername).SingleOrDefaultAsync(); if (user == null) diff --git a/Timeline/Timeline.csproj b/Timeline/Timeline.csproj index d1f9b2ed..e29c4e4b 100644 --- a/Timeline/Timeline.csproj +++ b/Timeline/Timeline.csproj @@ -49,6 +49,11 @@ True UserController.resx + + True + True + UsernameValidator.resx + True True @@ -82,6 +87,13 @@ ResXFileCodeGenerator UserController.Designer.cs + + ResXFileCodeGenerator + UsernameValidator.Designer.cs + + + + ResXFileCodeGenerator Validator.Designer.cs -- cgit v1.2.3