aboutsummaryrefslogtreecommitdiff
path: root/Timeline
diff options
context:
space:
mode:
Diffstat (limited to 'Timeline')
-rw-r--r--Timeline/Controllers/TokenController.cs34
-rw-r--r--Timeline/Resources/Controllers/TokenController.en.Designer.cs72
-rw-r--r--Timeline/Resources/Controllers/TokenController.en.resx153
-rw-r--r--Timeline/Startup.cs5
-rw-r--r--Timeline/Timeline.csproj15
5 files changed, 264 insertions, 15 deletions
diff --git a/Timeline/Controllers/TokenController.cs b/Timeline/Controllers/TokenController.cs
index ce5786ca..eba69319 100644
--- a/Timeline/Controllers/TokenController.cs
+++ b/Timeline/Controllers/TokenController.cs
@@ -7,6 +7,8 @@ using System.Threading.Tasks;
using Timeline.Models.Http;
using Timeline.Services;
using Timeline.Helpers;
+using Microsoft.Extensions.Localization;
+using System.Globalization;
namespace Timeline
{
@@ -42,12 +44,14 @@ namespace Timeline.Controllers
private readonly IUserService _userService;
private readonly ILogger<TokenController> _logger;
private readonly IClock _clock;
+ private readonly IStringLocalizer<TokenController> _localizer;
- public TokenController(IUserService userService, ILogger<TokenController> logger, IClock clock)
+ public TokenController(IUserService userService, ILogger<TokenController> logger, IClock clock, IStringLocalizer<TokenController> localizer)
{
_userService = userService;
_logger = logger;
_clock = clock;
+ _localizer = localizer;
}
[HttpPost("create")]
@@ -56,7 +60,7 @@ namespace Timeline.Controllers
{
void LogFailure(string reason, Exception? e = null)
{
- _logger.LogInformation(e, Log.Format("Attemp to login failed.",
+ _logger.LogInformation(e, Log.Format(_localizer["LogCreateFailure"],
("Reason", reason),
("Username", request.Username),
("Password", request.Password),
@@ -72,9 +76,9 @@ namespace Timeline.Controllers
var result = await _userService.CreateToken(request.Username, request.Password, expireTime);
- _logger.LogInformation(Log.Format("Attemp to login succeeded.",
+ _logger.LogInformation(Log.Format(_localizer["LogCreateSuccess"],
("Username", request.Username),
- ("Expire At", expireTime?.ToString() ?? "default")
+ ("Expire At", expireTime?.ToString(CultureInfo.CurrentUICulture.DateTimeFormat) ?? "default")
));
return Ok(new CreateTokenResponse
{
@@ -84,15 +88,15 @@ namespace Timeline.Controllers
}
catch (UserNotExistException e)
{
- LogFailure("User does not exist.", e);
+ LogFailure(_localizer["LogUserNotExist"], e);
return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Create.BadCredential,
- "Bad username or password."));
+ _localizer["ErrorBadCredential"]));
}
catch (BadPasswordException e)
{
- LogFailure("Password is wrong.", e);
+ LogFailure(_localizer["LogBadPassword"], e);
return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Create.BadCredential,
- "Bad username or password."));
+ _localizer["ErrorBadCredential"]));
}
}
@@ -102,17 +106,17 @@ namespace Timeline.Controllers
{
void LogFailure(string reason, Exception? e = null, params (string, object?)[] otherProperties)
{
- var properties = new (string, object)[2 + otherProperties.Length];
+ var properties = new (string, object?)[2 + otherProperties.Length];
properties[0] = ("Reason", reason);
properties[1] = ("Token", request.Token);
otherProperties.CopyTo(properties, 2);
- _logger.LogInformation(e, Log.Format("Token verification failed.", properties));
+ _logger.LogInformation(e, Log.Format(_localizer["LogVerifyFailure"], properties));
}
try
{
var result = await _userService.VerifyToken(request.Token);
- _logger.LogInformation(Log.Format("Token verification succeeded.",
+ _logger.LogInformation(Log.Format(_localizer["LogVerifySuccess"],
("Username", result.Username), ("Token", request.Token)));
return Ok(new VerifyTokenResponse
{
@@ -123,27 +127,27 @@ namespace Timeline.Controllers
{
if (e.ErrorCode == JwtTokenVerifyException.ErrorCodes.Expired)
{
- const string message = "Token is expired.";
+ string message = _localizer["ErrorVerifyExpire"];
var innerException = e.InnerException as SecurityTokenExpiredException;
LogFailure(message, e, ("Expires", innerException?.Expires), ("Current Time", _clock.GetCurrentTime()));
return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Verify.Expired, message));
}
else
{
- const string message = "Token is of bad format.";
+ string message = _localizer["ErrorVerifyBadFormat"];
LogFailure(message, e);
return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Verify.BadFormat, message));
}
}
catch (UserNotExistException e)
{
- const string message = "User does not exist. Administrator might have deleted this user.";
+ string message = _localizer["ErrorVerifyUserNotExist"];
LogFailure(message, e);
return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Verify.UserNotExist, message));
}
catch (BadTokenVersionException e)
{
- const string message = "Token has an old version.";
+ string message = _localizer["ErrorVerifyOldVersion"];
LogFailure(message, e, ("Token Version", e.TokenVersion), ("Required Version", e.RequiredVersion));
return BadRequest(new CommonResponse(ErrorCodes.Http.Token.Verify.OldVersion, message));
}
diff --git a/Timeline/Resources/Controllers/TokenController.en.Designer.cs b/Timeline/Resources/Controllers/TokenController.en.Designer.cs
new file mode 100644
index 00000000..64326860
--- /dev/null
+++ b/Timeline/Resources/Controllers/TokenController.en.Designer.cs
@@ -0,0 +1,72 @@
+//------------------------------------------------------------------------------
+// <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.Controllers {
+ 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()]
+ public class TokenController {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal TokenController() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ public static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Resources.Controllers.TokenController", typeof(TokenController).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)]
+ public static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A user succeeded to create a token..
+ /// </summary>
+ public static string LogCreateSuccess {
+ get {
+ return ResourceManager.GetString("LogCreateSuccess", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/Timeline/Resources/Controllers/TokenController.en.resx b/Timeline/Resources/Controllers/TokenController.en.resx
new file mode 100644
index 00000000..7309ea6a
--- /dev/null
+++ b/Timeline/Resources/Controllers/TokenController.en.resx
@@ -0,0 +1,153 @@
+<?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="ErrorBadCredential" xml:space="preserve">
+ <value>Username or password is invalid.</value>
+ </data>
+ <data name="ErrorVerifyBadFormat" xml:space="preserve">
+ <value>The token is of bad format. It might not be created by the server.</value>
+ </data>
+ <data name="ErrorVerifyExpire" xml:space="preserve">
+ <value>The token is expired.</value>
+ </data>
+ <data name="ErrorVerifyOldVersion" xml:space="preserve">
+ <value>Token has an old version. User might have update some info.</value>
+ </data>
+ <data name="ErrorVerifyUserNotExist" xml:space="preserve">
+ <value>User does not exist. Administrator might have deleted this user.</value>
+ </data>
+ <data name="LogBadPassword" xml:space="preserve">
+ <value>The password is wrong.</value>
+ </data>
+ <data name="LogCreateFailure" xml:space="preserve">
+ <value>A user failed to create a token.</value>
+ </data>
+ <data name="LogCreateSuccess" xml:space="preserve">
+ <value>A user succeeded to create a token.</value>
+ </data>
+ <data name="LogUserNotExist" xml:space="preserve">
+ <value>The user does not exist.</value>
+ </data>
+ <data name="LogVerifyFailure" xml:space="preserve">
+ <value>A token failed to be verified.</value>
+ </data>
+ <data name="LogVerifySuccess" xml:space="preserve">
+ <value>A token succeeded to be verified.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/Timeline/Startup.cs b/Timeline/Startup.cs
index ddbe0840..72c9bf32 100644
--- a/Timeline/Startup.cs
+++ b/Timeline/Startup.cs
@@ -50,6 +50,11 @@ namespace Timeline
);
});
+ services.AddLocalization(options =>
+ {
+ options.ResourcesPath = "Resources";
+ });
+
services.AddScoped<IUserService, UserService>();
services.AddScoped<IJwtService, JwtService>();
services.AddTransient<IPasswordService, PasswordService>();
diff --git a/Timeline/Timeline.csproj b/Timeline/Timeline.csproj
index c634563a..01207ae2 100644
--- a/Timeline/Timeline.csproj
+++ b/Timeline/Timeline.csproj
@@ -26,4 +26,19 @@
<PackageReference Include="SixLabors.ImageSharp" Version="1.0.0-dev002868" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.6.0" />
</ItemGroup>
+
+ <ItemGroup>
+ <Compile Update="Resources\Controllers\TokenController.en.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>TokenController.en.resx</DependentUpon>
+ </Compile>
+ </ItemGroup>
+
+ <ItemGroup>
+ <EmbeddedResource Update="Resources\Controllers\TokenController.en.resx">
+ <Generator>PublicResXFileCodeGenerator</Generator>
+ <LastGenOutput>TokenController.en.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
+ </ItemGroup>
</Project>