phpvms/app/Http/Middleware/ApiAuth.php

74 lines
2.0 KiB
PHP
Raw Normal View History

<?php
/**
* Handle the authentication for the API layer
*/
namespace App\Http\Middleware;
use App\Contracts\Middleware;
use App\Models\Enums\UserState;
2018-02-21 12:33:09 +08:00
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ApiAuth implements Middleware
{
/**
* Handle an incoming request.
*
2018-08-27 00:40:04 +08:00
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
// Check if Authorization header is in place
$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');
}
}
// Try to find the user via API key. Cache this lookup
$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.'"');
}
if ($user->state !== UserState::ACTIVE) {
return $this->unauthorized('User is not ACTIVE, please contact an administrator');
}
// Set the user to the request
Auth::setUser($user);
2018-01-03 04:37:52 +08:00
$request->merge(['user' => $user]);
$request->setUserResolver(function () use ($user) {
return $user;
});
return $next($request);
}
/**
* Return an unauthorized message
2018-08-27 00:40:04 +08:00
*
* @param mixed $details
*
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
*/
private function unauthorized($details = '')
{
return response([
'error' => [
'code' => '401',
'http_code' => 'Unauthorized',
'message' => 'Invalid or missing API key ('.$details.')',
],
], 401);
}
}