How to Configure the Auth.go file for the Google Glass Mirror API Using Golang

Go (golang) logo

For those who have asked how my auth.go file is configured for the Go Quick Start project, I’ve posted my auth.go file below.

// Copyright (C) 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package qslquery

import (
	"fmt"
	"net/http"
	"strings"

	"code.google.com/p/goauth2/oauth"
	"code.google.com/p/google-api-go-client/mirror/v1"
	"code.google.com/p/google-api-go-client/oauth2/v2"

	"appengine"
	"appengine/urlfetch"
)

const revokeEndpointFmt = "https://accounts.google.com/o/oauth2/revoke?token=%s"

// Because App Engine owns main and starts the HTTP service,
// we do our setup during initialization.
func init() {
	http.HandleFunc("/auth", authHandler)
	http.HandleFunc("/oauth2callback", errorAdapter(oauth2callbackHandler))
	http.HandleFunc("/signout", errorAdapter(signoutHandler))
}

// auth is the HTTP handler that redirects the user to authenticate
// with OAuth.
func authHandler(w http.ResponseWriter, r *http.Request) {
	url := config(r.Host).AuthCodeURL(r.URL.RawQuery)
	http.Redirect(w, r, url, http.StatusFound)
}

// oauth2callback is the handler to which Google's OAuth service redirects the
// user after they have granted the appropriate permissions.
func oauth2callbackHandler(w http.ResponseWriter, r *http.Request) error {
	c := appengine.NewContext(r)

	// Create an oauth transport with a urlfetch.Transport embedded inside.
	t := &oauth.Transport{
		Config:    config(r.Host),
		Transport: &urlfetch.Transport{Context: c},
	}

	// Exchange the code for access and refresh tokens.
	tok, err := t.Exchange(r.FormValue("code"))
	if err != nil {
		return fmt.Errorf("Exchange(%q): %v", r.FormValue("code"), err)
	}

	o, err := oauth2.New(t.Client())
	if err != nil {
		return fmt.Errorf("Unable to instantiate UserInfo service: %s", err)
	}
	u, err := o.Userinfo.Get().Do()
	if err != nil {
		return fmt.Errorf("Unable to retrieve user ID: %s", err)
	}

	userId := fmt.Sprintf("%s_%s", strings.Split(clientId, ".")[0], u.Id)

	if err = storeUserID(w, r, userId); err != nil {
		return fmt.Errorf("Unable to store user ID: %s", err)
	}
	storeCredential(c, userId, tok)
	bootstrapUser(r, t.Client(), userId)
	http.Redirect(w, r, "/", http.StatusFound)
	return nil
}

// bootstrapUser sets up sharing contact and notification for a new user.
func bootstrapUser(r *http.Request, client *http.Client, userId string) {
	c := appengine.NewContext(r)
	m, _ := mirror.New(client)

	if strings.HasPrefix(r.Host, "https://") {
		s := &mirror.Subscription{
			Collection:  "timeline",
			UserToken:   userId,
			CallbackUrl: fullURL(r.Host, "/notify"),
		}
		m.Subscriptions.Insert(s).Do()

		c := &mirror.Contact{
			Id:          "APP_Name",
			DisplayName: "App Name",
			ImageUrls:   []string{fullURL(r.Host, "/static/images/gopher.png")},
		}
		m.Contacts.Insert(c).Do()
	} else {
		c.Infof("Post auth tasks are not supported on staging.")
	}

	t := &mirror.TimelineItem{
		Text:         "Welcome to QSL Query!",
		Notification: &mirror.NotificationConfig{Level: "DEFAULT"},
	}

	m.Timeline.Insert(t).Do()
	insertCallsignSearchItem(r, m)
}

// signout Revokes access for the user and removes the associated credentials from the datastore.
func signoutHandler(w http.ResponseWriter, r *http.Request) error {
	if r.Method != "POST" {
		return nil
	}
	c := appengine.NewContext(r)
	userId, err := userID(r)
	if err != nil {
		return fmt.Errorf("Unable to retrieve user ID: %s", err)
	}
	if userId == "" {
		http.Redirect(w, r, "/auth", http.StatusFound)
		return nil
	}
	t := authTransport(c, userId)
	if t == nil {
		http.Redirect(w, r, "/auth", http.StatusFound)
		return nil
	}
	client := urlfetch.Client(c)
	_, err = client.Get(fmt.Sprintf(revokeEndpointFmt, t.Token.RefreshToken))
	if err != nil {
		return fmt.Errorf("Unable to revoke token: %s", err)
	}
	storeUserID(w, r, "")
	deleteCredential(c, userId)

	http.Redirect(w, r, "/", http.StatusFound)
	return nil
}

My Google Glass App has been Featured in QST Magazine!

QSL Query featured in QST 12/2013

QSL Query, the Glassware I wrote for amateur radio operators using Google’s Go programming language, has been featured in the Eclectic Technology column of the December 2013 issue of QST!  QST is the monthly journal of the Amateur Radio Relay League.  It is free to all ARRL members and can also be found at most major bookstores and supermarkets.

QSL Query featured in QST 12/2013

How to Delete All Google Glass Timeline Items

Google Glass logo

For my QSL Query for Google Glass application, I needed a function that deletes all timeline items at once, rather than deleting them one at a time. The following code is written in Go, and is inserted into main.go if you are using Google’s Go Quick Start Project as your Glassware template.

// deleteAllTimelineItems deletes all timeline items.
func deleteAllTimelineItems(r *http.Request, svc *mirror.Service) string {
  timelineItems, err := svc.Timeline.List().Do()
  if err != nil {
    return fmt.Sprintf("An error occurred: %vn", err)
  }
  for _, t := range timelineItems.Items {
    err := svc.Timeline.Delete(t.Id).Do()
    if err != nil {
      return fmt.Sprintf("An error occurred: %vn", err)
    }
  }
  return "All timeline items have been deleted."
}

This function can be called from within other code blocks, or a button can be added to index.html:

<form action="/" method="post">
  <input type="hidden" name="operation" value="deleteAllTimelineItems" />
  <button class="btn" type="submit">Delete All Timeline Items</button>
  <input type="hidden" name="contentType" value="image/png" />
</form>

If it is going to be called with this button, the name of the operation must be added to the operations variable in main.go – it’s the last line before the closing curly brace.

// Map of operations to functions.
var operations = map[string]func(*http.Request, *mirror.Service) string{
    "insertSubscription":       insertSubscription,
    "deleteSubscription":       deleteSubscription,
    "insertItem":               insertItem,
    "insertItemWithAction":     insertItemWithAction,
    "insertItemAllUsers":       insertItemAllUsers,
    "insertContact":            insertContact,
    "deleteContact":            deleteContact,
    "deleteTimelineItem":       deleteTimelineItem,
    "deleteAllTimelineItems":   deleteAllTimelineItems,
}