2014-06-17 09:53:08 -04:00
|
|
|
// +build appengine
|
|
|
|
|
|
|
|
package google
|
|
|
|
|
|
|
|
import (
|
2014-09-02 17:06:51 -04:00
|
|
|
"net/http"
|
|
|
|
|
2014-06-17 09:53:08 -04:00
|
|
|
"github.com/golang/oauth2"
|
2014-07-09 01:27:34 -04:00
|
|
|
|
|
|
|
"appengine"
|
2014-07-11 13:57:28 -04:00
|
|
|
"appengine/urlfetch"
|
2014-06-17 09:53:08 -04:00
|
|
|
)
|
|
|
|
|
2014-06-22 17:39:35 -04:00
|
|
|
// AppEngineConfig represents a configuration for an
|
|
|
|
// App Engine application's Google service account.
|
2014-06-17 09:53:08 -04:00
|
|
|
type AppEngineConfig struct {
|
2014-08-31 18:36:50 -04:00
|
|
|
// Transport is the transport to be used
|
|
|
|
// to construct new oauth2.Transport instances from
|
|
|
|
// this configuration.
|
2014-07-14 13:59:30 -04:00
|
|
|
Transport *urlfetch.Transport
|
2014-08-31 18:13:59 -04:00
|
|
|
|
|
|
|
context appengine.Context
|
|
|
|
scopes []string
|
2014-06-17 09:53:08 -04:00
|
|
|
}
|
|
|
|
|
2014-06-22 17:39:35 -04:00
|
|
|
// NewAppEngineConfig creates a new AppEngineConfig for the
|
|
|
|
// provided auth scopes.
|
2014-06-17 09:53:08 -04:00
|
|
|
func NewAppEngineConfig(context appengine.Context, scopes []string) *AppEngineConfig {
|
2014-08-31 18:13:59 -04:00
|
|
|
return &AppEngineConfig{
|
|
|
|
context: context,
|
|
|
|
scopes: scopes,
|
|
|
|
}
|
2014-06-17 09:53:08 -04:00
|
|
|
}
|
|
|
|
|
2014-06-22 17:39:35 -04:00
|
|
|
// NewTransport returns a transport that authorizes
|
|
|
|
// the requests with the application's service account.
|
2014-08-14 01:22:35 -04:00
|
|
|
func (c *AppEngineConfig) NewTransport() *oauth2.Transport {
|
2014-09-02 17:06:51 -04:00
|
|
|
return oauth2.NewTransport(c.transport(), c, nil)
|
2014-06-17 09:53:08 -04:00
|
|
|
}
|
|
|
|
|
2014-06-22 17:39:35 -04:00
|
|
|
// FetchToken fetches a new access token for the provided scopes.
|
2014-06-17 09:53:08 -04:00
|
|
|
func (c *AppEngineConfig) FetchToken(existing *oauth2.Token) (*oauth2.Token, error) {
|
2014-08-05 15:25:29 -04:00
|
|
|
token, expiry, err := appengine.AccessToken(c.context, c.scopes...)
|
2014-06-17 09:53:08 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &oauth2.Token{
|
|
|
|
AccessToken: token,
|
|
|
|
Expiry: expiry,
|
|
|
|
}, nil
|
|
|
|
}
|
2014-09-02 17:06:51 -04:00
|
|
|
|
|
|
|
func (c *AppEngineConfig) transport() http.RoundTripper {
|
|
|
|
if c.Transport != nil {
|
|
|
|
return c.Transport
|
|
|
|
}
|
|
|
|
return &urlfetch.Transport{Context: c.context}
|
|
|
|
}
|