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"
14
"github.com/juju/juju/jujuclient"
17
// APIContext holds the context required for making connections to
19
type APIContext struct {
21
BakeryClient *httpbakery.Client
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.
28
// If ctxt is nil, no command-line authorization
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(),
38
return nil, errors.Trace(err)
40
client := httpbakery.NewClient()
43
filler := &form.IOFiller{
47
client.VisitWebPage = ussologin.VisitWebPage(
51
jujuclient.NewTokenStore(),
54
client.VisitWebPage = httpbakery.OpenWebBrowser
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 != "" {
69
return cookiejar.DefaultCookieFile()
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")