I am implementing Google log in for the first time as described here and here.
I am using HTML with Javascript.
The problem that needs solving is as follows: How can I, after the initial login, on a different page (say a landing page, or portal that the user sees after logging in), check if the user is logged in? Is there a service I can call to check the user’s login in status with my app key or something similar? I assume I would have to include the google API on each page.
Login Page Code:
Script In Head (Code from Google’s tutorial listed above):
<head> .... <script src="https://apis.google.com/js/platform.js" async defer></script> <script> function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log('ID: ' + profile.getId()); console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); alert(profile.getName()); } function logout() { alert('logging out'); var auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { console.log('User signed out.'); }); } ... </head>
Code In Body (1st line from Google’s tutorial listed above, 2nd line to trigger logout test)
<body> ... <div class="g-signin2" data-onsuccess="onSignIn"></div> <div onmousedown="logout()">Logout</div> ... </body>
Is there some way I can include the google API on another page, and then call some check login status function? Or another way to concretely tell if the user is logged in or out?
Advertisement
Answer
You can stringify a custom userEntity object and store it in sessionStorage where you can check it anytime you load a new page. I have not tested the following but it should work (doing something similar with WebAPI tokens in the same way)
function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log('ID: ' + profile.getId()); console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); var myUserEntity = {}; myUserEntity.Id = profile.getId(); myUserEntity.Name = profile.getName(); //Store the entity object in sessionStorage where it will be accessible from all pages of your site. sessionStorage.setItem('myUserEntity',JSON.stringify(myUserEntity)); alert(profile.getName()); } function checkIfLoggedIn() { if(sessionStorage.getItem('myUserEntity') == null){ //Redirect to login page, no user entity available in sessionStorage window.location.href='Login.html'; } else { //User already logged in var userEntity = {}; userEntity = JSON.parse(sessionStorage.getItem('myUserEntity')); ... DoWhatever(); } } function logout() { //Don't forget to clear sessionStorage when user logs out sessionStorage.clear(); }
Of course, you can have some internal checks if the sessionStorage object is tampered with. This approach should work with modern browsers like Chrome and Firefox.