<?php
 namespace App\Http\Middleware; use App\Models\Setting; use App\Services\CitizenshipService; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class EnsureEmailIsVerified { private const ALLOWED_ROUTES = [ 'email' => [ 'store.auth.verify-email', 'store.auth.resend-email-verification', 'store.auth.logout', ], 'sms' => [ 'store.auth.verify-phone', 'store.auth.send-phone-verification', 'store.auth.logout', ], 'citizenship' => [ 'store.auth.verify-citizenship', 'store.auth.logout', ], ]; public function handle(Request $request, Closure $next) { if (! Auth::guard('client')->check()) { return $next($request); } $client = Auth::guard('client')->user(); $routeName = $request->route()?->getName(); if (Setting::getValue('email_verification', true) && ! $client->email_verified_at) { if ($this->isAllowedRoute($routeName, 'email')) { return $next($request); } return $this->respond($request, 'store.auth_email_verification_required', 'store.auth.verify-email'); } if (Setting::getValue('sms_verification', false) && ! $client->phone_verified_at) { if ($this->isAllowedRoute($routeName, 'sms')) { return $next($request); } return $this->respond($request, 'store.auth_phone_verification_required', 'store.auth.verify-phone'); } $citizenshipEnabled = Setting::getValue('citizenship_verification', false) || Setting::getValue('verification_enabled', false); if ($citizenshipEnabled && in_array($client->verification_status, ['unverified', 'pending', 'expired'], true)) { $countryCode = $client->country?->a2_iso; $hasCountrySettings = $countryCode ? \App\Models\CitizenshipCountrySetting::where('country_code', $countryCode)->exists() : false; if ($hasCountrySettings) { if ($this->isAllowedRoute($routeName, 'citizenship')) { return $next($request); } return $this->respond($request, 'store.auth_citizenship_verification_required', 'store.auth.verify-citizenship'); } } return $next($request); } private function isAllowedRoute(?string $routeName, string $step): bool { if (! $routeName) { return false; } $allAllowed = array_merge( self::ALLOWED_ROUTES['email'], self::ALLOWED_ROUTES['sms'], self::ALLOWED_ROUTES['citizenship'] ); return in_array($routeName, $allAllowed); } private function respond(Request $request, string $messageKey, string $route) { if ($request->expectsJson()) { return response()->json([ 'message' => __($messageKey), 'redirect' => route($route), ], 403); } return redirect()->route($route) ->with('warning', __($messageKey)); } } 