-
Notifications
You must be signed in to change notification settings - Fork 0
/
identity.go
87 lines (74 loc) · 1.98 KB
/
identity.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
package smaevcharger
import (
"net/http"
"net/url"
"strings"
"time"
"github.com/thommyho/robotui/util"
"github.com/thommyho/robotui/util/oauth"
"github.com/thommyho/robotui/util/request"
"golang.org/x/oauth2"
)
// Token is the SMAEVCHarger22 Token
// Auth Token Data json Response structure
type Token struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
}
func (t *Token) AsOAuth2Token() *oauth2.Token {
if t == nil {
return nil
}
return &oauth2.Token{
AccessToken: t.AccessToken,
TokenType: t.TokenType,
RefreshToken: t.RefreshToken,
Expiry: time.Now().Add(time.Second * time.Duration(t.ExpiresIn)),
}
}
// tokenSource is an oauth2.TokenSource
type tokenSource struct {
*request.Helper
oauth2.TokenSource
uri string
user string
password string
}
// TokenSource creates an SMAevCharger token source
func TokenSource(log *util.Logger, uri, user, password string) (oauth2.TokenSource, error) {
c := &tokenSource{
Helper: request.NewHelper(log),
uri: uri + "/token",
user: user,
password: password,
}
data := url.Values{
"grant_type": {"password"},
"password": {password},
"username": {user},
}
req, err := request.New(http.MethodPost, c.uri, strings.NewReader(data.Encode()), request.URLEncoding)
if err == nil {
var token Token
if err = c.DoJSON(req, &token); err == nil {
c.TokenSource = oauth.RefreshTokenSource(token.AsOAuth2Token(), c)
}
}
return c, err
}
func (c *tokenSource) RefreshToken(token *oauth2.Token) (*oauth2.Token, error) {
data := url.Values{
"grant_type": {"refresh_token"},
"refresh_token": {token.RefreshToken},
}
req, err := request.New(http.MethodPost, c.uri, strings.NewReader(data.Encode()), request.URLEncoding)
if err == nil {
var token Token
if err = c.DoJSON(req, &token); err == nil {
return token.AsOAuth2Token(), nil
}
}
return nil, err
}