<?php

namespace App\Http\Middleware;

use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return '/admin/login.php?redir=' . urlencode($_SERVER['REQUEST_URI']);
        }
    }

    /**
     * Determine if the user is logged in to any of the given guards.
     *
     * @param  array  $guards
     * @return void
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    protected function authenticate($request, array $guards)
    {
        if (empty($_SESSION['adminId'])) {
            // If 2FA is pending and not expired, redirect to the verify page instead of login
            if (!empty($_SESSION['admin_2fa_pending_id'])
                && !empty($_SESSION['admin_2fa_pending_at'])
                && (time() - $_SESSION['admin_2fa_pending_at']) <= 300
            ) {
                throw new AuthenticationException(
                    'Two-factor authentication required.',
                    $guards,
                    '/admin/2fa_verify.php?redir=' . urlencode($_SERVER['REQUEST_URI'])
                );
            }

            throw new AuthenticationException('Unauthenticated.', $guards, $this->redirectTo($request));
        }
    }
}
