vendredi 2 août 2019

Access $user variable inside of Laravel middleware

I have a Laravel application that I have integrated with Xenforo so I can use Xenforo as the main user system behind the application. All of that is working properly, but my next challenge is trying to create middleware that takes the users' Xenforo permissions and restricts access to certain pages on the Laravel application.

I have a $user variable that I am passing to all of my views, and that contains all of the necessary user data that I need. I'm curious how I would go about accessing that same $user variable within my middleware to pull out their forum permissions?

I have researched passing variables through the routes which I can access in the middleware. However, I am not looking to pass an actual parameter through the url to accomplish the task.

My BaseController contains the following and passes the $user variable to all of my views.

class BaseController extends Controller
{
    public function __construct()
    {
      // Setting up the Xenforo enviornment
      $dir = __DIR__;
      require_once('../public/forum/src/XF.php');
      \XF::start($dir);
      $app = \XF::setupApp('XF\Pub\App');

      // Retrieving the user_id of the current authenticated user
      $session = $app->session();
      $user_id = $session->get('userId');

      // Looking up a users information by their user_id
      $finder = \XF::finder('XF:User');
      $user = $finder->where('user_id', $user_id)->fetchOne();

      // Passing the user to every view
      View::share('user', $user);
    }
}

Here is the middleware and how I'm trying to get it to operate. My biggest issue is trying to get access to the $user variable that I originally created above.

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      // I cannot access the $user variable currently
      if ($user->is_staff == true)
      {
          return $next($request);
      }
      else
      {
          //Restrict access and redirect
      }

    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire