forked from XeroAPI/xerogolang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxerogolang.go
906 lines (772 loc) · 26 KB
/
xerogolang.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
package xerogolang
import (
"bytes"
"context"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"time"
"crypto"
"github.com/XeroAPI/xerogolang/auth"
"github.com/XeroAPI/xerogolang/helpers"
"github.com/markbates/goth"
"github.com/mrjones/oauth"
"github.com/ninja-software/xoauthlite"
"github.com/ninja-software/xoauthlite/oidc"
"golang.org/x/oauth2"
)
// Version software release tag version
var Version = "v0.1.7"
var (
requestURL = "https://api.xero.com/oauth/RequestToken"
authorizeURL = "https://api.xero.com/oauth/Authorize"
tokenURL = "https://api.xero.com/oauth/AccessToken"
endpointProfile = "https://api.xero.com/api.xro/2.0/"
//userAgentString should match the name of your Application
userAgentString = os.Getenv("XERO_USER_AGENT") + " (xerogolang 0.2.0) " + os.Getenv("XERO_KEY")
//privateKeyFilePath is a file path to your .pem private/public key file
//You only need this for private and partner Applications
//more details here: https://developer.xero.com/documentation/api-guides/create-publicprivate-key
privateKeyFilePath = os.Getenv("XERO_PRIVATE_KEY_PATH")
)
// AuthType supported oauth type
type AuthType string
// list of supported oauth type
const (
AuthTypeOAuth1A AuthType = "oauth1a"
AuthTypeOAuth2 AuthType = "oauth2"
)
// Provider is the implementation of `goth.Provider` for accessing Xero.
type Provider struct {
AuthType AuthType
TenantID string // pick which tenant for oauth2 to interact with
Scopes []string
ClientKey string
Secret string
CallbackURL string
HTTPClient *http.Client
Method string
UserAgentString string
PrivateKey string
debug bool
consumer *oauth.Consumer
oauth2Client *xoauthlite.OidcClient // holds config only
oauth2Session *OAuth2Session
providerName string
ready bool
}
//newPublicConsumer creates a consumer capable of communicating with a Public application: https://developer.xero.com/documentation/auth-and-limits/public-applications
func (p *Provider) newPublicConsumer(authURL string) *oauth.Consumer {
var c *oauth.Consumer
if p.HTTPClient != nil {
c = oauth.NewCustomHttpClientConsumer(
p.ClientKey,
p.Secret,
oauth.ServiceProvider{
RequestTokenUrl: requestURL,
AuthorizeTokenUrl: authURL,
AccessTokenUrl: tokenURL},
p.HTTPClient,
)
} else {
c = oauth.NewConsumer(
p.ClientKey,
p.Secret,
oauth.ServiceProvider{
RequestTokenUrl: requestURL,
AuthorizeTokenUrl: authURL,
AccessTokenUrl: tokenURL},
)
}
c.Debug(p.debug)
return c
}
//newPartnerConsumer creates a consumer capable of communicating with a Partner application: https://developer.xero.com/documentation/auth-and-limits/partner-applications
func (p *Provider) newPrivateOrPartnerConsumer(authURL string) *oauth.Consumer {
block, _ := pem.Decode([]byte(p.PrivateKey))
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Fatal(err)
}
var c *oauth.Consumer
if p.HTTPClient != nil {
c = oauth.NewCustomRSAConsumer(
p.ClientKey,
privateKey,
crypto.SHA1,
oauth.ServiceProvider{
RequestTokenUrl: requestURL,
AuthorizeTokenUrl: authURL,
AccessTokenUrl: tokenURL},
p.HTTPClient,
)
} else {
c = oauth.NewRSAConsumer(
p.ClientKey,
privateKey,
oauth.ServiceProvider{
RequestTokenUrl: requestURL,
AuthorizeTokenUrl: authURL,
AccessTokenUrl: tokenURL},
)
}
c.Debug(p.debug)
return c
}
// New creates a new Xero provider, and sets up important connection details.
// You should always call `xero.New` to get a new Provider. Never try to create
// one manually.
func New(clientKey, secret, callbackURL string) *Provider {
p := &Provider{
AuthType: AuthTypeOAuth1A,
ClientKey: clientKey,
Secret: secret,
CallbackURL: callbackURL,
//Method determines how you will connect to Xero.
//Options are public, private, and partner
//Use public if this is your first time.
//More details here: https://developer.xero.com/documentation/getting-started/api-application-types
Method: os.Getenv("XERO_METHOD"),
PrivateKey: helpers.ReadPrivateKeyFromPath(privateKeyFilePath),
UserAgentString: userAgentString,
providerName: "xero",
}
return p
}
// NewNoEnviro creates a new Xero provider without using the environmental set variables
// , and sets up important connection details.
// You should always call `xero.New` to get a new Provider. Never try to create
// one manually.
func NewNoEnviro(clientKey, secret, callbackURL, userAgent, xeroMethod string, privateKey []byte) *Provider {
// Set variables without using the environment
userAgentString = userAgent + " (xerogolang 0.2.0) " + clientKey
privateKeyFilePath = ""
p := &Provider{
AuthType: AuthTypeOAuth1A,
ClientKey: clientKey,
Secret: secret,
CallbackURL: callbackURL,
//Method determines how you will connect to Xero.
//Options are public, private, and partner
//Use public if this is your first time.
//More details here: https://developer.xero.com/documentation/getting-started/api-application-types
Method: xeroMethod,
PrivateKey: string(privateKey),
UserAgentString: userAgentString,
providerName: "xero",
}
return p
}
// NewOAuth2 creates a new Xero provider using OAuth2, and sets up important connection details.
// You should always call `xero.NewOAuth2` to get a new Provider. Never try to create
// one manually.
func NewOAuth2(clientID, clientSecret string, callbackURL *url.URL, xeroMethod string, scopes []string, tenantID string) *Provider {
p := &Provider{
AuthType: AuthTypeOAuth2,
TenantID: tenantID,
ClientKey: clientID,
Secret: clientSecret,
CallbackURL: callbackURL.String(),
Method: xeroMethod,
PrivateKey: "",
UserAgentString: userAgentString,
providerName: "xero",
Scopes: scopes,
consumer: &oauth.Consumer{}, // non-nil to skip
oauth2Client: &xoauthlite.OidcClient{
Authority: oidc.DefaultAuthority,
ClientID: clientID,
ClientSecret: clientSecret,
Scopes: oidc.DefaultScopes,
RedirectURL: callbackURL,
},
}
return p
}
// ResumeOauth2 resume previous oauth session by using previous tokens
func (p *Provider) ResumeOauth2(authorisationEndpoint, accessToken, refreshToken, tenantID string) (*OAuth2Session, error) {
// setup session if not exist
if p.oauth2Session == nil {
p.oauth2Session = &OAuth2Session{}
}
osess := p.oauth2Session
osess.AuthURL = authorisationEndpoint
osess.TenantID = tenantID
osess.AccessToken = accessToken
osess.RefreshToken = &OAuth2RefreshToken{
String: refreshToken,
}
return osess, nil
}
// StartAutoOauth2TokenRefresh start automatic token refresher
func (p *Provider) StartAutoOauth2TokenRefresh(clientReady *bool) {
// using primitive for loop with goroutine because there is no reliable way of changing ticker time
go func() {
firstLoop := true
for {
// wait enough so it wait time can be changed and also not eating cpu
time.Sleep(time.Second * 5)
// sanity check
if p.oauth2Session == nil {
continue
}
// shorthand
rt := p.oauth2Session.RefreshToken
// prevent starting more than 1 refresher
// wont stop if there is multiple started at short time, but this will do
if firstLoop && rt.RefresherIsAlive {
break
}
// not yet to refresh
tickSpeed := rt.RefresherTime
// fail safe, min 5 min
if tickSpeed < 300 {
tickSpeed = 300
}
if rt.CreatedAt.Add(time.Duration(tickSpeed) * time.Second).After(time.Now()) {
continue
}
rt.RefresherIsAlive = true
firstLoop = false
_, err := p.RefreshOAuth2Token()
if err != nil {
rt.RefresherIsAlive = false
break
}
// When an xero api call returns a failure the xero client ready becomes false which prevents further calls
// to the API and presents an error in frontend etc. to prompt token refresh. There is potential to recover
// from this state. So if the token refresh is successful, then the API can be used again, so client ready
// state can go back to true.
if clientReady != nil {
*clientReady = true
}
}
}()
}
// Oauth2TokenRefresherIsAlive is it alive
func (p *Provider) Oauth2TokenRefresherIsAlive() bool {
return p.oauth2Session.RefreshToken.RefresherIsAlive
}
// SetOauth2Session set oauth2 session in instance
func (p *Provider) SetOauth2Session(wellKnownConfig *oidc.WellKnownConfiguration, viewModel *xoauthlite.TokenResultViewModel) *OAuth2Session {
now := time.Now()
oAuth2Session := &OAuth2Session{
AuthURL: wellKnownConfig.AuthorisationEndpoint,
AccessToken: viewModel.AccessToken,
AccessTokenExpires: now.Add(time.Second * 1800),
RefreshToken: &OAuth2RefreshToken{
String: viewModel.RefreshToken,
CreatedAt: now,
},
IdentityToken: viewModel.IDToken,
CreatedAt: now,
UpdatedAt: now,
}
p.oauth2Session = oAuth2Session
return oAuth2Session
}
// GetOauth2TokenRefreshRate get the token refresh rate
func (p *Provider) GetOauth2TokenRefreshRate() int {
return p.oauth2Session.RefreshToken.RefresherTime
}
// SetOauth2TokenRefreshRate set the token refresh rate
func (p *Provider) SetOauth2TokenRefreshRate(sec int) error {
if sec < 60*5 {
return fmt.Errorf("time cannot be less than 5 minutes")
}
if sec > 60*29 {
return fmt.Errorf("time cannot be higher than 29 minutes")
}
if p.oauth2Session == nil {
return ErrOauth2SessionIsNil
}
p.oauth2Session.RefreshToken.RefresherTime = sec
return nil
}
// SetOauth2TokenRefreshEcho set the token refresh echo or not
func (p *Provider) SetOauth2TokenRefreshEcho(echo bool) error {
if p.oauth2Session == nil {
return ErrOauth2SessionIsNil
}
p.oauth2Session.RefreshToken.Echo = echo
return nil
}
// NewCustomHTTPClient creates a new Xero provider, with a custom http client
func NewCustomHTTPClient(clientKey, secret, callbackURL string, httpClient *http.Client) *Provider {
p := &Provider{
ClientKey: clientKey,
Secret: secret,
CallbackURL: callbackURL,
Method: os.Getenv("XERO_METHOD"),
PrivateKey: helpers.ReadPrivateKeyFromPath(privateKeyFilePath),
UserAgentString: userAgentString,
providerName: "xero",
HTTPClient: httpClient,
}
return p
}
// Name is the name used to retrieve this provider later.
func (p *Provider) Name() string {
return p.providerName
}
// SetName is to update the name of the provider (needed in case of multiple providers of 1 type)
func (p *Provider) SetName(name string) {
p.providerName = name
}
// Client does pretty much everything
func (p *Provider) Client() *http.Client {
return goth.HTTPClientWithFallBack(p.HTTPClient)
}
// Debug sets the logging of the OAuth client to verbose.
func (p *Provider) Debug(debug bool) {
p.debug = debug
}
// BeginAuth asks Xero for an authentication end-point and a request token for a session.
// Xero does not support the "state" variable.
func (p *Provider) BeginAuth(state string) (goth.Session, error) {
if p.AuthType == AuthTypeOAuth2 {
return p.BeginOAuth2(state)
}
if p.consumer == nil {
p.initConsumer()
}
if p.Method == "private" {
accessToken := &oauth.AccessToken{
Token: p.ClientKey,
Secret: p.Secret,
}
privateSession := &Session{
AuthURL: authorizeURL,
RequestToken: nil,
AccessToken: accessToken,
AccessTokenExpires: time.Now().UTC().Add(87600 * time.Hour),
}
return privateSession, nil
}
requestToken, url, err := p.consumer.GetRequestTokenAndUrl(p.CallbackURL)
if err != nil {
return nil, err
}
session := &Session{
AuthURL: url,
RequestToken: requestToken,
}
return session, nil
}
// BeginOAuth2 asks Xero for an authentication end-point and a request token for a session.
// Xero does not support the "state" variable.
func (p *Provider) BeginOAuth2(stateX string) (goth.Session, error) {
u, err := url.Parse(p.CallbackURL)
if err != nil {
return nil, err
}
if p.ClientKey == "" {
return nil, fmt.Errorf("empty client id")
}
if p.Secret == "" {
return nil, fmt.Errorf("empty client secret")
}
clientConfig := &xoauthlite.OidcClient{
Authority: oidc.DefaultAuthority,
ClientID: p.ClientKey,
ClientSecret: p.Secret,
Scopes: p.Scopes,
RedirectURL: u,
}
var wellKnownConfig, wellKnownErr = oidc.GetMetadata(clientConfig.Authority)
if wellKnownErr != nil {
return nil, wellKnownErr
}
// not used
codeChallenge := ""
codeVerifier := ""
// build browser link
state, stateErr := oidc.GenerateRandomStringURLSafe(24)
if stateErr != nil {
return nil, stateErr
}
authorisationURL, err := oidc.BuildCodeAuthorisationRequest(
*wellKnownConfig,
clientConfig.ClientID,
clientConfig.RedirectURL.String(),
clientConfig.Scopes,
state,
codeChallenge,
)
if err != nil {
return nil, err
}
fmt.Println("Open browser to", authorisationURL)
// setup http server
m := http.NewServeMux()
s := http.Server{
Addr: fmt.Sprintf(":%s", u.Port()),
Handler: m,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Open a web server to receive the redirect
m.HandleFunc("/callback", handler(clientConfig, wellKnownConfig, codeVerifier, state, p, cancel))
go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Println(err)
}
}()
select {
case <-ctx.Done():
// Shutdown the server when the context is canceled
err := s.Shutdown(ctx)
if err != nil {
log.Println(err)
}
}
return p.oauth2Session, nil
}
//processRequest processes a request prior to it being sent to the API
func (p *Provider) processRequest(request *http.Request, session goth.Session, additionalHeaders map[string]string) ([]byte, error) {
if p.AuthType == AuthTypeOAuth2 {
sessOA2 := session.(*OAuth2Session)
return p.processRequestOAuth2(request, sessOA2, additionalHeaders)
}
sess := session.(*Session)
if p.consumer == nil {
p.initConsumer()
}
if sess.AccessToken == nil {
// data is not yet retrieved since accessToken is still empty
return nil, fmt.Errorf("%s cannot process request without accessToken", p.providerName)
}
request.Header.Add("User-Agent", p.UserAgentString)
for key, value := range additionalHeaders {
request.Header.Add(key, value)
}
var err error
var response *http.Response
if p.HTTPClient == nil {
client, _ := p.consumer.MakeHttpClient(sess.AccessToken)
response, err = client.Do(request)
} else {
transport, _ := p.consumer.MakeRoundTripper(sess.AccessToken)
response, err = transport.RoundTrip(request)
}
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
helpers.ReaderToString(response.Body),
)
}
responseBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("Could not read response: %s", err.Error())
}
if responseBytes == nil {
return nil, fmt.Errorf("Received no response: %s", err.Error())
}
return responseBytes, nil
}
//processRequestOAuth2 processes a request prior to it being sent to the API for oauth2
func (p *Provider) processRequestOAuth2(request *http.Request, session *OAuth2Session, additionalHeaders map[string]string) ([]byte, error) {
var err error
err = p.initOAuth2()
if err != nil {
return nil, err
}
request.Header.Add("Authorization", "Bearer "+session.AccessToken)
request.Header.Add("Xero-tenant-id", session.TenantID)
request.Header.Add("User-Agent", p.UserAgentString)
for key, value := range additionalHeaders {
request.Header.Add(key, value)
}
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
helpers.ReaderToString(response.Body),
)
}
responseBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("Could not read response: %w", err)
}
if responseBytes == nil {
return nil, fmt.Errorf("Received nil response")
}
return responseBytes, nil
}
//Find retrieves the requested data from an endpoint to be unmarshaled into the appropriate data type
func (p *Provider) Find(session goth.Session, endpoint string, additionalHeaders map[string]string, querystringParameters map[string]string) ([]byte, error) {
var querystring string
if querystringParameters != nil {
for key, value := range querystringParameters {
escapedValue := url.QueryEscape(value)
querystring = querystring + "&" + key + "=" + escapedValue
}
querystring = strings.TrimPrefix(querystring, "&")
querystring = "?" + querystring
}
request, err := http.NewRequest("GET", endpointProfile+endpoint+querystring, nil)
if err != nil {
return nil, err
}
return p.processRequest(request, session, additionalHeaders)
}
//Create sends data to an endpoint and returns a response to be unmarshaled into the appropriate data type
func (p *Provider) Create(session goth.Session, endpoint string, additionalHeaders map[string]string, body []byte, querystringParameters map[string]string) ([]byte, error) {
var querystring string
if querystringParameters != nil {
for key, value := range querystringParameters {
escapedValue := url.QueryEscape(value)
querystring = querystring + "&" + key + "=" + escapedValue
}
querystring = strings.TrimPrefix(querystring, "&")
querystring = "?" + querystring
}
bodyReader := bytes.NewReader(body)
request, err := http.NewRequest("PUT", endpointProfile+endpoint+querystring, bodyReader)
if err != nil {
return nil, err
}
return p.processRequest(request, session, additionalHeaders)
}
//Update sends data to an endpoint and returns a response to be unmarshaled into the appropriate data type
func (p *Provider) Update(session goth.Session, endpoint string, additionalHeaders map[string]string, body []byte, querystringParameters map[string]string) ([]byte, error) {
var querystring string
if querystringParameters != nil {
for key, value := range querystringParameters {
escapedValue := url.QueryEscape(value)
querystring = querystring + "&" + key + "=" + escapedValue
}
querystring = strings.TrimPrefix(querystring, "&")
querystring = "?" + querystring
}
bodyReader := bytes.NewReader(body)
request, err := http.NewRequest("POST", endpointProfile+endpoint+querystring, bodyReader)
if err != nil {
return nil, err
}
return p.processRequest(request, session, additionalHeaders)
}
//Remove deletes the specified data from an endpoint
func (p *Provider) Remove(session goth.Session, endpoint string, additionalHeaders map[string]string) ([]byte, error) {
request, err := http.NewRequest("DELETE", endpointProfile+endpoint, nil)
if err != nil {
return nil, err
}
return p.processRequest(request, session, additionalHeaders)
}
// TenantConnection is the singular schema of endpoint response of xero api /connections
type TenantConnection struct {
ID string `json:"id"`
TenantID string `json:"tenantId"`
TenantName string `json:"tenantName"`
TenantType string `json:"tenantType"`
CreatedDateUTC string `json:"createdDateUtc"`
UpdatedDateUTC string `json:"updatedDateUtc"`
}
// TenantConnections is collection, expected response from endpoint xero api /connections
type TenantConnections []*TenantConnection
// Connections finds out tenant connections that session have access to
func (p *Provider) Connections(session goth.Session, additionalHeaders map[string]string) ([]*TenantConnection, error) {
endpoint := "https://api.xero.com/connections"
request, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
responseBytes, err := p.processRequest(request, session, additionalHeaders)
if err != nil {
return nil, err
}
var tconnections TenantConnections
err = json.Unmarshal(responseBytes, &tconnections)
if err != nil {
return nil, fmt.Errorf("Could not unmarshal response: %w", err)
}
return tconnections, nil
}
//Organisation is the expected response from the Organisation endpoint - this is not a complete schema
//and should only be used by FetchUser
type Organisation struct {
// Display name of organisation shown in Xero
Name string `json:"Name,omitempty"`
// Organisation name shown on Reports
LegalName string `json:"LegalName,omitempty"`
// Organisation Type
OrganisationType string `json:"OrganisationType,omitempty"`
// Country code for organisation. See ISO 3166-2 Country Codes
CountryCode string `json:"CountryCode,omitempty"`
// A unique identifier for the organisation.
ShortCode string `json:"ShortCode,omitempty"`
}
//OrganisationCollection is the Total response from the Xero API
type OrganisationCollection struct {
Organisations []Organisation `json:"Organisations,omitempty"`
}
// FetchUser will go to Xero and access basic information about the user.
func (p *Provider) FetchUser(session goth.Session) (goth.User, error) {
sess := session.(*Session)
user := goth.User{
Provider: p.Name(),
}
additionalHeaders := map[string]string{
"Accept": "application/json",
}
responseBytes, err := p.Find(sess, "Organisation", additionalHeaders, nil)
if err != nil {
return user, err
}
var organisationCollection OrganisationCollection
err = json.Unmarshal(responseBytes, &organisationCollection)
if err != nil {
return user, fmt.Errorf("Could not unmarshal response: %s", err.Error())
}
user.Name = organisationCollection.Organisations[0].Name
user.NickName = organisationCollection.Organisations[0].LegalName
user.Location = organisationCollection.Organisations[0].CountryCode
user.Description = organisationCollection.Organisations[0].OrganisationType
user.UserID = organisationCollection.Organisations[0].ShortCode
user.AccessToken = sess.AccessToken.Token
user.AccessTokenSecret = sess.AccessToken.Secret
user.ExpiresAt = sess.AccessTokenExpires
user.Email = p.Method
return user, err
}
//RefreshOAuth1Token should be used instead of RefeshToken which is not compliant with the Oauth1.0a standard
func (p *Provider) RefreshOAuth1Token(session *Session) error {
if p.consumer == nil {
p.initConsumer()
}
if session.AccessToken == nil {
return fmt.Errorf("Could not refresh token as last valid accessToken was not found")
}
newAccessToken, err := p.consumer.RefreshToken(session.AccessToken)
if err != nil {
return err
}
session.AccessToken = newAccessToken
session.AccessTokenExpires = time.Now().UTC().Add(30 * time.Minute)
return nil
}
// holds error
var (
ErrNotOauth2Type = errors.New("not oauth2 type")
ErrRefreshTokenUsed = errors.New("refresh token already used")
ErrRefresherIsAlive = errors.New("existing auto token refresher is running")
ErrOauth2SessionIsNil = errors.New("oauth2 session is nil")
)
// RefreshOAuth2Token force refresh token
func (p *Provider) RefreshOAuth2Token() (*OAuth2Session, error) {
// not a oauth2 type
if p.AuthType != AuthTypeOAuth2 {
return nil, ErrNotOauth2Type
}
// make sure session exists
osess := p.oauth2Session
if osess == nil {
return nil, ErrOauth2SessionIsNil
}
if osess.RefreshToken.Used {
return osess, ErrRefreshTokenUsed
}
clientID := p.oauth2Client.ClientID
clientSecret := p.oauth2Client.ClientSecret
refreshToken := osess.RefreshToken.String
now := time.Now()
refreshResult, err := oidc.RefreshToken(
oidc.DefaultAuthority,
clientID,
clientSecret,
refreshToken,
)
if err != nil {
osess.RefreshToken.Used = true
osess.RefreshToken.LastUsedAt = now
return osess, err
}
// update refresh token
osess.RefreshToken.String = refreshResult.RefreshToken
osess.RefreshToken.Used = false
osess.RefreshToken.LastUsedAt = now
osess.RefreshToken.CreatedAt = now
// update access token
// note that access token changes each time it is refreshed, so store the update
osess.AccessToken = refreshResult.AccessToken
osess.AccessTokenExpires = time.Now().Add(time.Duration(refreshResult.ExpiresIn) * time.Second)
if osess.RefreshToken.Echo {
log.Println("xero oauth2 token refreshed")
}
return osess, nil
}
//RefreshToken refresh token is not provided by the Xero Public or Private Application -
//only the Partner Application and you must use RefreshOAuth1Token instead
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
return nil, errors.New("Refresh token is only provided by Xero for Partner Applications")
}
//RefreshTokenAvailable refresh token is not provided by the Xero Public or Private Application -
//only the Partner Application and you must use RefreshOAuth1Token instead
func (p *Provider) RefreshTokenAvailable() bool {
return false
}
//GetSessionFromStore returns a session for a given a request and a response
//This is an exaple of how you could get a session from a store - as long as you're
//supplying a goth.Session to the interactors it will work though so feel free to use your
//own method
func (p *Provider) GetSessionFromStore(request *http.Request, response http.ResponseWriter) (goth.Session, error) {
sessionMarshalled, _ := auth.Store.Get(request, "xero"+auth.SessionName)
value := sessionMarshalled.Values["xero"]
if value == nil {
return nil, errors.New("could not find a matching session for this request")
}
session, err := p.UnmarshalSession(value.(string))
if err != nil {
return nil, errors.New("could not unmarshal session for this request")
}
sess := session.(*Session)
if sess.AccessTokenExpires.Before(time.Now().UTC().Add(5 * time.Minute)) {
if p.Method == "partner" {
p.RefreshOAuth1Token(sess)
sessionMarshalled.Values["xero"] = sess.Marshal()
err = sessionMarshalled.Save(request, response)
return session, err
}
return nil, errors.New("access token has expired - please reconnect")
}
return session, err
}
func (p *Provider) initConsumer() {
switch p.Method {
case "private":
p.consumer = p.newPrivateOrPartnerConsumer(authorizeURL)
case "public":
p.consumer = p.newPublicConsumer(authorizeURL)
case "partner":
p.consumer = p.newPrivateOrPartnerConsumer(authorizeURL)
default:
p.consumer = p.newPublicConsumer(authorizeURL)
}
}
func (p *Provider) initOAuth2() error {
var _, err = oidc.GetMetadata(oidc.DefaultAuthority)
if err != nil {
return err
}
return nil
}
// Ready is the provider is authenticated and ready to process
func (p *Provider) Ready() bool {
return p.ready
}