drogonframework / drogon

Drogon: A C++14/17/20 based HTTP web application framework running on Linux/macOS/Unix/Windows
MIT License
11.44k stars 1.1k forks source link

Sesion , cookie and headers clearity in drogon #1735

Closed behindmagic9 closed 1 year ago

behindmagic9 commented 1 year ago

i don't find this in the documentation of the drogon , do drogon automatically handles the sessionId or we do have to provide one ?? whats the cookie and sessionId mechanism in drogon ??if any client does not let support cookies then how it handles that , by url ?? or nay other alternate method ?how ??? what header top include while setting/adding up the cookie especially in Json format , like storing session id as well as user information?? And ... can anybody please tell me whats wrong in these handler? its showing parse error in storeJsonInCookie handler and not retrieving any from the retrieving handler !!

class MyController : public HttpController<MyController> {
public:
    METHOD_LIST_BEGIN
        ADD_METHOD_TO(MyController::storeJsonInCookie, "/storeJsonInCookie", HttpMethod::Post);
        ADD_METHOD_TO(MyController::retrieveJsonFromCookie, "/retrieveJsonFromCookie", HttpMethod::Get);
    METHOD_LIST_END

    void storeJsonInCookie(const HttpRequestPtr& req, std::function<void(const HttpResponsePtr&)>&& callback) {
        Json::Value jsonData;
        jsonData["name"] = "John Doe";
        jsonData["age"] = 30;
        jsonData["location"] = "New York";

        std::String jsonString = jsonData.toStyledString();
        LOG_DEBUG << "json value is : " << jsonString ;

        auto response = HttpResponse::newHttpResponse();
    Cookie cookie("user_data", jsonString);
        response->addCookie(cookie);

        response->setBody("JSON data stored in the cookie");
        callback(response);
    }

void retrieveJsonFromCookie(const HttpRequestPtr& req, std::function<void(const HttpResponsePtr&)>&& callback) {
    const std::string& cookieValue = req->getCookie("user_data");

    LOG_DEBUG << "Received Cookie Value: " << cookieValue;

    if (!cookieValue.empty()) {
          Json::Value jsonData;
        Json::Reader reader;
        bool parsingSuccessful = reader.parse(cookieValue, jsonData);

        if (parsingSuccessful) {
            auto response = HttpResponse::newHttpJsonResponse(jsonData);
            response->addHeader("Content-Type", "application/json");
            LOG_DEBUG << "Successfully parsed JSON from cookie.";

            LOG_DEBUG << "Parsed JSON data: " << jsonData.toStyledString();

            callback(response);
        } else {
            // Handle parsing error
            auto response = HttpResponse::newHttpResponse();
            response->setBody("Error parsing JSON data from cookie");
            LOG_DEBUG << "Error parsing JSON data from cookie.";
            callback(response);
        }
    } else {
        auto response = HttpResponse::newHttpResponse();
        response->setBody("Cookie is empty");
        LOG_DEBUG << "Cookie is empty.";
        callback(response);
    }}
};
hwc0919 commented 1 year ago

Session in drogon

Drogon uses cookie based session. This is a widely used technology, you could google it out easily.

do drogon automatically handles the sessionId or we do have to provide one

If you set enable_session: true if config, drogon will automatically search for JSESSIONID cookie in resquest header, and add set-cookie header in responses. For every JSESSIONID, there is a session allocated in memory. Custom data should be stored in session.

If client send requests with correct JSESSIONID cookie, drogon will find the corresponding session. Use HttpRequest::getSession() to get it, and use it like a map to store your custom data.

if any client does not let support cookies then how it handles that

To make session work, client side must handle cookie correctly. Normal web browsers will handle cookie automatically.

HTTP is a stateless protocol. If client side does not send back cookie(for example, using incognito mode in chrome), you could NEVER make use of cookie-based session. In this case, every request send by client will be treated as from a new sender and a new session will be allocated for it. This would be a waste of memory.

Cookie in drogon

Nothing special to explain here, just regular cookie. Both HttpRequest and HttpResponse have getCookie() and addCookie() apis.

behindmagic9 commented 1 year ago

ohkayy , can you please correct my code above that be very helpful in clear understanding of this ?? !!

drizzle042 commented 4 months ago

@hwc0919 just to clarify. You said:

Drogon allocates Session in memory.

Isn’t this a bit prodigal? Are there any other options for Session storage?