title: Preventing multiple logins to a website in Play framework
body: <p>I'm working on the design of a program using Play framework for Java. It's a website that requires users to log in and it needs to prevent a user from logging into an account that is already logged in. </p>
  
  <p>When a user logs in, the username is stored in the Cache (using memcached). When the user logs out, the username is disacarded from the Cache. If a login attempt is made for a username that exists in the Cache, the login attempt is rejected. </p>
  
  <p>For example, a user logs in with the username "joe". Someone from another computer attempts to log in with the username "joe" and it gets rejected because "joe" is already logged in.</p>
  
  <p>Simple enough, except when a user closes their browser tab, then they are locked out because their username still exists in the Cache.</p>
  
  <p>So, using javascript, I've captured the window.onbeforeunload event to redirect to a route that runs a Java method that clears the Cache. The problem is that window.onbeforeunload is fired when the user clicks a link or reloads the page. So, if the user reloads the page, they are logged out, or if they click on a link within the website, they are logged out. Is there a way to prevent that from happening?</p>
  
  <p><strong>Edit</strong>:
  I am using Security.Authenticated to ensure people can't access the website unless they have a session in their cookie. I have a BaseController that extends Controller and all of my controllers extend BaseController (except the one that handles the login page), and the BaseController is annotated with:</p>
  
  <pre><code>@Security.Authenticated(Secured.class)
  </code></pre>
  
  <p>Secured ensures that when somebody tries to access the website, if they don't have a session, they are redirected to the login page. Once they log in, a cookie is created with the session and Secured will allow them to access the page.</p>