58 lines
2.2 KiB
PHP
58 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Laravel\Socialite\Facades\Socialite;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class VerifyMicrosoftSession
|
|
{
|
|
/**
|
|
* Handle an incoming request.
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$user = Auth::user();
|
|
|
|
// Only check if user is authenticated and has a Microsoft ID linked
|
|
if ($user && $user->microsoft_id) {
|
|
$lastChecked = session('ms_session_last_checked');
|
|
|
|
// Check every 30 seconds upon page access/refresh
|
|
if (!$lastChecked || now()->diffInSeconds($lastChecked) > 30) {
|
|
// Set timestamp immediately to prevent redirect loop
|
|
session(['ms_session_last_checked' => now()]);
|
|
|
|
// Store target URL to return to after silent verification
|
|
session(['sso_check_origin' => $request->fullUrl()]);
|
|
|
|
// Determine domain hint based on user's email domain
|
|
$domainHint = (str_ends_with($user->email, '.onmicrosoft.com') || (str_contains($user->email, '@') && !str_ends_with($user->email, 'outlook.com') && !str_ends_with($user->email, 'hotmail.com') && !str_ends_with($user->email, 'live.com')))
|
|
? 'organizations'
|
|
: 'consumers';
|
|
|
|
try {
|
|
// Redirect to Microsoft with prompt=none to check session status
|
|
return Socialite::driver('microsoft')
|
|
->redirectUrl(route('sso.callback-check'))
|
|
->with([
|
|
'login_hint' => $user->email,
|
|
'domain_hint' => $domainHint,
|
|
'prompt' => 'none'
|
|
])
|
|
->redirect();
|
|
} catch (\Exception $e) {
|
|
\Illuminate\Support\Facades\Log::error('Microsoft session silent verification failed', [
|
|
'message' => $e->getMessage()
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return $next($request);
|
|
}
|
|
}
|