github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/cmd/modelcmd/apicontext.go (about)

     1  package modelcmd
     2  
     3  import (
     4  	"net/http"
     5  	"os"
     6  
     7  	"github.com/juju/errors"
     8  	"github.com/juju/idmclient/ussologin"
     9  	"github.com/juju/persistent-cookiejar"
    10  	"gopkg.in/juju/environschema.v1/form"
    11  	"gopkg.in/macaroon-bakery.v1/httpbakery"
    12  
    13  	"github.com/juju/cmd"
    14  	"github.com/juju/juju/jujuclient"
    15  )
    16  
    17  // APIContext holds the context required for making connections to
    18  // APIs used by juju.
    19  type APIContext struct {
    20  	Jar          *cookiejar.Jar
    21  	BakeryClient *httpbakery.Client
    22  }
    23  
    24  // NewAPIContext returns an API context that will use the given
    25  // context for user interactions when authorizing.
    26  // The returned API context must be closed after use.
    27  //
    28  // If ctxt is nil, no command-line authorization
    29  // will be supported.
    30  //
    31  // This function is provided for use by commands that cannot use
    32  // JujuCommandBase. Most clients should use that instead.
    33  func NewAPIContext(ctxt *cmd.Context) (*APIContext, error) {
    34  	jar, err := cookiejar.New(&cookiejar.Options{
    35  		Filename: cookieFile(),
    36  	})
    37  	if err != nil {
    38  		return nil, errors.Trace(err)
    39  	}
    40  	client := httpbakery.NewClient()
    41  	client.Jar = jar
    42  	if ctxt != nil {
    43  		filler := &form.IOFiller{
    44  			In:  ctxt.Stdin,
    45  			Out: ctxt.Stdout,
    46  		}
    47  		client.VisitWebPage = ussologin.VisitWebPage(
    48  			"juju",
    49  			&http.Client{},
    50  			filler,
    51  			jujuclient.NewTokenStore(),
    52  		)
    53  	} else {
    54  		client.VisitWebPage = httpbakery.OpenWebBrowser
    55  	}
    56  	return &APIContext{
    57  		Jar:          jar,
    58  		BakeryClient: client,
    59  	}, nil
    60  }
    61  
    62  // cookieFile returns the path to the cookie used to store authorization
    63  // macaroons. The returned value can be overridden by setting the
    64  // JUJU_COOKIEFILE or GO_COOKIEFILE environment variables.
    65  func cookieFile() string {
    66  	if file := os.Getenv("JUJU_COOKIEFILE"); file != "" {
    67  		return file
    68  	}
    69  	return cookiejar.DefaultCookieFile()
    70  }
    71  
    72  // Close closes the API context, saving any cookies to the
    73  // persistent cookie jar.
    74  func (ctxt *APIContext) Close() error {
    75  	if err := ctxt.Jar.Save(); err != nil {
    76  		return errors.Annotatef(err, "cannot save cookie jar")
    77  	}
    78  	return nil
    79  }