pistache icon indicating copy to clipboard operation
pistache copied to clipboard

Setting a request attribute

Open andreastedile opened this issue 2 years ago • 2 comments

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:

andreastedile avatar Jun 13 '22 11:06 andreastedile

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.

dennisjenkins75 avatar Jun 13 '22 16:06 dennisjenkins75

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

Fabio3rs avatar Jul 24 '22 23:07 Fabio3rs