feat: enhance request validation with method checks and error handling

This commit is contained in:
whaffman 2025-10-30 23:04:27 +01:00
parent f0aaef2ee0
commit d8fb7d0846
2 changed files with 15 additions and 3 deletions

View File

@ -1,6 +1,7 @@
#include <webserv/client/Client.hpp>
#include <webserv/handler/CgiHandler.hpp> // for CgiHandler
#include <webserv/handler/ErrorHandler.hpp> // for ErrorHandler
#include <webserv/handler/URI.hpp>
#include <webserv/http/HttpHeaders.hpp> // for HttpHeaders
#include <webserv/http/HttpRequest.hpp> // for HttpRequest
#include <webserv/http/HttpResponse.hpp> // for HttpResponse
@ -110,7 +111,8 @@ void Client::request()
catch (const RequestValidator::ValidationException &e)
{
Log::error("Validation Exception during request handling: " + std::string(e.what()));
ErrorHandler::createErrorResponse(e.code(), *httpResponse_);
const auto &config = httpRequest_->getUri().getConfig();
ErrorHandler::createErrorResponse(e.code(), *httpResponse_, config);
return;
}
catch (const std::exception &e)

View File

@ -1,7 +1,9 @@
#include "webserv/log/Log.hpp"
#include <webserv/config/AConfig.hpp>
#include <webserv/http/RequestValidator.hpp>
#include <algorithm>
#include <cstddef>
#include <optional>
#include <string>
@ -85,8 +87,15 @@ std::optional<RequestValidator::ValidationError> RequestValidator::validateMetho
if (request->getMethod().empty())
{
return ValidationError{400, "Bad Request: Empty HTTP Method"};
return ValidationError{400, "Bad Request: Empty or Invalid HTTP Method"};
}
std::vector<std::string> possibleMethods = {"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"};
if (std::ranges::find(possibleMethods, request->getMethod()) == possibleMethods.end())
{
return ValidationError{501, "Method Not Implemented"};
}
if (allowedMethodsOpt.has_value())
{
allowedMethods = std::move(*allowedMethodsOpt);
@ -102,6 +111,7 @@ std::optional<RequestValidator::ValidationError> RequestValidator::validateMetho
return std::nullopt; // Method is allowed
}
}
return ValidationError{405, "Method Not Allowed"};
}