From f4f611d82df1f041b1a8f2f616b5fdd19cc3329d Mon Sep 17 00:00:00 2001 From: nugroho Date: Tue, 20 May 2025 02:29:42 +0700 Subject: [PATCH] Finer checks for finer error messages --- Commons.cs | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/Commons.cs b/Commons.cs index c36a550..46c6129 100644 --- a/Commons.cs +++ b/Commons.cs @@ -248,18 +248,40 @@ internal static class HttpContextExtensions { internal static async Task RequestValidated(this HttpContext Context, int RequiredLevel = 0, string ValidMethod = "GET", bool CheckJson = false) { - if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase) || - (CheckJson && !Context.Request.HasJsonContentType())) + if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase)) { await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed."); return false; } - - if (!Auth.IsAuthorized(Context, RequiredLevel)) + if (CheckJson && !Context.Request.HasJsonContentType()) { - await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized."); + await Context.WriteJsonResponse(StatusCodes.Status415UnsupportedMediaType, $"Supports only explicitly set application/json content-type, but received {Context.Request.ContentType ?? "request with no content-type set"} instead."); return false; } + if (!Auth.IsAuthorized(Context, RequiredLevel)) + { + await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized."); + return false; + } + return true; + } + internal static async Task RequestValidated(this HttpContext Context, string RequiredUserName, string ValidMethod = "GET", bool CheckJson = false) + { + if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase)) + { + await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed."); + return false; + } + if (CheckJson && !Context.Request.HasJsonContentType()) + { + await Context.WriteJsonResponse(StatusCodes.Status415UnsupportedMediaType, $"Supports only explicitly set application/json content-type, but received {Context.Request.ContentType ?? "request with no content-type set"} instead."); + return false; + } + if (!Auth.IsAuthorized(Context, RequiredUserName)) + { + await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized."); + return false; + } return true; } internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message, object Data)