Initialize repo and add session changes (2025-09-08)
This commit is contained in:
32
app/Http/Middleware/ApiTokenAuth.php
Normal file
32
app/Http/Middleware/ApiTokenAuth.php
Normal file
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\User;
|
||||
|
||||
class ApiTokenAuth
|
||||
{
|
||||
public function handle(Request $request, Closure $next)
|
||||
{
|
||||
$header = $request->header('Authorization', '');
|
||||
if (! str_starts_with($header, 'Bearer ')) {
|
||||
return response()->json(['error' => ['code' => 'unauthorized']], 401);
|
||||
}
|
||||
$token = substr($header, 7);
|
||||
$userId = Cache::get('api_token:'.$token);
|
||||
if (! $userId) {
|
||||
return response()->json(['error' => ['code' => 'unauthorized']], 401);
|
||||
}
|
||||
$user = User::find($userId);
|
||||
if (! $user) {
|
||||
return response()->json(['error' => ['code' => 'unauthorized']], 401);
|
||||
}
|
||||
Auth::login($user); // for policies if needed
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user