Home > Enterprise >  How to authorize before run a function in Controller| Laravel
How to authorize before run a function in Controller| Laravel

Time:08-21

I have an API task where I should authorize before deleting data (BookReview),

Access to this endpoint requires authentication with an API token and admin privileges.

in User table I have api_token and is_admin field: [![User Table][1]][1]

this is my BookReviewController:

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


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

i don't know what to add in my controller, and further more I need to authorize it from postman

[![Postman][2]][2]

the delete function works fine, but there is no authorization yet [1]: https://i.stack.imgur.com/ywvC8.png [2]: https://i.stack.imgur.com/fyhpG.png

CodePudding user response:

You should use some middleware. The middleware is the authetication step that you are missing. In the middleware, you should make the validation like find the user by de token that he sent to you, see if he is an admin an then send the request to the controller (if he is an admin) or return an 401 status code if he is not authorized to do this.

To help you with middleware is nobody better then the documentation

CodePudding user response:

If you have is_admin in your DB so you can check user is admin or not.

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


    $check_bookReview = BookReview::firstWhere('id', $reviewId);
    if ($check_bookReview && auth()->user()->is_admin == 1) {
        BookReview::destroy($reviewId);
        return response()->noContent();
    } else {
        abort(404);
    }
}

or in your controller:

use Auth;

if (Auth::user() &&  Auth::user()->is_admin == 1) {
    //destroy 
}

and if you want use middleware then: in routes/web.php add:

Route::group(['middleware' => ['auth', 'admin']], function () {
    Route::post('/destroy-something', 'YourController@destroy')->name('destroy.review');
});

in app/Http/Middleware create a middleware for admin. then add it to app/Http/Kernel.php to the protected $routeMiddleware array.

  • Related