Cachet/app/Http/Middleware/ApiAuthenticate.php

68 lines
1.7 KiB
PHP
Raw Normal View History

2015-03-20 18:30:45 -06:00
<?php
/*
* This file is part of Cachet.
*
2015-07-06 17:37:01 +01:00
* (c) Alt Three Services Limited
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
2015-03-20 18:30:45 -06:00
namespace CachetHQ\Cachet\Http\Middleware;
use CachetHQ\Cachet\Models\User;
use Closure;
2015-05-20 17:01:26 -05:00
use Illuminate\Contracts\Auth\Guard;
2015-03-20 18:30:45 -06:00
use Illuminate\Database\Eloquent\ModelNotFoundException;
2015-06-18 18:12:10 +01:00
use Symfony\Component\HttpKernel\Exception\HttpException;
2015-03-20 18:30:45 -06:00
class ApiAuthenticate
{
2015-05-20 17:01:26 -05:00
/**
2015-06-10 14:03:31 +01:00
* The authentication guard instance.
2015-05-20 17:01:26 -05:00
*
* @var \Illuminate\Contracts\Auth\Guard
*/
protected $auth;
/**
2015-06-10 14:03:31 +01:00
* Create a new api authenticate middleware instance.
2015-05-20 17:01:26 -05:00
*
* @param \Illuminate\Contracts\Auth\Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
2015-03-20 18:30:45 -06:00
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($apiToken = $request->header('X-Cachet-Token')) {
try {
$this->auth->onceUsingId(User::findByApiToken($apiToken)->id);
} catch (ModelNotFoundException $e) {
2015-06-18 18:12:10 +01:00
throw new HttpException(401);
}
} elseif ($request->getUser()) {
if ($this->auth->onceBasic() !== null) {
2015-06-18 18:12:10 +01:00
throw new HttpException(401);
}
} else {
2015-06-18 18:12:10 +01:00
throw new HttpException(401);
2015-03-20 18:30:45 -06:00
}
}
return $next($request);
}
}