<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

/**
 * Sign every visitor in as the reference admin.
 *
 * This copy of the site exists so people can read content that was not migrated
 * to WordPress. Its own login is a barrier to that and nothing else: the real
 * accounts came across from production, so nobody has a working password here,
 * and the passwords that are in the table are production hashes we should not
 * be inviting anyone to guess at.
 *
 * Access is controlled one layer up instead. The host sits behind the shared
 * BW auth gate, so the public never reaches this application at all — by the
 * time a request arrives here, someone has already been authenticated.
 *
 * Deliberately driven by MIRROR_AUTO_LOGIN_USER_ID rather than a hardcoded id:
 * with the variable unset this middleware does nothing, so the code is inert
 * anywhere it does not belong — including if it were ever restored onto a
 * production host.
 */
class AutoLoginMirrorAdmin
{
    public function handle(Request $request, Closure $next)
    {
        if (! Auth::check()) {
            $id = (int) env('MIRROR_AUTO_LOGIN_USER_ID', 0);

            if ($id > 0) {
                Auth::loginUsingId($id);
            }
        }

        return $next($request);
    }
}
