Finer checks for finer error messages

This commit is contained in:
nugroho 2025-05-20 02:29:42 +07:00
parent ff2f5eaaf6
commit f4f611d82d

View File

@ -248,18 +248,40 @@ internal static class HttpContextExtensions
{ {
internal static async Task<bool> RequestValidated(this HttpContext Context, int RequiredLevel = 0, string ValidMethod = "GET", bool CheckJson = false) internal static async Task<bool> RequestValidated(this HttpContext Context, int RequiredLevel = 0, string ValidMethod = "GET", bool CheckJson = false)
{ {
if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase) || if (!ValidMethod.Equals(Context.Request.Method, StringComparison.OrdinalIgnoreCase))
(CheckJson && !Context.Request.HasJsonContentType()))
{ {
await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed."); await Context.WriteJsonResponse(StatusCodes.Status405MethodNotAllowed, "Method Not Allowed.");
return false; return false;
} }
if (CheckJson && !Context.Request.HasJsonContentType())
if (!Auth.IsAuthorized(Context, RequiredLevel))
{ {
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; return false;
} }
if (!Auth.IsAuthorized(Context, RequiredLevel))
{
await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized.");
return false;
}
return true;
}
internal static async Task<bool> 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; return true;
} }
internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message, object Data) internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message, object Data)