Google Login with Javascript

Soldato
Joined
28 Apr 2011
Posts
15,026
Location
Barnet, London
I have a little website I use with work, which I coded a few years back mainly with PHP, but now Google have changed how they auth logins and it's not up to scratch. I've done some searching and found a webpage that's given me some Javascript to do it -

Code:
<head>
  <title>Google Auth Demo</title>
  <meta name="google-signin-client_id" content="409998107623-1tqdn73ud4iuusp7f6cehlaoro3einrp.apps.googleusercontent.com">
  <script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
  <h1>Welcome to the Demo</h1>
  <div class="g-signin2" data-onsuccess="onSignIn"></div>
  <div id="content"></div>
</body>

 
<script>
    function onSignIn(googleUser) {
      // get user profile information
      console.log(googleUser.getBasicProfile());

      $userEmail = googleUser.getBasicProfile().getEmail();

      var element = document.querySelector('#content')
      element.innerText = $userEmail
    }
  </script>

This all works fine and will display my email if and when I log in. The button changes to 'Signed In' and everything. Very neat.

I also have code for checking if someone is logged in -

Code:
<script>
    function isUserSignedIn() {
    gapi.load('auth2', function() {
        var isSignedIn = auth2.isSignedIn.get()
        console.log('is signed in? ', isSignedIn)
        })
    }
</script>

I realise I'm kind of asking someone to do my homework for me and really I should do some Javascript classes and learn what's going on, but I wonder if it's simple enough someone can explain two things for me?

1) How do I use the 'check someone is logged in' at the top of certain pages and redirect them to the login page if they aren't?

2) From within the webpage, how do I reference the $userEmail from the JS script? Ideally I need to do this globally across the site. I think I used $_SESSION in the PHP parts?

(Bonus points for how I only allow a certain domain. I did have the code for that, I think I lost it now!)

Thanks for any help! :)
 
A quick Google, one suggestion for sharing variables, which I guess works across the site, is using cookies -

Add a cookie with the javascript variable you want to access.

document.cookie="profile_viewer_uid=1";

Then acces it in php via

$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];

Will this work for me?
 
Back
Top Bottom