2015-03-20 18:30:45 -06:00
|
|
|
<?php
|
|
|
|
|
2015-04-19 08:52:39 +01:00
|
|
|
/*
|
|
|
|
* This file is part of Cachet.
|
|
|
|
*
|
2015-05-25 17:59:08 +01:00
|
|
|
* (c) Cachet HQ <support@cachethq.io>
|
2015-04-19 08:52:39 +01:00
|
|
|
*
|
|
|
|
* 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;
|
|
|
|
|
|
|
|
class ApiAuthenticate
|
|
|
|
{
|
2015-05-20 17:01:26 -05:00
|
|
|
/**
|
|
|
|
* The Guard implementation.
|
|
|
|
*
|
|
|
|
* @var \Illuminate\Contracts\Auth\Guard
|
|
|
|
*/
|
|
|
|
protected $auth;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new filter instance.
|
|
|
|
*
|
|
|
|
* @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)
|
|
|
|
{
|
2015-06-02 08:35:30 +01:00
|
|
|
if ($this->auth->guest()) {
|
|
|
|
if ($apiToken = $request->header('X-Cachet-Token')) {
|
|
|
|
try {
|
|
|
|
$user = User::findByApiToken($apiToken);
|
2015-05-20 17:01:26 -05:00
|
|
|
|
2015-06-02 08:35:30 +01:00
|
|
|
$this->auth->onceUsingId($user->id);
|
|
|
|
} catch (ModelNotFoundException $e) {
|
|
|
|
return $this->handleError();
|
|
|
|
}
|
|
|
|
} elseif ($user = $request->getUser()) {
|
|
|
|
if ($this->auth->onceBasic() !== null) {
|
|
|
|
return $this->handleError();
|
|
|
|
}
|
|
|
|
} else {
|
2015-05-22 18:29:09 +01:00
|
|
|
return $this->handleError();
|
2015-03-20 18:30:45 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $next($request);
|
|
|
|
}
|
2015-05-22 18:29:09 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Common method for returning an unauthorized error.
|
|
|
|
*
|
|
|
|
* @return \Symfony\Component\HttpFoundation\Response
|
|
|
|
*/
|
|
|
|
protected function handleError()
|
|
|
|
{
|
|
|
|
return response()->json([
|
|
|
|
'message' => 'You are not authorized to view this content.',
|
|
|
|
'status_code' => 401,
|
|
|
|
], 401);
|
|
|
|
}
|
2015-03-20 18:30:45 -06:00
|
|
|
}
|