This repository has been archived by the owner on Apr 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
session.go
72 lines (61 loc) · 1.78 KB
/
session.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
package xerogolang
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/markbates/goth"
"github.com/mrjones/oauth"
)
// Session stores data during the auth process with Xero.
type Session struct {
AuthURL string
AccessToken *oauth.AccessToken
RequestToken *oauth.RequestToken
AccessTokenExpires time.Time
}
// GetAuthURL will return the URL set by calling the `BeginAuth` function on the Xero provider.
func (s Session) GetAuthURL() (string, error) {
if s.AuthURL == "" {
return "", errors.New(goth.NoAuthUrlErrorMessage)
}
return s.AuthURL, nil
}
// Authorize the session with Xero and return the access token to be stored for future use.
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
p := provider.(*Provider)
if p.Method == "private" {
privateAccessToken := &oauth.AccessToken{
Token: p.ClientKey,
Secret: p.Secret,
}
s.AccessTokenExpires = time.Now().UTC().Add(87600 * time.Hour)
s.AccessToken = privateAccessToken
return p.ClientKey, nil
}
if s.RequestToken == nil {
return "", fmt.Errorf("Missing Request Token")
}
accessToken, err := p.consumer.AuthorizeToken(s.RequestToken, params.Get("oauth_verifier"))
if err != nil {
return "", err
}
s.AccessTokenExpires = time.Now().UTC().Add(30 * time.Minute)
s.AccessToken = accessToken
return accessToken.Token, nil
}
// Marshal the session into a string
func (s Session) Marshal() string {
b, _ := json.Marshal(s)
return string(b)
}
func (s Session) String() string {
return s.Marshal()
}
// UnmarshalSession will unmarshal a JSON string into a session.
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
sess := &Session{}
err := json.NewDecoder(strings.NewReader(data)).Decode(sess)
return sess, err
}