From 9adfa3c8311f4ace9388dc805f1a4df6fba97f0e Mon Sep 17 00:00:00 2001 From: crupest Date: Sat, 24 Apr 2021 19:13:35 +0800 Subject: refactor: Refactor auth handler messages. --- BackEnd/Timeline/Auth/MyAuthenticationHandler.cs | 55 ++++---- BackEnd/Timeline/Auth/Resource.Designer.cs | 153 +++++++++++++++++++++ BackEnd/Timeline/Auth/Resource.resx | 150 ++++++++++++++++++++ .../Authentication/AuthHandler.Designer.cs | 99 ------------- .../Resources/Authentication/AuthHandler.resx | 132 ------------------ BackEnd/Timeline/Timeline.csproj | 14 +- 6 files changed, 340 insertions(+), 263 deletions(-) create mode 100644 BackEnd/Timeline/Auth/Resource.Designer.cs create mode 100644 BackEnd/Timeline/Auth/Resource.resx delete mode 100644 BackEnd/Timeline/Resources/Authentication/AuthHandler.Designer.cs delete mode 100644 BackEnd/Timeline/Resources/Authentication/AuthHandler.resx (limited to 'BackEnd') diff --git a/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs b/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs index f1f71b20..f3d18a0e 100644 --- a/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs +++ b/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs @@ -14,7 +14,6 @@ using System.Threading.Tasks; using Timeline.Models; using Timeline.Models.Http; using Timeline.Services; -using static Timeline.Resources.Authentication.AuthHandler; namespace Timeline.Auth { @@ -37,16 +36,28 @@ namespace Timeline.Auth { private const string TokenErrorCodeKey = "TokenErrorCode"; - private static CommonResponse CreateChallengeResponseBody(int errorCode) + private static int GetErrorCodeForUserTokenException(UserTokenException e) { - return new CommonResponse(errorCode, errorCode switch + return e switch { - ErrorCodes.Common.Token.TimeExpired => "The token is out of date and expired. Please create a new one.", - ErrorCodes.Common.Token.VersionExpired => "The token is of old version and expired. Please create a new one.", - ErrorCodes.Common.Token.BadFormat => "The token is of bad format. It might not be created by this server.", - ErrorCodes.Common.Token.UserNotExist => "The owner of the token does not exist. It might have been deleted.", - _ => "Unknown error." - }); + UserTokenTimeExpiredException => ErrorCodes.Common.Token.TimeExpired, + UserTokenVersionExpiredException => ErrorCodes.Common.Token.VersionExpired, + UserTokenBadFormatException => ErrorCodes.Common.Token.BadFormat, + UserTokenUserNotExistException => ErrorCodes.Common.Token.UserNotExist, + _ => ErrorCodes.Common.Token.Unknown + }; + } + + private static string GetTokenErrorMessageFromErrorCode(int errorCode) + { + return errorCode switch + { + ErrorCodes.Common.Token.TimeExpired => Resource.MessageTokenTimeExpired, + ErrorCodes.Common.Token.VersionExpired => Resource.MessageTokenVersionExpired, + ErrorCodes.Common.Token.BadFormat => Resource.MessageTokenBadFormat, + ErrorCodes.Common.Token.UserNotExist => Resource.MessageTokenUserNotExist, + _ => Resource.MessageTokenUnknownError + }; } private readonly ILogger _logger; @@ -72,7 +83,7 @@ namespace Timeline.Auth if (!string.IsNullOrEmpty(header) && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { var token = header["Bearer ".Length..].Trim(); - _logger.LogInformation(LogTokenFoundInHeader, token); + _logger.LogInformation(Resource.LogTokenFoundInHeader, token); return token; } @@ -83,7 +94,7 @@ namespace Timeline.Auth string token = Request.Query[paramQueryKey]; if (!string.IsNullOrEmpty(token)) { - _logger.LogInformation(LogTokenFoundInQuery, paramQueryKey, token); + _logger.LogInformation(Resource.LogTokenFoundInQuery, paramQueryKey, token); return token; } } @@ -97,7 +108,7 @@ namespace Timeline.Auth var token = ExtractToken(); if (string.IsNullOrEmpty(token)) { - _logger.LogInformation(LogTokenNotFound); + _logger.LogInformation(Resource.LogTokenNotFound); return AuthenticateResult.NoResult(); } @@ -117,19 +128,14 @@ namespace Timeline.Auth return AuthenticateResult.Success(new AuthenticationTicket(principal, AuthenticationConstants.Scheme)); } - catch (Exception e) when (!(e is ArgumentException)) + catch (UserTokenException e) { - _logger.LogInformation(e, LogTokenValidationFail); + var errorCode = GetErrorCodeForUserTokenException(e); + + _logger.LogInformation(e, Resource.LogTokenValidationFail, GetTokenErrorMessageFromErrorCode(errorCode)); return AuthenticateResult.Fail(e, new AuthenticationProperties(new Dictionary() { - [TokenErrorCodeKey] = (e switch - { - UserTokenTimeExpiredException => ErrorCodes.Common.Token.TimeExpired, - UserTokenVersionExpiredException => ErrorCodes.Common.Token.VersionExpired, - UserTokenBadFormatException => ErrorCodes.Common.Token.BadFormat, - UserTokenUserNotExistException => ErrorCodes.Common.Token.UserNotExist, - _ => ErrorCodes.Common.Token.Unknown - }).ToString(CultureInfo.InvariantCulture) + [TokenErrorCodeKey] = errorCode.ToString(CultureInfo.InvariantCulture) })); } } @@ -144,14 +150,13 @@ namespace Timeline.Auth { if (!int.TryParse(tokenErrorCode, out var errorCode)) errorCode = ErrorCodes.Common.Token.Unknown; - body = CreateChallengeResponseBody(errorCode); + body = new CommonResponse(errorCode, GetTokenErrorMessageFromErrorCode(errorCode)); } else { - body = new CommonResponse(ErrorCodes.Common.Unauthorized, "You must use a token to authenticate."); + body = new CommonResponse(ErrorCodes.Common.Unauthorized, Resource.MessageNoToken); } - var bodyData = JsonSerializer.SerializeToUtf8Bytes(body, typeof(CommonResponse), _jsonOptions.CurrentValue.JsonSerializerOptions); Response.ContentType = MimeTypes.ApplicationJson; diff --git a/BackEnd/Timeline/Auth/Resource.Designer.cs b/BackEnd/Timeline/Auth/Resource.Designer.cs new file mode 100644 index 00000000..e9ef970e --- /dev/null +++ b/BackEnd/Timeline/Auth/Resource.Designer.cs @@ -0,0 +1,153 @@ +//------------------------------------------------------------------------------ +// +// 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.Auth { + 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 Resource { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resource() { + } + + /// + /// 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.Auth.Resource", typeof(Resource).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 Token is found in authorization header. Token is {0} .. + /// + internal static string LogTokenFoundInHeader { + get { + return ResourceManager.GetString("LogTokenFoundInHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Token is found in query param with key "{0}". Token is {1} .. + /// + internal static string LogTokenFoundInQuery { + get { + return ResourceManager.GetString("LogTokenFoundInQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No jwt token is found.. + /// + internal static string LogTokenNotFound { + get { + return ResourceManager.GetString("LogTokenNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A jwt token validation failed. Error reason: {0}. + /// + internal static string LogTokenValidationFail { + get { + return ResourceManager.GetString("LogTokenValidationFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must use a token to authenticate to access this resource.. + /// + internal static string MessageNoToken { + get { + return ResourceManager.GetString("MessageNoToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The token is of bad format. It might not be created by this server.. + /// + internal static string MessageTokenBadFormat { + get { + return ResourceManager.GetString("MessageTokenBadFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The token is out of date and expired. Please create a new one.. + /// + internal static string MessageTokenTimeExpired { + get { + return ResourceManager.GetString("MessageTokenTimeExpired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A unknown error occured when verify token.. + /// + internal static string MessageTokenUnknownError { + get { + return ResourceManager.GetString("MessageTokenUnknownError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The owner of the token does not exist. It might have been deleted.. + /// + internal static string MessageTokenUserNotExist { + get { + return ResourceManager.GetString("MessageTokenUserNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The token is of old version and expired. Please create a new one.. + /// + internal static string MessageTokenVersionExpired { + get { + return ResourceManager.GetString("MessageTokenVersionExpired", resourceCulture); + } + } + } +} diff --git a/BackEnd/Timeline/Auth/Resource.resx b/BackEnd/Timeline/Auth/Resource.resx new file mode 100644 index 00000000..21f2b2de --- /dev/null +++ b/BackEnd/Timeline/Auth/Resource.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Token is found in authorization header. Token is {0} . + + + Token is found in query param with key "{0}". Token is {1} . + + + No jwt token is found. + + + A jwt token validation failed. Error reason: {0} + + + You must use a token to authenticate to access this resource. + + + The token is of bad format. It might not be created by this server. + + + The token is out of date and expired. Please create a new one. + + + A unknown error occured when verify token. + + + The owner of the token does not exist. It might have been deleted. + + + The token is of old version and expired. Please create a new one. + + \ No newline at end of file diff --git a/BackEnd/Timeline/Resources/Authentication/AuthHandler.Designer.cs b/BackEnd/Timeline/Resources/Authentication/AuthHandler.Designer.cs deleted file mode 100644 index fd4540ea..00000000 --- a/BackEnd/Timeline/Resources/Authentication/AuthHandler.Designer.cs +++ /dev/null @@ -1,99 +0,0 @@ -//------------------------------------------------------------------------------ -// -// 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.Authentication { - 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 AuthHandler { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal AuthHandler() { - } - - /// - /// 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.Authentication.AuthHandler", typeof(AuthHandler).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 Token is found in authorization header. Token is {0} .. - /// - internal static string LogTokenFoundInHeader { - get { - return ResourceManager.GetString("LogTokenFoundInHeader", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Token is found in query param with key "{0}". Token is {1} .. - /// - internal static string LogTokenFoundInQuery { - get { - return ResourceManager.GetString("LogTokenFoundInQuery", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to No jwt token is found.. - /// - internal static string LogTokenNotFound { - get { - return ResourceManager.GetString("LogTokenNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A jwt token validation failed.. - /// - internal static string LogTokenValidationFail { - get { - return ResourceManager.GetString("LogTokenValidationFail", resourceCulture); - } - } - } -} diff --git a/BackEnd/Timeline/Resources/Authentication/AuthHandler.resx b/BackEnd/Timeline/Resources/Authentication/AuthHandler.resx deleted file mode 100644 index 4cddc8ce..00000000 --- a/BackEnd/Timeline/Resources/Authentication/AuthHandler.resx +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - Token is found in authorization header. Token is {0} . - - - Token is found in query param with key "{0}". Token is {1} . - - - No jwt token is found. - - - A jwt token validation failed. - - \ No newline at end of file diff --git a/BackEnd/Timeline/Timeline.csproj b/BackEnd/Timeline/Timeline.csproj index 6b565598..272c8b1e 100644 --- a/BackEnd/Timeline/Timeline.csproj +++ b/BackEnd/Timeline/Timeline.csproj @@ -56,10 +56,10 @@ - - True - True - AuthHandler.resx + + True + True + Resource.resx True @@ -169,9 +169,9 @@ - - ResXFileCodeGenerator - AuthHandler.Designer.cs + + ResXFileCodeGenerator + Resource.Designer.cs ResXFileCodeGenerator -- cgit v1.2.3