<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;

class AssignGuardAndAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @param null $guard
     * @return mixed
     * @throws AuthorizationException exception
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if($guard != null) {
            auth()->shouldUse($guard);
            if (!auth()->check())
                return abort(401);
        }
        return $next($request);
    }
}