1

I need to check the user roles provided by spatie/laravel-permission, and i was wondering if it would be possible to create a guzzle request in the middleware that executes on every route.

for the API i am using Laravel/Passport.

suggestions for other/better methods are Welcome as well.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • Wouldnt you be able to access the user directly in the middleware? I see no reason to use guzzle to make a different request to a route to check this. – killstreet Mar 18 '21 at 15:48
  • 1
    front-end and back-end are seperated, so i can't just access the user without making a request, but the main goal is that this role is returned before my .blade.php is loaded in, @killstreet – Quinten van den Herik Mar 18 '21 at 16:05
  • After reading some documentation of the spatie/laravel-permission it looks like you should be able to use the @can () method in blade instead. https://spatie.be/docs/laravel-permission/v3/introduction and https://laravel.com/docs/8.x/authorization#via-blade-templates. would this not suffice the work? There is also little information in your question, maybe tell what it is you want to achieve? That way we can look for maybe other methods. Question is a bit abstract right now to get into details. – killstreet Mar 19 '21 at 09:06
  • 1
    @killstreet Okay so its like this: back-end Authentication functions completely, no problems user gets blocked or redirected from requests, if he doesn't have the right user role to proceed. But the front-end blade files have to make an HTTP call to receive information from the server to know what role is assigned to the user, so therefore the blade files are loaded before the ajax calls are executed, so `@can` is no option. that's why i was wondering if i can make an api call with guzzle before my blade files are loaded. I hopes this clarifies the goal, :D – Quinten van den Herik Mar 19 '21 at 15:42
  • normally when permissions are required and backend and frontend are separate you use something like local storage or any frontend hooks, to store the permissions when one logs in and use it in frontend to avoid checking it from back again – bhucho Mar 20 '21 at 04:50
  • because sending an http request via middleware will slow down all api and for a http request you are doing another – bhucho Mar 20 '21 at 04:51
  • @bhucho, the challenge with `localStorage` is that you **don't** know when an update has been made on the previously stored _permissions_ between multiple HTTP requests. – steven7mwesigwa Mar 20 '21 at 13:12
  • when permissions are changed you log out the user with message and once logs in then you get new localstorage – bhucho Mar 21 '21 at 11:16
  • @QuintenvandenHerik You say your frontend and backend are separated. What do you use for frontend? This would help to clarify the actual situation. – killstreet Mar 21 '21 at 16:22
  • @QuintenvandenHerik let's continue this in chat. [Lets continue this in a chat](https://chat.stackoverflow.com/rooms/230186/can-i-create-a-middleware-that-executes-an-guzzle-request) – killstreet Mar 21 '21 at 16:34
  • @killstreet, nvm. Ty for the time and explanation, but i am going to use a different method. – Quinten van den Herik Mar 22 '21 at 09:17

1 Answers1

0

Is used this code for the Guzzle http request:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Session;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $requiredRoles="none")
    {

        $response = Http::withToken(Session::get('accessToken'))->withHeaders([
                    "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
                    "Origin" => "http://base.fourdesign-test.nl",
                    'Content-Type' => "application/json",
                    "Access-Control-Allow-Origin" => '*'])->withOptions(['base_uri' => env('API_URL')])->get("/api/checkpermission");

        if(!$response) {
            die();
        }

        if($requiredRoles == "none" && empty($response['userRoles'])) {
            return $next($request);
        } else if(empty($response['userRoles'])) {
            return redirect('/login');
        }

        $requiredRoles = explode("|", $requiredRoles);
        $allowRequest = false;
        foreach ($response['userRoles'] as $userRole) {
            Session::put($userRole, true);
            foreach ($requiredRoles as $requiredRole) {
                if ($requiredRole == 'none') {
                    $allowRequest = true;
                }
                if ($requiredRole == $userRole) {
                    $allowRequest = true;
                }
            }
        }

        if ($allowRequest === true) {
            return $next($request);
        }

        return redirect()->back();
    }
}