Skip to content

Commit

Permalink
Updated CorsFilter.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
tembolo1284 committed Dec 15, 2024
1 parent a024cd0 commit e6564cd
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions api/src/filters/CorsFilter.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// CorsFilter.cpp
#include "filters/CorsFilter.h"
#include "utils/Logger.h"

Expand All @@ -8,32 +7,46 @@ namespace api {
void CorsFilter::doFilter(const drogon::HttpRequestPtr& req,
drogon::FilterCallback&& fcb,
drogon::FilterChainCallback&& fccb) {
API_LOG_DEBUG("Processing CORS request for path: {}", req->getPath());
API_LOG_DEBUG("Starting CORS filter for path: {} method: {}", req->getPath(), req->getMethodString());
API_LOG_DEBUG("Request headers:");
for (const auto& header : req->getHeaders()) {
API_LOG_DEBUG(" {}: {}", header.first, header.second);
}

// Handle preflight OPTIONS request
if (req->getMethodString() == "OPTIONS") {
// Handle preflight request
API_LOG_DEBUG("Handling OPTIONS preflight request");
API_LOG_DEBUG("Processing OPTIONS preflight request");
auto resp = drogon::HttpResponse::newHttpResponse();

// Add CORS headers for preflight
resp->addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
resp->addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
resp->addHeader("Access-Control-Allow-Headers", "Content-Type");
resp->addHeader("Access-Control-Max-Age", "86400");
resp->addHeader("Access-Control-Allow-Headers", "*");
resp->addHeader("Access-Control-Max-Age", "3600");

// Important: Set status 200 for OPTIONS
// Set 200 OK status
resp->setStatusCode(drogon::k200OK);

API_LOG_DEBUG("Sending preflight response with headers:");
for (const auto& header : resp->getHeaders()) {
API_LOG_DEBUG(" {}: {}", header.first, header.second);
}

fcb(resp);
return;
}

// For non-OPTIONS requests
auto resp = drogon::HttpResponse::newHttpResponse();
resp->addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
resp->addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
resp->addHeader("Access-Control-Allow-Headers", "Content-Type");
// For actual request
API_LOG_DEBUG("Processing actual request");

// Continue with the request chain
// Continue with request chain and add CORS headers to the final response
auto modCallback = [fcb](const drogon::HttpResponsePtr& responsePtr) {
responsePtr->addHeader("Access-Control-Allow-Origin", "http://localhost:3000");
responsePtr->addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
responsePtr->addHeader("Access-Control-Allow-Headers", "*");
fcb(responsePtr);
};

fccb();
}

Expand Down

0 comments on commit e6564cd

Please sign in to comment.