1
// Copyright 2015 Canonical Ltd.
2
// Licensed under the LGPLv3, see LICENCE file for details.
11
"github.com/juju/httprequest"
13
"gopkg.in/macaroon-bakery.v1/httpbakery"
15
"github.com/juju/idmclient/params"
18
// Note: tests for this code are in the server implementation.
21
Production = "https://api.jujucharms.com/identity"
22
Staging = "https://api.staging.jujucharms.com/identity"
25
// Client represents the client of an identity server.
30
// NewParams holds the parameters for creating a new client.
31
type NewParams struct {
33
Client *httpbakery.Client
35
// AuthUsername holds the username for admin login.
38
// AuthPassword holds the password for admin login.
42
// New returns a new client.
43
func New(p NewParams) *Client {
45
c.Client.BaseURL = p.BaseURL
46
if p.AuthUsername != "" {
47
c.Client.Doer = &basicAuthClient{
50
password: p.AuthPassword,
53
c.Client.Doer = p.Client
55
c.Client.UnmarshalError = httprequest.ErrorUnmarshaler(new(params.Error))
59
// basicAuthClient wraps a bakery.Client, adding a basic auth
60
// header to every request.
61
type basicAuthClient struct {
62
client *httpbakery.Client
67
func (c *basicAuthClient) Do(req *http.Request) (*http.Response, error) {
68
req.SetBasicAuth(c.user, c.password)
69
return c.client.Do(req)
72
func (c *basicAuthClient) DoWithBody(req *http.Request, r io.ReadSeeker) (*http.Response, error) {
73
req.SetBasicAuth(c.user, c.password)
74
return c.client.DoWithBody(req, r)
77
// LoginMethods returns information about the available login methods
78
// for the given URL, which is expected to be a URL as passed to
79
// a VisitWebPage function during the macaroon bakery discharge process.
80
func LoginMethods(client *http.Client, u *url.URL) (*params.LoginMethods, error) {
81
req, err := http.NewRequest("GET", u.String(), nil)
83
return nil, errgo.Notef(err, "cannot create request")
85
req.Header.Set("Accept", "application/json")
86
resp, err := client.Do(req)
88
return nil, errgo.Notef(err, "cannot do request")
90
defer resp.Body.Close()
91
if resp.StatusCode != http.StatusOK {
92
var herr httpbakery.Error
93
if err := httprequest.UnmarshalJSONResponse(resp, &herr); err != nil {
94
return nil, errgo.Notef(err, "cannot unmarshal error")
98
var lm params.LoginMethods
99
if err := httprequest.UnmarshalJSONResponse(resp, &lm); err != nil {
100
return nil, errgo.Notef(err, "cannot unmarshal login methods")
105
//go:generate httprequest-generate-client $IDM_SERVER_REPO/internal/v1 apiHandler client