How to put WordPress website behind the credential for visitors?

I have put the following code in index.php file. It’s working fine as I was looking.

define('WP_USERNAME', 'PassW0rd$2017');

$error_msg = '';
$status = session_status();

if (PHP_SESSION_DISABLED === $status) {
    // That's why you cannot rely on sessions!
    // return;
}
if (PHP_SESSION_NONE === $status) {
    session_start();
}
if (isset($_SESSION['user_name']) && $_SESSION['user_name'] != '' && $_SESSION['user_name'] == WP_USERNAME) {
    // -------------
} else {

    if (isset($_POST['user_name']) && $_POST['user_name'] != '') {

        if ($_POST['user_name'] == WP_USERNAME) {

            $_SESSION['user_name'] = $_POST['user_name'];
            echo '<script>location.reload();</script>';

        } else {
            // $_SESSION[ 'user_name' ] = $_POST['user_name'];
            $error_msg = 'Invalid access token, Please try again.';
            // echo '<script>location.reload();</script>';
        }

    }

    echo '<div style="width: 350px;margin: 200px auto;padding: 10px;">';

    if ($error_msg) {
        echo '<p style="color:#940d0d">' . $error_msg . '</p>';
    }

    echo '<form method="POST" action="">';
    echo '<label>Please Access token before visiting this site.</label><br/>';
    echo '<input type="text" name="user_name" style="padding: 5px;width: 100%;margin-top: 10px;"><br/>';
    echo '<input type="submit" value="Submit to Access" style="padding: 8px 12px;margin-top: 10px;background: #0dc176;border: 0;color: #fff;cursor: pointer;font-size: 18px;">';
    echo '</form></div>';

    exit();

}