Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting a request attribute #1080

Open
andreastedile opened this issue Jun 13, 2022 · 2 comments
Open

Setting a request attribute #1080

andreastedile opened this issue Jun 13, 2022 · 2 comments

Comments

@andreastedile
Copy link

andreastedile commented Jun 13, 2022

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! 😄

@dennisjenkins75
Copy link
Collaborator

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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants