Files
alrahma_sunday_school_api/app/Http/Middleware/TeacherPortalAuthenticate.php
T
root 36101b78d3
API CI/CD / Validate (composer + pint) (push) Successful in 2m7s
API CI/CD / Test (PHPUnit) (push) Failing after 2m17s
API CI/CD / Build frontend assets (push) Successful in 2m13s
API CI/CD / Security audit (push) Successful in 32s
API CI/CD / Deploy to shared hosting (PHP) (push) Has been skipped
fix: guard Auth::guard('sanctum') call with try-catch in TeacherPortalAuthenticate
The TeacherPortalAuthenticate middleware called Auth::guard('sanctum')
without a try-catch, unlike MultiAuth and EnsurePrintRequestsAdminAccess
which already handle the InvalidArgumentException gracefully when the
sanctum guard driver is not yet registered.

This caused 'Auth guard [sanctum] is not defined' errors in tests when
the SanctumServiceProvider's driver registration hadn't completed before
middleware execution.
2026-06-24 02:33:06 -04:00

53 lines
1.4 KiB
PHP

<?php
namespace App\Http\Middleware;
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;
/**
* Session (web) auth first (legacy parity), then Sanctum / JWT like {@see MultiAuth}.
*/
class TeacherPortalAuthenticate
{
public function handle(Request $request, Closure $next): Response
{
if (Auth::guard('web')->check()) {
Auth::setUser(Auth::guard('web')->user());
return $next($request);
}
try {
$sanctumUser = Auth::guard('sanctum')->user();
} catch (\InvalidArgumentException) {
$sanctumUser = null;
}
if ($sanctumUser) {
Auth::setUser($sanctumUser);
return $next($request);
}
$token = $request->bearerToken();
if ($token !== null && $token !== '') {
try {
$jwtUser = JWTAuth::setToken($token)->authenticate();
if ($jwtUser) {
Auth::setUser($jwtUser);
return $next($request);
}
} catch (JWTException $e) {
// fall through
}
}
return response()->json(['message' => 'Unauthorized.'], 401);
}
}