Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GitHub detect signing in/out?

When opening several tabs/windows on the GitHub website, if you happen to sign in/out on one of these, you get a notification on all others invinting you to reload to refresh your session state.

How is that done?

All I know so far is the pages HTML code contains some hidden SVG graphic + spans which are activated through JavaScript :

<div class="js-stale-session-flash stale-session-flash flash flash-warn flash-banner d-none">
  <svg aria-hidden="true" class="octicon octicon-alert" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path d="M8.865 1.52c-.18-.31-.51-.5-.87-.5s-.69.19-.87.5L.275 13.5c-.18.31-.18.69 0 1 .19.31.52.5.87.5h13.7c.36 0 .69-.19.86-.5.17-.31.18-.69.01-1L8.865 1.52zM8.995 13h-2v-2h2v2zm0-3h-2V6h2v4z"></path></svg>
  <span class="signed-in-tab-flash">You signed in with another tab or window. <a href="">Reload</a> to refresh your session.</span>
  <span class="signed-out-tab-flash">You signed out in another tab or window. <a href="">Reload</a> to refresh your session.</span>
</div>
like image 221
Bernard Rosset Avatar asked Oct 26 '25 12:10

Bernard Rosset


1 Answers

This is done with storageEvents.

Basically, the Storage interface emits storage event on global objects which it affects.

Essentially, on each generated GitHub page load, GitHub sets the meta tag with the name 'user-login'. The value will be the currently logged in user.

For example, if I view the source code for a page that I have loaded in GitHub, the source code contains this line:

<meta name="user-login" content="timgws">

Then, each time the page loads, the content's value is retrieved, and stored inside LocalStorage. Roughly, with jQuery the code is:

localStorage.setItem("logged-in", $("meta[name='user-login']").attr("content"));

Finally, the last magic trick is to listen for the storage event, pick up if the username has changed and then switch the visibility of the flash class.

var currentUser = localStorage.getItem("logged-in");
window.addEventListener("storage", function (event) {
    if (event.storageArea === localStorage && event.key === "logged-in"
        && event.newValue !== currentUser) {

        $('.flash').removeClass('d-none');
    }
});

You might want to add some code to differentiate between users logging in and out (which should be pretty easy by comparing the value of currentUser)

like image 138
Tim Groeneveld Avatar answered Oct 29 '25 00:10

Tim Groeneveld