-
Notifications
You must be signed in to change notification settings - Fork 29
/
client.go
76 lines (67 loc) · 1.76 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package idptest
import (
"context"
"crypto/sha256"
"encoding/base64"
"net/http"
"net/http/httptest"
errgo "gopkg.in/errgo.v1"
"github.com/canonical/candid/idp"
"github.com/canonical/candid/idp/idputil"
"github.com/canonical/candid/idp/idputil/secret"
)
// A Client allows tests to simulate sending HTTP requests to an IDP.
type Client struct {
idp idp.IdentityProvider
codec *secret.Codec
loginState *http.Cookie
state string
}
// NewClient create a new client for the given IDP.
func NewClient(idp idp.IdentityProvider, codec *secret.Codec) *Client {
return &Client{
idp: idp,
codec: codec,
}
}
// SetLoginStatus sets a login status that will be added to every
// request.
func (c *Client) SetLoginState(state idputil.LoginState) {
value, err := c.codec.Encode(state)
if err != nil {
panic(err)
}
c.loginState = &http.Cookie{
Name: idputil.LoginCookieName,
Value: value,
}
rawValue, err := base64.URLEncoding.DecodeString(value)
if err != nil {
panic(err)
}
hash := sha256.Sum256(rawValue)
c.state = base64.RawURLEncoding.EncodeToString(hash[:])
}
// Do simulates a round trip to the idp handler.
func (c *Client) Do(req *http.Request) (*http.Response, error) {
if c.loginState != nil {
v := req.URL.Query()
v.Set("state", c.state)
req.URL.RawQuery = v.Encode()
req.AddCookie(c.loginState)
}
req.ParseForm()
w := httptest.NewRecorder()
c.idp.Handle(context.Background(), w, req)
return w.Result(), nil
}
// Get simulates a get request on the idp handler.
func (c *Client) Get(url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, errgo.Mask(err)
}
return c.Do(req)
}