f83f21936f
API CI/CD / Validate (composer + pint) (push) Successful in 3m30s
API CI/CD / Test (PHPUnit) (push) Failing after 5m4s
API CI/CD / Build frontend assets (push) Successful in 1m1s
API CI/CD / Security audit (push) Failing after 49s
API CI/CD / Deploy to shared hosting (PHP) (push) Has been skipped
75 lines
1.9 KiB
PHP
75 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Support\AccountAvailability;
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException;
|
|
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class MultiAuth
|
|
{
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
try {
|
|
$sanctumUser = Auth::guard('sanctum')->user();
|
|
} catch (\InvalidArgumentException) {
|
|
$sanctumUser = null;
|
|
}
|
|
|
|
if ($sanctumUser) {
|
|
Auth::setUser($sanctumUser);
|
|
|
|
if ($response = $this->denyUnavailableAccount($sanctumUser)) {
|
|
return $response;
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
|
|
try {
|
|
if ($apiUser = Auth::guard('api')->user()) {
|
|
Auth::setUser($apiUser);
|
|
|
|
if ($response = $this->denyUnavailableAccount($apiUser)) {
|
|
return $response;
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
} catch (\Throwable) {
|
|
}
|
|
|
|
$token = $request->bearerToken();
|
|
if ($token) {
|
|
try {
|
|
$jwtUser = JWTAuth::setToken($token)->authenticate();
|
|
if ($jwtUser) {
|
|
Auth::setUser($jwtUser);
|
|
|
|
if ($response = $this->denyUnavailableAccount($jwtUser)) {
|
|
return $response;
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
} catch (JWTException $e) {
|
|
}
|
|
}
|
|
|
|
return response()->json(['message' => 'Unauthorized.'], 401);
|
|
}
|
|
|
|
private function denyUnavailableAccount(object $user): ?Response
|
|
{
|
|
if (AccountAvailability::isAuthUnavailable($user)) {
|
|
return response()->json(['message' => 'Account unavailable.'], 403);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|