forked from doubledutch/go-force
-
Notifications
You must be signed in to change notification settings - Fork 1
/
oauth.go
206 lines (169 loc) · 5.08 KB
/
oauth.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package force
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
const (
grantType = "password"
loginUri = "https://login.salesforce.com/services/oauth2/token"
testLoginUri = "https://test.salesforce.com/services/oauth2/token"
invalidSessionErrorCode = "INVALID_SESSION_ID"
)
type ForceOauth struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
InstanceUrl string `json:"instance_url"`
Id string `json:"id"`
IssuedAt string `json:"issued_at"`
Signature string `json:"signature"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
clientId string
clientSecret string
refreshToken string
userName string
password string
securityToken string
environment string
}
func (oauth *ForceOauth) Validate() error {
if oauth == nil || len(oauth.InstanceUrl) == 0 || len(oauth.AccessToken) == 0 {
return fmt.Errorf("Invalid Force Oauth Object: %#v", oauth)
}
return nil
}
func (oauth *ForceOauth) Expired(apiErrors ApiErrors) bool {
for _, err := range apiErrors {
if err.ErrorCode == invalidSessionErrorCode {
return true
}
}
return false
}
func (oauth *ForceOauth) RefreshAccessToken() error {
log.Println("Refreshing access token")
payload := url.Values{
"grant_type": {"refresh_token"},
"client_id": {oauth.clientId},
"client_secret": {oauth.clientSecret},
"refresh_token": {oauth.RefreshToken},
}
respBytes, err := oauth.AuthenticatePayload(payload)
if nil == err {
log.Println("Refreshed access token")
var updatedOAuth ForceOauth
if err := json.Unmarshal(respBytes, &updatedOAuth); err != nil {
return fmt.Errorf("Unable to unmarshal authentication response: %v (%s)", err, string(respBytes))
}
oauth.AccessToken = updatedOAuth.AccessToken
oauth.IssuedAt = updatedOAuth.IssuedAt
} else {
log.Println("Refreshing access token: " + err.Error())
}
return err
}
func (oauth *ForceOauth) Authenticate() error {
payload := url.Values{
"grant_type": {grantType},
"client_id": {oauth.clientId},
"client_secret": {oauth.clientSecret},
"username": {oauth.userName},
"password": {fmt.Sprintf("%v%v", oauth.password, oauth.securityToken)},
}
// Build Uri
uri := loginUri
if oauth.environment == "sandbox" {
uri = testLoginUri
}
// Build Body
body := strings.NewReader(payload.Encode())
// Build Request
req, err := http.NewRequest("POST", uri, body)
if err != nil {
return fmt.Errorf("Error creating authenitcation request: %v", err)
}
// Add Headers
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", responseType)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("Error sending authentication request: %v", err)
}
defer resp.Body.Close()
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Error reading authentication response bytes: %v", err)
}
// Attempt to parse response as a force.com api error
apiError := &ApiError{}
if err := json.Unmarshal(respBytes, apiError); err == nil {
// Check if api error is valid
if apiError.Validate() {
return apiError
}
}
if err := json.Unmarshal(respBytes, oauth); err != nil {
return fmt.Errorf("Unable to unmarshal authentication response: %v", err)
}
return nil
}
func (oauth *ForceOauth) AuthenticateCode(code string, redirectURI string) error {
payload := url.Values{
"grant_type": {"authorization_code"},
"client_id": {oauth.clientId},
"client_secret": {oauth.clientSecret},
"code": {code},
"redirect_uri": {redirectURI},
}
respBytes, err := oauth.AuthenticatePayload(payload)
if nil == err {
if err := json.Unmarshal(respBytes, oauth); err != nil {
return fmt.Errorf("Unable to unmarshal authentication response: %v", err)
}
}
return nil
}
func (oauth *ForceOauth) AuthenticatePayload(payload url.Values) ([]byte, error) {
// Build Uri
uri := loginUri
if oauth.environment == "sandbox" {
uri = testLoginUri
}
// Build Body
body := strings.NewReader(payload.Encode())
// Build Request
req, err := http.NewRequest("POST", uri, body)
if err != nil {
return nil, fmt.Errorf("Error creating authenitcation request: %v", err)
}
log.Printf("body: %v, %+v", uri, payload.Encode())
// Add Headers
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", responseType)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("Error sending authentication request: %v", err)
}
defer resp.Body.Close()
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error reading authentication response bytes: %v", err)
}
log.Printf("respBytes: %+v", string(respBytes))
// Attempt to parse response as a force.com api error
apiError := &ApiError{}
if err := json.Unmarshal(respBytes, apiError); err == nil {
// Check if api error is valid
if apiError.Validate() {
return nil, apiError
}
}
return respBytes, nil
}