forked from andrew-waters/gomo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client_authenticate.go
60 lines (46 loc) · 1.16 KB
/
client_authenticate.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
package gomo
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
var errUnableToAuthenticate = errors.New("Unable to authenticate")
// AuthResponse contains the response from the auth call
type authResponse struct {
Expires int `json:"expires"`
ExpiresIn int `json:"expires_in"`
Identifier string `json:"identifier"`
TokenType string `json:"token_type"`
AccessToken string `json:"access_token"`
}
func (c Client) authURL() string {
return fmt.Sprintf("%s/oauth/access_token", c.Endpoint)
}
// Authenticate makes a call to get the access token for the client's credentials
func (c *Client) Authenticate() error {
var err error
r, err := http.PostForm(c.authURL(), c.credentials.authFormValues())
if err != nil {
return err
}
if r.StatusCode != 200 {
return errUnableToAuthenticate
}
return c.extractAccessTokenFromResponse(r)
}
func (c *Client) extractAccessTokenFromResponse(r *http.Response) error {
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
ar := authResponse{}
err = json.Unmarshal(b, &ar)
if err != nil {
return err
}
c.AccessToken = ar.AccessToken
return nil
}