blackbirdchess-server/app/Http/Middleware/EnsureTokenIsValid.php

36 lines
934 B
PHP

<?php
namespace App\Http\Middleware;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class EnsureTokenIsValid
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$token = str_replace('Bearer ', '', $request->headers->get('Authorization'));
$authorization = Cache::get('BBC-' . $token, false);
if(!$authorization) {
throw new UnauthorizedHttpException('You are not logged in');
}
$user = $authorization['User'];
Auth::setUser($user);
return $next($request);
}
}