2017-12-12 12:05:22 +08:00
|
|
|
<?php
|
|
|
|
/**
|
|
|
|
* Handle the authentication for the API layer
|
|
|
|
*/
|
|
|
|
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
|
2018-01-05 10:50:57 +08:00
|
|
|
use App\Models\Enums\UserState;
|
2018-02-21 12:33:09 +08:00
|
|
|
use App\Models\User;
|
2017-12-12 12:05:22 +08:00
|
|
|
use Auth;
|
|
|
|
use Closure;
|
|
|
|
|
|
|
|
class ApiAuth
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Handle an incoming request.
|
|
|
|
*
|
|
|
|
* @param \Illuminate\Http\Request $request
|
|
|
|
* @param \Closure $next
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function handle($request, Closure $next)
|
|
|
|
{
|
|
|
|
// Check if Authorization header is in place
|
2017-12-31 03:31:11 +08:00
|
|
|
$api_key = $request->header('x-api-key', null);
|
|
|
|
if($api_key === null) {
|
|
|
|
$api_key = $request->header('Authorization', null);
|
|
|
|
if ($api_key === null) {
|
|
|
|
return $this->unauthorized('X-API-KEY header missing');
|
|
|
|
}
|
2017-12-12 12:05:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Try to find the user via API key. Cache this lookup
|
2017-12-13 06:58:27 +08:00
|
|
|
$user = User::where('api_key', $api_key)->first();
|
|
|
|
if($user === null) {
|
2017-12-31 01:58:34 +08:00
|
|
|
return $this->unauthorized('User not found with key "'.$api_key.'"');
|
2017-12-12 12:05:22 +08:00
|
|
|
}
|
|
|
|
|
2018-01-05 10:50:57 +08:00
|
|
|
if($user->state !== UserState::ACTIVE) {
|
|
|
|
return $this->unauthorized('User is not ACTIVE, please contact an administrator');
|
|
|
|
}
|
|
|
|
|
2017-12-12 12:05:22 +08:00
|
|
|
// Set the user to the request
|
|
|
|
Auth::setUser($user);
|
2018-01-03 04:37:52 +08:00
|
|
|
$request->merge(['user' => $user]);
|
2017-12-12 12:05:22 +08:00
|
|
|
$request->setUserResolver(function () use ($user) {
|
|
|
|
return $user;
|
|
|
|
});
|
|
|
|
|
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return an unauthorized message
|
|
|
|
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
|
|
|
|
*/
|
2017-12-31 01:58:34 +08:00
|
|
|
private function unauthorized($details='')
|
2017-12-12 12:05:22 +08:00
|
|
|
{
|
|
|
|
return response([
|
|
|
|
'error' => [
|
|
|
|
'code' => '401',
|
|
|
|
'http_code' => 'Unauthorized',
|
2017-12-31 01:58:34 +08:00
|
|
|
'message' => 'Invalid or missing API key ('. $details .')',
|
2017-12-12 12:05:22 +08:00
|
|
|
],
|
|
|
|
], 401);
|
|
|
|
}
|
|
|
|
}
|