title: How to track if a user is logged in by session?
body: <p>I am trying to come up with a mechanism to check if a user has logged in, because certain pages on my web services are available only to registered users. I have my thoughts formalized in the following pseudocode.</p>
  
  <pre><code>void login(username, password)
  {
        if (username == db.user.username &amp;&amp; password == db.user.password)
            username.session = startSession(username);
        else
              response.redirect("/login");
  }
  
  String startSession(String username)
  {
       String sessionID = encoder.encode(randomBytes, username);  /* generates
  a random session id*/
       mysql.session_table.insert(username, sessionID);  /* save the session 
  id to session table */
  
       return sessionID;
  }
  
  String getSession(String username)
  {
       return username.session;
  }
  
  
  boolean isSessionNew(sessionID)
  {
       if (sessionID.age &gt; threshold)
             return false;
       else
             return true;
  }
  </code></pre>
  
  <p>Basically, when a user successfully logs in, I will generate a random session ID (startSession method) and save the sessionID, the username, along with the timestamp of its creation to the mysql database table "session". When the user visits a protected web page, the page will check if the user has a valid session ID (by session's age).</p>
  
  <p>My concern about this design is it may incur too much overhead in communicating with the database. Is there an easier and secure way to track user login session?</p>