Authenticating Users

This page shows 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.

Adding a context

Adding a new context is shown below:

c := appengine.NewContext(r)

The appengine.NewContext function returns a context.Context value associated with the current request. This is an opaque value used by many functions in the Go App Engine SDK to communicate with the App Engine service.

Getting the current user

If the user is already signed in to your application, user.Current returns a pointer to a user.User value. Otherwise, it returns nil:

if u := user.Current(c); u != nil {
        g.Author = u.String()
// We set the same parent key on every Greeting entity to ensure each Greeting
// is in the same entity group. Queries across the single entity group
// will be consistent. However, the write rate to a single entity group
// should be limited to ~1/second.
key := datastore.NewIncompleteKey(c, "Greeting", guestbookKey(c))
_, err := datastore.Put(c, key, &g)
if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
http.Redirect(w, r, "/", http.StatusFound)

Note that if the user is not signed in, an HTTP status code of 302 Found redirects the browser to the Google account sign-in screen.

If the datastore.Put function returns an error value, the http.Error helper displays an error.

Send feedback about...

App Engine standard environment for Go