ldc-legaulois/app/Http/Middleware/EnsureEmailIsVerified.php
2026-09-25 16:25:31 +02:00

54 lines
1.7 KiB
PHP

<?php
namespace App\Http\Middleware;
use Carbon\Carbon;
use Closure;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use LDC\LDCCRM\Models\Customer as CrmCustomer;
class EnsureEmailIsVerified
{
/**
* Specify the redirect route for the middleware.
*/
public static function redirectTo(string $route): string
{
return static::class . ':' . $route;
}
/**
* Handle an incoming request.
*
* @param string|null $redirectToRoute
*/
public function handle(Request $request, Closure $next, $redirectToRoute = null): mixed
{
/** @var \App\Models\Customer $customerModel */
$customerModel = $request->user();
if ($customerModel instanceof MustVerifyEmail) {
$crmCustomer = CrmCustomer::findWithEmail($customerModel->email);
// Check there is a crm customer.
if (! $crmCustomer) {
$customerModel->delete();
} else {
// Check the status of crm customer & customer model.
if ($crmCustomer->status !== $customerModel->hasVerifiedEmail()) {
$customerModel->email_verified_at = $crmCustomer->status ? Carbon::now() : null;
$customerModel->saveOrFail();
}
if (! $crmCustomer->status && ! $customerModel->hasVerifiedEmail()) {
return $request->expectsJson()
? abort(403, 'Your email address is not verified.')
: Redirect::guest(URL::route($redirectToRoute ?: 'club.verification.notice'));
}
}
}
return $next($request);
}
}