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,13 +248,16 @@ internal static class HttpContextExtensions
{
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) ||
(CheckJson && !Context.Request.HasJsonContentType()))
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, RequiredLevel))
{
await Context.WriteJsonResponse(StatusCodes.Status401Unauthorized, "Unauthorized.");
@ -262,6 +265,25 @@ internal static class HttpContextExtensions
}
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;
}
internal static async Task WriteJsonResponse(this HttpContext Context, int Status, string Message, object Data)
{
Context.Response.StatusCode = Status;