Cachet/app/Http/Middleware/ApiAuthenticate.php

71 lines
1.7 KiB
PHP
Raw Normal View History

2015-03-20 18:30:45 -06:00
<?php
/*
* This file is part of Cachet.
*
* (c) James Brooks <james@cachethq.io>
* (c) Joseph Cohen <joseph.cohen@dinkbit.com>
* (c) Graham Campbell <graham@mineuk.com>
*
* 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)
{
if ($apiToken = $request->header('X-Cachet-Token')) {
try {
2015-05-20 17:01:26 -05:00
$user = User::findByApiToken($apiToken);
$this->auth->onceUsingId($user->id);
2015-03-20 18:30:45 -06:00
} catch (ModelNotFoundException $e) {
return response()->json([
'message' => 'The API token you provided was not correct.',
'status_code' => 401,
], 401);
}
} else {
return response()->json([
'message' => 'You are not authorized to view this content.',
'status_code' => 401,
], 401);
}
return $next($request);
}
}