pistacheio / pistache

A high-performance REST toolkit written in C++
https://pistacheio.github.io/pistache/
Apache License 2.0
3.12k stars 690 forks source link

Setting a request attribute #1080

Open andreastedile opened 2 years ago

andreastedile commented 2 years ago

In the past I have used Java Servlets (now Jarkarta Servlets). With Servlets, I could set a "request attribute". To better explain what a request attribute is, it is easier if I provide a use case.

bool auth_middleware(Request &request, ResponseWriter &response) {
    const auto cookies = req.cookies();
    const auto userId = getUserId(&cookies);
    // use a service to retrieve the User entity corresponding to userId
    const std::optional<User> user = UserService::getUser(userId);
    if (user.has_value()) {
        request.setAttribute("user", user->get());
        return true; // proceed along the chain
    } else {
        response.send(Code::Bad_Request);
        return false; // reject the request
    }
}

When the execution flow reaches the actual handler, one could do as follows:

void some_handler(const Rest::Request &request, Http::ResponseWriter response) {
    auto user = request.getAttribute<User>("user");
    // use "user" for whatever purpose
}

The advantage of this is that any handler that needs to do something with the User entity does not need to repeat the logic of checking whether the user exists and is authenticated (separation of concerns).

Is it possible to do something like this in Pistache? Thank you! :smile:

dennisjenkins75 commented 2 years ago

Off the top of my head, I don't know if Pistache currently supports this use case, but I can see it being very useful. If Pistache does not have this type of API, you are free to submit a pull requests to add it. Please add proper unit tests to cover your changes.

Fabio3rs commented 1 year ago

I think this is very useful, I did a pull request: #1085