<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureTwoFactor
{
    /**
     * If the current user has 2FA enabled but the current session has not
     * cleared the challenge, send them to the challenge screen.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if ($user && method_exists($user, 'hasTwoFactor') && $user->hasTwoFactor()
            && ! $request->session()->get('2fa_passed', false)) {
            return redirect()->route('2fa.challenge');
        }

        return $next($request);
    }
}
