-
Notifications
You must be signed in to change notification settings - Fork 0
/
identity.go
78 lines (63 loc) · 1.74 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
package jlr
import (
"fmt"
"net/http"
"time"
"github.com/thommyho/robotui/util"
"github.com/thommyho/robotui/util/oauth"
"github.com/thommyho/robotui/util/request"
"golang.org/x/oauth2"
)
// https://github.com/ardevd/jlrpy
const IFAS_BASE_URL = "https://ifas.prod-row.jlrmotor.com/ifas/jlr"
type Identity struct {
*request.Helper
user, password, device string
oauth2.TokenSource
}
// NewIdentity creates Fiat identity
func NewIdentity(log *util.Logger, user, password, device string) *Identity {
return &Identity{
Helper: request.NewHelper(log),
user: user,
password: password,
device: device,
}
}
// Login authenticates with given payload
func (v *Identity) login(data map[string]string) (Token, error) {
uri := fmt.Sprintf("%s/tokens", IFAS_BASE_URL)
req, err := request.New(http.MethodPost, uri, request.MarshalJSON(data), map[string]string{
"Authorization": "Basic YXM6YXNwYXNz",
"Content-type": request.JSONContent,
"X-Device-Id": v.device,
})
var token Token
if err == nil {
err = v.DoJSON(req, &token)
token.Expiry = time.Now().Add(time.Duration(token.ExpiresIn) * time.Second)
}
return token, err
}
// Login authenticates with username/password
func (v *Identity) Login() (Token, error) {
data := map[string]string{
"grant_type": "password",
"username": v.user,
"password": v.password,
}
token, err := v.login(data)
if err == nil {
v.TokenSource = oauth.RefreshTokenSource(&token.Token, v)
}
return token, err
}
// RefreshToken implements oauth.TokenRefresher
func (v *Identity) RefreshToken(token *oauth2.Token) (*oauth2.Token, error) {
data := map[string]string{
"grant_type": "refresh_token",
"refresh_token": token.RefreshToken,
}
res, err := v.login(data)
return &res.Token, err
}