diff options
author | 杨宇千 <crupest@outlook.com> | 2019-10-22 20:49:52 +0800 |
---|---|---|
committer | 杨宇千 <crupest@outlook.com> | 2019-10-22 20:49:52 +0800 |
commit | 9c9762b4ecbd816be98ee0dd606fe15cc253b415 (patch) | |
tree | cd8dea96c88e9784ceeb7342f486160ceadc6a58 | |
parent | c442b7ad597f430b186dd8019de70332b574c4ba (diff) | |
download | timeline-9c9762b4ecbd816be98ee0dd606fe15cc253b415.tar.gz timeline-9c9762b4ecbd816be98ee0dd606fe15cc253b415.tar.bz2 timeline-9c9762b4ecbd816be98ee0dd606fe15cc253b415.zip |
...
-rw-r--r-- | Timeline.Tests/UsernameValidatorUnitTest.cs | 65 | ||||
-rw-r--r-- | Timeline/Models/Validation/UsernameValidator.cs | 37 | ||||
-rw-r--r-- | Timeline/Models/Validation/Validator.cs | 58 | ||||
-rw-r--r-- | Timeline/Resources/Models/Validation/UsernameValidator.Designer.cs | 90 | ||||
-rw-r--r-- | Timeline/Resources/Models/Validation/UsernameValidator.en.resx | 129 | ||||
-rw-r--r-- | Timeline/Resources/Models/Validation/UsernameValidator.resx | 129 | ||||
-rw-r--r-- | Timeline/Resources/Models/Validation/UsernameValidator.zh.resx | 129 | ||||
-rw-r--r-- | Timeline/Resources/Models/Validation/Validator.Designer.cs | 27 | ||||
-rw-r--r-- | Timeline/Resources/Models/Validation/Validator.resx | 9 | ||||
-rw-r--r-- | Timeline/Services/UserService.cs | 18 | ||||
-rw-r--r-- | Timeline/Timeline.csproj | 12 |
11 files changed, 604 insertions, 99 deletions
diff --git a/Timeline.Tests/UsernameValidatorUnitTest.cs b/Timeline.Tests/UsernameValidatorUnitTest.cs index 9a80a3a2..283e18e2 100644 --- a/Timeline.Tests/UsernameValidatorUnitTest.cs +++ b/Timeline.Tests/UsernameValidatorUnitTest.cs @@ -1,6 +1,5 @@ using FluentAssertions;
using Timeline.Models.Validation;
-using Timeline.Tests.Mock.Services;
using Xunit;
namespace Timeline.Tests
@@ -16,15 +15,9 @@ namespace Timeline.Tests private string FailAndMessage(string username)
{
- var result = _validator.Validate(username, TestStringLocalizerFactory.Create(), out var message);
+ var (result, messageGenerator) = _validator.Validate(username);
result.Should().BeFalse();
- return message;
- }
-
- private void Succeed(string username)
- {
- _validator.Validate(username, TestStringLocalizerFactory.Create(), out var message).Should().BeTrue();
- message.Should().Be(ValidationConstants.SuccessMessage);
+ return messageGenerator(null);
}
[Fact]
@@ -36,8 +29,9 @@ namespace Timeline.Tests [Fact]
public void NotString()
{
- var result = _validator.Validate(123, TestStringLocalizerFactory.Create(), out var message);
+ var (result, messageGenerator) = _validator.Validate(123);
result.Should().BeFalse();
+ var message = messageGenerator(null);
message.Should().ContainEquivalentOf("type");
}
@@ -47,31 +41,14 @@ namespace Timeline.Tests FailAndMessage("").Should().ContainEquivalentOf("empty");
}
- [Fact]
- public void WhiteSpace()
+ [Theory]
+ [InlineData("!")]
+ [InlineData("!abc")]
+ [InlineData("ab c")]
+ public void BadCharactor(string value)
{
- FailAndMessage(" ").Should().ContainEquivalentOf("whitespace");
- FailAndMessage("\t").Should().ContainEquivalentOf("whitespace");
- FailAndMessage("\n").Should().ContainEquivalentOf("whitespace");
-
- FailAndMessage("a b").Should().ContainEquivalentOf("whitespace");
- FailAndMessage("a\tb").Should().ContainEquivalentOf("whitespace");
- FailAndMessage("a\nb").Should().ContainEquivalentOf("whitespace");
- }
-
- [Fact]
- public void BadCharactor()
- {
- FailAndMessage("!").Should().ContainEquivalentOf("regex");
- FailAndMessage("!abc").Should().ContainEquivalentOf("regex");
- FailAndMessage("ab!c").Should().ContainEquivalentOf("regex");
- }
-
- [Fact]
- public void BadBegin()
- {
- FailAndMessage("-").Should().ContainEquivalentOf("regex");
- FailAndMessage("-abc").Should().ContainEquivalentOf("regex");
+ FailAndMessage(value).Should().ContainEquivalentOf("invalid")
+ .And.ContainEquivalentOf("character");
}
[Fact]
@@ -80,14 +57,20 @@ namespace Timeline.Tests FailAndMessage(new string('a', 40)).Should().ContainEquivalentOf("long");
}
- [Fact]
- public void Success()
+ [Theory]
+ [InlineData("abc")]
+ [InlineData("-abc")]
+ [InlineData("_abc")]
+ [InlineData("abc-")]
+ [InlineData("abc_")]
+ [InlineData("a-bc")]
+ [InlineData("a-b-c")]
+ [InlineData("a-b_c")]
+ public void Success(string value)
{
- Succeed("abc");
- Succeed("_abc");
- Succeed("a-bc");
- Succeed("a-b-c");
- Succeed("a-b_c");
+
+ var (result, _) = _validator.Validate(value);
+ result.Should().BeTrue();
}
}
}
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<string>
{
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 @@ -7,8 +7,15 @@ using Timeline.Helpers; namespace Timeline.Models.Validation
{
/// <summary>
+ /// Generate a message from a localizer factory.
+ /// If localizerFactory is null, it should return a neutral-cultural message.
+ /// </summary>
+ /// <param name="localizerFactory">The localizer factory. Could be null.</param>
+ /// <returns>The message.</returns>
+ public delegate string ValidationMessageGenerator(IStringLocalizerFactory? localizerFactory);
+
+ /// <summary>
/// A validator to validate value.
- /// See <see cref="Validate(object?, out string)"/>.
/// </summary>
public interface IValidator
{
@@ -16,14 +23,8 @@ namespace Timeline.Models.Validation /// Validate given value.
/// </summary>
/// <param name="value">The value to validate.</param>
- /// <param name="message">The validation message.</param>
- /// <returns>True if validation passed. Otherwise false.</returns>
- bool Validate(object? value, IStringLocalizerFactory localizerFactory, out string message);
- }
-
- public static class ValidationConstants
- {
- public const string SuccessMessage = "Validation succeeded.";
+ /// <returns>Validation success or not and the message generator.</returns>
+ (bool, ValidationMessageGenerator) Validate(object? value);
}
/// <summary>
@@ -39,36 +40,32 @@ namespace Timeline.Models.Validation /// </remarks>
public abstract class Validator<T> : IValidator
{
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "<Pending>")]
- 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<IStringLocalizerFactory>();
- 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<IStringLocalizerFactory>();
+ 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 @@ +//------------------------------------------------------------------------------
+// <auto-generated>
+// 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.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Timeline.Resources.Models.Validation {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // 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() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [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;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to An empty string is not allowed..
+ /// </summary>
+ internal static string InvariantValidationMessageEmptyString {
+ get {
+ return ResourceManager.GetString("InvariantValidationMessageEmptyString", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Invalid character, only alphabet, digit, underscore and hyphen are allowed. .
+ /// </summary>
+ internal static string InvariantValidationMessageInvalidChar {
+ get {
+ return ResourceManager.GetString("InvariantValidationMessageInvalidChar", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Too long, more than 26 characters is not premitted..
+ /// </summary>
+ 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 @@ +<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="ValidationMessageEmptyString" xml:space="preserve">
+ <value>An empty string is not allowed.</value>
+ </data>
+ <data name="ValidationMessageInvalidChar" xml:space="preserve">
+ <value>Invalid character, only alphabet, digit, underscore and hyphen are allowed.</value>
+ </data>
+ <data name="ValidationMessageTooLong" xml:space="preserve">
+ <value>Too long, more than 26 characters is not premitted.</value>
+ </data>
+</root>
\ 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 @@ +<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="InvariantValidationMessageEmptyString" xml:space="preserve">
+ <value>An empty string is not allowed.</value>
+ </data>
+ <data name="InvariantValidationMessageInvalidChar" xml:space="preserve">
+ <value>Invalid character, only alphabet, digit, underscore and hyphen are allowed. </value>
+ </data>
+ <data name="InvariantValidationMessageTooLong" xml:space="preserve">
+ <value>Too long, more than 26 characters is not premitted.</value>
+ </data>
+</root>
\ 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 @@ +<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="ValidationMessageEmptyString" xml:space="preserve">
+ <value>空字符串是不允许的。</value>
+ </data>
+ <data name="ValidationMessageInvalidChar" xml:space="preserve">
+ <value>无效的字符,只能使用字母、数字、下划线和连字符。</value>
+ </data>
+ <data name="ValidationMessageTooLong" xml:space="preserve">
+ <value>太长了,不能大于26个字符。</value>
+ </data>
+</root>
\ 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 @@ -61,6 +61,33 @@ namespace Timeline.Resources.Models.Validation { }
/// <summary>
+ /// Looks up a localized string similar to Value is not of type {0}..
+ /// </summary>
+ internal static string InvariantValidatorMessageBadType {
+ get {
+ return ResourceManager.GetString("InvariantValidatorMessageBadType", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Value can't be null..
+ /// </summary>
+ internal static string InvariantValidatorMessageNull {
+ get {
+ return ResourceManager.GetString("InvariantValidatorMessageNull", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Validation succeeded..
+ /// </summary>
+ internal static string InvariantValidatorMessageSuccess {
+ get {
+ return ResourceManager.GetString("InvariantValidatorMessageSuccess", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to Failed to create a validator instance from default constructor. See inner exception..
/// </summary>
internal static string ValidateWithAttributeCreateFail {
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 @@ <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
+ <data name="InvariantValidatorMessageBadType" xml:space="preserve">
+ <value>Value is not of type {0}.</value>
+ </data>
+ <data name="InvariantValidatorMessageNull" xml:space="preserve">
+ <value>Value can't be null.</value>
+ </data>
+ <data name="InvariantValidatorMessageSuccess" xml:space="preserve">
+ <value>Validation succeeded.</value>
+ </data>
<data name="ValidateWithAttributeCreateFail" xml:space="preserve">
<value>Failed to create a validator instance from default constructor. See inner exception.</value>
</data>
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<UserService> logger, IMemoryCache memoryCache, IStringLocalizerFactory localizerFactory, DatabaseContext databaseContext, IJwtService jwtService, IPasswordService passwordService)
+ public UserService(ILogger<UserService> 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 @@ <AutoGen>True</AutoGen>
<DependentUpon>UserController.resx</DependentUpon>
</Compile>
+ <Compile Update="Resources\Models\Validation\UsernameValidator.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>UsernameValidator.resx</DependentUpon>
+ </Compile>
<Compile Update="Resources\Models\Validation\Validator.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
@@ -82,6 +87,13 @@ <Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>UserController.Designer.cs</LastGenOutput>
</EmbeddedResource>
+ <EmbeddedResource Update="Resources\Models\Validation\UsernameValidator.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>UsernameValidator.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
+ <EmbeddedResource Update="Resources\Models\Validation\Validator.en.resx">
+ <Generator></Generator>
+ </EmbeddedResource>
<EmbeddedResource Update="Resources\Models\Validation\Validator.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Validator.Designer.cs</LastGenOutput>
|