0

I have an authorization using middleware where Function could only run when authorized

this is my middleware:

class IsAdmin
{
    public function handle($request, Closure $next)
    {
        if (auth()->check() && auth()->user()->is_admin == 1) {
            return $next($request);
        }

        return abort(403, 'Forbidden');
    }
}

my Controller:

public function destroy(int $bookId, int $reviewId, Request $request)
{
    // @TODO implement

    $check_bookReview = BookReview::firstWhere('id', $reviewId)->where('book_id', $bookId);
    if ($check_bookReview && isAdmin()) {
        BookReview::destroy($reviewId);
        return response()->noContent();
    } else {
        abort(404);
    }
}

and my api.php as well my Kernel:

'auth.admin' => \App\Http\Middleware\IsAdmin::class

Route::group(['middleware' => ['auth.admin']], function (){
Route::post('/books', 'BooksController@store');
Route::post('/books/{id}/reviews', 'BooksReviewController@store');
Route::delete('/books/{bookId}/reviews/{reviewId}', 'BooksReviewController@destroy');
});

and i have a User db field where it contains api_token and is_admin like below: User DB

and my Postman still return 403 forbidden while i already gave an authorization by headers: Postman

what should i do here, to fulfill my function?

1 Answer 1

1

Looks like your Authenticate middleware is not working, so it likely fails on auth()->check().

Make sure to use the auth middleware from Laravel, you can also use a guard as described here: https://laravel.com/docs/9.x/authentication#protecting-routes

Sign up to request clarification or add additional context in comments.

6 Comments

i've changed it into auth middleware from laravel, its still the same, what i don't understand is am i doing the correct way on my postman?
Still the same meaning what error exactly? (You have suspicious isAdmin() function call in the controller which shouldn’t be there..
isAdmin() is my middleware class for authorization in my route, the error is forbidden 403 in postman which when I implement middleware auth in my route
Show the error. Also I mean the IsAdmin() function call you have in the controller which shouldn’t be there.
the error is in the picture above, the postman one. i put it on the controller to check if user isAdmin() then function can run else 404
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.