/
googleplus.go
361 lines (336 loc) · 11.9 KB
/
googleplus.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package oauth2_client
import (
"bytes"
"encoding/json"
"errors"
"github.com/pomack/jsonhelper.go/jsonhelper"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type GooglePlusUserInfoResult interface {
UserInfo
Id() string
MiddleName() string
Prefix() string
Suffix() string
Nickname() string
EmailAddresses() []string
Urls() []string
}
type googleplusName struct {
FamilyName string `json:"familyName,omitempty"`
Formatted string `json:"formatted,omitempty"`
GivenName string `json:"givenName,omitempty"`
HonorificPrefix string `json:"honorificPrefix,omitempty"`
HonorificSuffix string `json:"honorificSuffix,omitempty"`
MiddleName string `json:"middleName,omitempty"`
}
type googleplusUrl struct {
Primary string `json:"primary,omitempty"`
Type string `json:"type,omitempty"`
Value string `json:"value,omitempty"`
}
type googleplusUserInfoResult struct {
id string `json:"id,omitempty"`
displayName string `json:"displayName,omitempty"`
name googleplusName `json:"name,omitempty"`
nickname string `json:"nickname,omitempty"`
emails []string `json:"emails,omitempty"`
url string `json:"url,omitempty"`
urls []googleplusUrl `json:"link,omitempty"`
}
func (p *googleplusUserInfoResult) Guid() string { return p.id }
func (p *googleplusUserInfoResult) Username() string { return p.id }
func (p *googleplusUserInfoResult) GivenName() string { return p.name.GivenName }
func (p *googleplusUserInfoResult) FamilyName() string { return p.name.FamilyName }
func (p *googleplusUserInfoResult) DisplayName() string { return p.displayName }
func (p *googleplusUserInfoResult) Url() string { return p.url }
func (p *googleplusUserInfoResult) Id() string { return p.id }
func (p *googleplusUserInfoResult) MiddleName() string { return p.name.MiddleName }
func (p *googleplusUserInfoResult) Prefix() string { return p.name.HonorificPrefix }
func (p *googleplusUserInfoResult) Suffix() string { return p.name.HonorificSuffix }
func (p *googleplusUserInfoResult) Nickname() string { return p.nickname }
func (p *googleplusUserInfoResult) EmailAddresses() []string { return p.emails }
func (p *googleplusUserInfoResult) Urls() []string {
l := len(p.urls)
arr := make([]string, l)
for i, theurl := range p.urls {
arr[i] = theurl.Value
}
return arr
}
type googleplusClient struct {
client *http.Client
clientId string "client_id"
clientSecret string "client_secret"
redirectUri string "redirect_uri"
scope string "scope"
state string "state"
accessToken string "access_token"
expiresAt time.Time "expires_at"
tokenType string "token_type"
refreshToken string "refresh_token"
}
type googleplusAuthorizationCodeResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn float64 `json:"expires_in"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
}
func NewGooglePlusClient() *googleplusClient {
return &googleplusClient{client: new(http.Client)}
}
func (p *googleplusClient) Client() *http.Client {
return p.client
}
func (p *googleplusClient) ClientId() string { return p.clientId }
func (p *googleplusClient) ClientSecret() string { return p.clientSecret }
func (p *googleplusClient) RedirectUri() string { return p.redirectUri }
func (p *googleplusClient) AccessToken() string { return p.accessToken }
func (p *googleplusClient) ExpiresAt() time.Time { return p.expiresAt }
func (p *googleplusClient) ExpiresAtString() string {
if p.expiresAt.IsZero() {
return ""
}
return p.expiresAt.Format(GOOGLE_DATETIME_FORMAT)
}
func (p *googleplusClient) TokenType() string { return p.tokenType }
func (p *googleplusClient) RefreshToken() string { return p.refreshToken }
func (p *googleplusClient) ServiceId() string { return "plus.google.com" }
func (p *googleplusClient) Initialize(properties jsonhelper.JSONObject) {
if properties == nil || len(properties) <= 0 {
return
}
if v, ok := properties["googleplus.client.id"]; ok {
p.clientId = v.(string)
}
if v, ok := properties["googleplus.client.secret"]; ok {
p.clientSecret = v.(string)
}
if v, ok := properties["googleplus.client.redirect_uri"]; ok {
p.redirectUri = v.(string)
}
if v, ok := properties["googleplus.client.scope"]; ok {
p.scope = v.(string)
}
if v, ok := properties["googleplus.client.state"]; ok {
p.state = v.(string)
}
if v, ok := properties["googleplus.client.access_token"]; ok {
p.accessToken = v.(string)
}
if v, ok := properties["googleplus.client.expires_at"]; ok {
seconds, err := strconv.ParseInt(v.(string), 10, 64)
if err == nil {
p.expiresAt = time.Now().Add(time.Second * time.Duration(seconds)).UTC()
} else {
if expiresAt, err := time.Parse(GOOGLE_DATETIME_FORMAT, v.(string)); err == nil {
p.expiresAt = expiresAt
}
}
}
if v, ok := properties["googleplus.client.token_type"]; ok {
p.tokenType = v.(string)
}
if v, ok := properties["googleplus.client.refresh_token"]; ok {
p.refreshToken = v.(string)
}
}
func (p *googleplusClient) Scope() string {
return p.scope
}
func (p *googleplusClient) SetScope(scope string) {
p.scope = scope
}
func (p *googleplusClient) State() string {
return p.state
}
func (p *googleplusClient) SetState(state string) {
p.state = state
}
func (p *googleplusClient) GenerateAuthorizationCodeUri(code string) (string, url.Values) {
m := make(url.Values)
m.Add("grant_type", "authorization_code")
m.Add("client_id", p.clientId)
m.Add("client_secret", p.clientSecret)
m.Add("code", code)
if len(p.redirectUri) > 0 {
m.Add("redirect_uri", p.redirectUri)
}
if len(p.scope) > 0 {
m.Add("scope", p.scope)
}
if len(p.state) > 0 {
m.Add("state", p.state)
}
return _GOOGLEPLUS_AUTHORIZATION_CODE_URL, m
}
func (p *googleplusClient) HandleClientAccept(code string) error {
now := time.Now().UTC()
url, m := p.GenerateAuthorizationCodeUri(code)
req, err := http.NewRequest(_GOOGLEPLUS_AUTHORIZATION_CODE_METHOD, url, bytes.NewBufferString(m.Encode()))
if err != nil {
LogError("Unable to retrieve generate authorization code uri")
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r, _, err := MakeRequest(p, req)
//r, err := http.PostForm(url, m)
if err != nil {
LogError("Unable to retrieve generate authorization code uri")
return err
}
s := new(googleplusAuthorizationCodeResponse)
err2 := json.NewDecoder(r.Body).Decode(s)
LogDebugf("Loaded response %T -> %#v", s, s)
if err2 != nil {
LogError("Unable to decode the response from ", r.Body)
return err2
}
if len(s.AccessToken) > 0 && len(s.RefreshToken) > 0 {
p.expiresAt = time.Unix(now.Unix()+int64(s.ExpiresIn), 0).UTC()
p.accessToken = s.AccessToken
p.tokenType = s.TokenType
p.refreshToken = s.RefreshToken
}
return nil
}
func (p *googleplusClient) handleClientAcceptRequest(req *http.Request) error {
q := req.URL.Query()
error := q.Get("error")
if len(error) > 0 {
LogError("Received error in client accept request")
return errors.New(error)
}
code := q.Get("code")
if len(code) <= 0 {
LogError("Received no code in client accept request")
return errors.New("Expected URL parameter \"code\" in request but not found")
}
return p.HandleClientAccept(code)
}
func (p *googleplusClient) UpdateAccessToken() (string, error) {
now := time.Now().UTC()
if p.expiresAt.IsZero() || p.expiresAt.Unix() <= now.Unix() {
m := make(url.Values)
m.Add("client_id", p.clientId)
m.Add("client_secret", p.clientSecret)
m.Add("refresh_token", p.refreshToken)
m.Add("grant_type", "refresh_token")
req, err := http.NewRequest(_GOOGLEPLUS_REFRESH_TOKEN_METHOD, _GOOGLEPLUS_REFRESH_TOKEN_URL, bytes.NewBufferString(m.Encode()))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r, _, err := MakeRequest(p, req)
//r, err := http.PostForm(uri, m)
if err != nil {
return "", err
}
s := new(googleplusAuthorizationCodeResponse)
err2 := json.NewDecoder(r.Body).Decode(s)
LogDebugf("Loaded response %T -> %#v", s, s)
if err2 != nil {
return "", err2
}
if len(s.AccessToken) > 0 {
p.expiresAt = time.Unix(now.Unix()+int64(s.ExpiresIn), 0).UTC()
p.accessToken = s.AccessToken
if len(s.RefreshToken) > 0 {
p.refreshToken = s.RefreshToken
}
}
}
return p.accessToken, nil
}
func (p *googleplusClient) GenerateRequestTokenUrl(properties jsonhelper.JSONObject) string {
if properties == nil {
properties = jsonhelper.NewJSONObject()
}
m := make(url.Values)
m.Add("response_type", "code")
if v, ok := properties["client_id"]; ok && len(v.(string)) > 0 {
m.Add("client_id", v.(string))
} else {
m.Add("client_id", p.clientId)
}
if v, ok := properties["redirect_uri"]; ok {
if len(v.(string)) > 0 {
m.Add("redirect_uri", v.(string))
}
} else if len(p.redirectUri) > 0 {
m.Add("redirect_uri", p.redirectUri)
}
if v, ok := properties["scope"]; ok {
if len(v.(string)) > 0 {
m.Add("scope", v.(string))
}
} else if len(p.scope) > 0 {
m.Add("scope", p.scope)
}
if v, ok := properties["state"]; ok {
if len(v.(string)) > 0 {
m.Add("state", v.(string))
}
} else if len(p.state) > 0 {
m.Add("state", p.state)
}
return MakeUrl(_GOOGLEPLUS_ACCESS_TOKEN_URL, m)
}
func (p *googleplusClient) RequestTokenGranted(req *http.Request) bool {
if err := p.handleClientAcceptRequest(req); err != nil {
LogError("Error in client accept request: ", err.Error())
return false
}
return true
}
func (p *googleplusClient) ExchangeRequestTokenForAccess(req *http.Request) error {
if len(p.refreshToken) <= 0 {
if err := p.handleClientAcceptRequest(req); err != nil {
return err
}
}
_, err := p.UpdateAccessToken()
return err
}
func (p *googleplusClient) CreateAuthorizedRequest(method string, headers http.Header, uri string, query url.Values, r io.Reader) (*http.Request, error) {
if len(method) <= 0 {
method = GET
}
method = strings.ToUpper(method)
if headers == nil {
headers = make(http.Header)
}
if query == nil {
query = make(url.Values)
}
accessToken, err := p.UpdateAccessToken()
if err != nil {
return nil, err
}
headers.Set("Authorization", "Bearer "+accessToken)
fullUrl := MakeUrl(uri, query)
req, err := http.NewRequest(method, fullUrl, r)
if req != nil {
req.Header = headers
}
return req, err
}
func (p *googleplusClient) RetrieveUserInfo() (UserInfo, error) {
req, err := p.CreateAuthorizedRequest(_GOOGLEPLUS_USERINFO_METHOD, nil, _GOOGLEPLUS_USERINFO_URL, nil, nil)
if err != nil {
return nil, err
}
result := new(googleplusUserInfoResult)
resp, _, err := MakeRequest(p, req)
if resp != nil && resp.Body != nil {
if err2 := json.NewDecoder(resp.Body).Decode(result); err == nil {
err = err2
}
}
return result, err
}