Authenticating Users

This page shows you how to authenticate users by using the Users API, which works with Google user accounts.

This page is part of a multi-page tutorial. To start from the beginning and see instructions for setting up, go to Creating a Guestbook.

Using the Users API

Walk through the application code you cloned from GitHub.

  1. In this code sample, if the user is already signed in to your application, getCurrentUser() returns the User object for the user. Otherwise, it returns null:

    # Looks for current Google account session
    $user = UserService::getCurrentUser();
  2. If the user is signed in, a personalized message displays, using the nickname associated with the user's account:

    if ($user) {
        echo 'Hello, ' . htmlspecialchars($user->getNickname());
  3. If the user is not signed in, the browser redirects to the Google account sign-in screen. The redirect includes the URL to this page (through the inclusion of $_SERVER['REQUEST_URI']) so the Google account sign-in mechanism will send the user back here after the user has signed in or registered for a new account:

    else {
        header('Location: ' . UserService::createLoginURL($_SERVER['REQUEST_URI']));