forked from etcinit/gonduit
-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.go
85 lines (72 loc) · 2.07 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
77
78
79
80
81
82
83
84
85
// Package gonduit provides a client for Phabricator's Conduit API.
package gonduit
import (
"crypto/sha1"
"fmt"
"io"
"strconv"
"time"
"github.com/thought-machine/gonduit/core"
"github.com/thought-machine/gonduit/entities"
"github.com/thought-machine/gonduit/requests"
"github.com/thought-machine/gonduit/responses"
)
// Conn is a connection to the conduit API.
type Conn struct {
host string
user string
capabilities *responses.ConduitCapabilitiesResponse
Session *entities.Session
dialer *Dialer
options *core.ClientOptions
}
func getAuthToken() string {
return strconv.FormatInt(time.Now().UTC().Unix(), 10)
}
func getAuthSignature(authToken, cert string) string {
h := sha1.New()
io.WriteString(h, authToken)
io.WriteString(h, cert)
return fmt.Sprintf("%x", h.Sum(nil))
}
// Connect calls conduit.connect to open an authenticated session for future
// requests.
func (c *Conn) Connect() error {
authToken := getAuthToken()
authSig := getAuthSignature(authToken, c.options.Cert)
var resp responses.ConduitConnectResponse
if err := c.Call("conduit.connect", &requests.ConduitConnectRequest{
Client: c.dialer.ClientName,
ClientVersion: c.dialer.ClientVersion,
ClientDescription: c.dialer.ClientDescription,
Host: c.host,
User: c.options.CertUser,
AuthToken: authToken,
AuthSignature: authSig,
}, &resp); err != nil {
return err
}
c.Session = &entities.Session{
SessionKey: resp.SessionKey,
ConnectionID: resp.ConnectionID,
}
c.options.SessionKey = resp.SessionKey
return nil
}
// Call allows you to make a raw conduit method call. Params will be marshalled
// as JSON and the result JSON will be unmarshalled into the result interface{}.
//
// This is primarily useful for calling conduit endpoints that aren't
// specifically supported by other methods in this package.
func (c *Conn) Call(
method string,
params interface{},
result interface{},
) error {
return core.PerformCall(
core.GetEndpointURI(c.host, method),
params,
&result,
c.options,
)
}