Joomla丢失自定义会话变量和cookie?

I created a login page outside of Joomla to use with certain pages that require a login/password protection. It checks to see if the user is already logged in, and if not saves the page they're on to a session variable ($redirected_from) and redirects to the login page. Then when they're logged in it saves their logged in state to another session variable ($username), so if they browse around and come back to one of the pages that requires a login, it doesn't redirect them to the login page again.

This is all working fine to a point. You can use the menu on the left for that section of the site and go between pages and back, and it remembers the logged in state. The problem is if you click on the Home link and go to the homepage, then go back to that section of the site, it forgets that you've logged in and you're redirected to the login page again.

I tried creating cookies to save the values too, figuring that Joomla was doing something to delete/reset the session variables when you visited "Home" and I have it echo the value onto the page. It saves the logged in state until you visit "Home" and then it's gone (echo's out nothing).

Is there something that Joomla does on the homepage that's going to reset any custom variables (session or cookie), and if so, is there any kind of work around for this?

Here's how the variables are being saved on the login page:

if ($username == $preset_username && $password == $preset_password) {
        $session =& JFactory::getSession();
        $session->set('user', $username);     

        if(!isset($_COOKIE['user']) || $_COOKIE['user'] == '') {
            setcookie('user', $username);
            JRequest::setVar('user', $username, 'COOKIE');
            $_COOKIE['user'] = $username;
        }
}

And here's how every page is checking for the user (using an include):

if (!($session->get('user'))) {
        $session->set('user', "");
}

$user_cookie = $_COOKIE['user'];

if (($session->get('user') == "" || $session->get('user') == null) && (!isset($_COOKIE['user']) || $_COOKIE['user'] == '')) {

    ...check against list of pages requiring login and if match saves page and redirects (this part works)...

}