* @author Graham Campbell * @author James Brooks */ class ApiAuthentication { /** * The authentication guard instance. * * @var \Illuminate\Contracts\Auth\Guard */ protected $auth; /** * Create a new api authentication middleware instance. * * @param \Illuminate\Contracts\Auth\Guard $auth * * @return void */ public function __construct(Guard $auth) { $this->auth = $auth; } /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param bool $required * * @return mixed */ public function handle(Request $request, Closure $next, $required = false) { if ($this->auth->guest()) { if ($apiToken = $request->header('X-Cachet-Token')) { try { $this->auth->onceUsingId(User::findByApiToken($apiToken)->id); } catch (ModelNotFoundException $e) { if ($required) { throw new HttpException(401); } } } elseif ($required) { throw new HttpException(401); } } return $next($request); } }