flightphp / core

An extensible micro-framework for PHP
https://docs.flightphp.com
MIT License
2.6k stars 407 forks source link

How to stop the request process when there is an issue in the Middleware? #582

Closed pamungkasandono closed 2 months ago

pamungkasandono commented 2 months ago

When I try to validate the token in the middleware, the output generated is not as expected. Here's an example of the middleware I created:

class AuthMiddleware
{
    public function before($params)
    {
        $token = Flight::request()->getHeader("Authorization");
        if (!$token) {
            return Flight::json([
                "message" => "Token required!."
            ], 400);
        }
    }
}

Flight::route('/', function () {
    return Flight::json([
        "message" => "Success."
    ], 200);
})->addMiddleware(new AuthMiddleware());

If I don't send the token in the header, the expected output should be:

{
    "message": "Token required!."
}

But in this case, why is the output:

{
    "message": "Token required!."
}{
    "message": "Success."
}

Could you please assist me? Is there something missing?

n0nag0n commented 2 months ago

My guess is you would do

if (!$token) {
    echo Flight::json([
        "message" => "Token required!."
    ], 400);
    return false; // add this line.
}
pamungkasandono commented 2 months ago

Thank you for your response.

When I tried using return false the return response, what I received is:

Forbidden

image

Do you have any other suggestions?

krmu commented 2 months ago

Instead of return false, try exit();

krmu commented 2 months ago

Worked for me, redirects were acting strange.

n0nag0n commented 2 months ago

Ahh yeah, like @krmu mentioned, I would either directly use exit; to stop execution.

n0nag0n commented 2 months ago

@pamungkasandono I've updated the documentation to be more clear about what behavior to expect. https://docs.flightphp.com/learn/middleware#handling-middleware-errors

pamungkasandono commented 2 months ago

@krmu my middleware is now working as expected with the addition of exit();. @n0nag0n documenting this would be really helpful for other. Thanks, everyone! I truly appreciate it!

n0nag0n commented 1 month ago

Thinking more about this along with some other things that have surfaced, I came up with this PR. https://github.com/flightphp/core/pull/594 Would love your feedback.

So in this case you would just do

Flight::jsonHalt([
    "message" => "Token required!."
], 400);

No exit, no Flight::halt() method. It would immediately stop execution on that line.