forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidentity.go
223 lines (185 loc) Β· 5.78 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
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
package ford
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strings"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/oauth"
"github.com/evcc-io/evcc/util/request"
"github.com/samber/lo"
"golang.org/x/oauth2"
)
const (
TokenURI = "https://api.mps.ford.com"
LoginUri = "https://login.ford.com/4566605f-43a7-400a-946e-89cc9fdb0bd7/B2C_1A_SignInSignUp_de-DE"
ClientID = "09852200-05fd-41f6-8c21-d36d3497dc64"
ApplicationID = "1E8C7794-FF5F-49BC-9596-A1E0C86C5B19"
)
var loginHeaders = map[string]string{
"Accept": "*/*",
"Accept-Language": "en-us",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1",
}
var OAuth2Config = &oauth2.Config{
ClientID: ClientID,
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("%s/oauth2/v2.0/authorize", LoginUri),
TokenURL: fmt.Sprintf("%s/oauth2/v2.0/token", LoginUri),
},
RedirectURL: "fordapp://userauthorized",
Scopes: []string{ClientID, "openid"},
}
type Settings struct {
TransId string `json:"transId"`
Csrf string `json:"csrf"`
}
type Identity struct {
*request.Helper
user, password string
oauth2.TokenSource
}
// NewIdentity creates Ford identity
func NewIdentity(log *util.Logger, user, password string) *Identity {
return &Identity{
Helper: request.NewHelper(log),
user: user,
password: password,
}
}
// Login authenticates with username/password to get new aws credentials
func (v *Identity) Login() error {
token, err := v.login()
if err == nil {
v.TokenSource = oauth.RefreshTokenSource((*oauth2.Token)(token), v)
}
return err
}
// login authenticates with username/password to get new token
func (v *Identity) login() (*oauth.Token, error) {
cv := oauth2.GenerateVerifier()
state := lo.RandomString(16, lo.AlphanumericCharset)
uri := OAuth2Config.AuthCodeURL(state, oauth2.S256ChallengeOption(cv),
oauth2.SetAuthURLParam("max_age", "3600"),
oauth2.SetAuthURLParam("ui_locales", "de-DE"),
oauth2.SetAuthURLParam("language_code", "de-DE"),
oauth2.SetAuthURLParam("country_code", "DE"),
oauth2.SetAuthURLParam("ford_application_id", ApplicationID),
)
v.Jar, _ = cookiejar.New(nil)
defer func() { v.Jar = nil }()
var body []byte
req, err := request.New(http.MethodGet, uri, nil, loginHeaders)
if err == nil {
body, err = v.DoBody(req)
}
if err != nil {
return nil, err
}
match := regexp.MustCompile(`var SETTINGS = (\{[^;]*\});`).FindSubmatch(body)
if len(match) < 2 {
return nil, errors.New("missing settings variable")
}
var settings Settings
if err := json.Unmarshal(match[1], &settings); err != nil {
return nil, err
}
data := url.Values{
"request_type": {"RESPONSE"},
"signInName": {v.user},
"password": {v.password},
}
v.Client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if req.URL.Scheme != "https" {
return http.ErrUseLastResponse
}
return nil
}
defer func() { v.Client.CheckRedirect = nil }()
uri2 := fmt.Sprintf("%s/SelfAsserted?tx=%s&p=B2C_1A_SignInSignUp_de-DE", LoginUri, settings.TransId)
req, err = request.New(http.MethodPost, uri2, strings.NewReader(data.Encode()), request.URLEncoding, map[string]string{
"Accept": "*/*",
"Accept-Language": "en-us",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1",
"Origin": "https://login.ford.com",
"Referer": uri,
"X-Csrf-Token": settings.Csrf,
})
if err == nil {
var resp *http.Response
if resp, err = v.Do(req); err == nil {
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, errors.New("self-assert failed")
}
}
}
uri3 := fmt.Sprintf("%s/api/CombinedSigninAndSignup/confirmed?rememberMe=false&csrf_token=%s&tx=%s&p=B2C_1A_SignInSignUp_de-DE", LoginUri, settings.Csrf, settings.TransId)
req, err = request.New(http.MethodGet, uri3, nil, request.URLEncoding, map[string]string{
"Origin": "https://login.ford.com",
"Referer": uri,
"X-Csrf-Token": settings.Csrf,
})
var loc *url.URL
if err == nil {
var resp *http.Response
if resp, err = v.Do(req); err == nil {
defer resp.Body.Close()
loc, err = url.Parse(resp.Header.Get("location"))
}
}
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(
context.WithValue(context.Background(), oauth2.HTTPClient, v.Client),
request.Timeout,
)
defer cancel()
code := loc.Query().Get("code")
if code == "" {
return nil, errors.New("could not obtain auth code- check user and password")
}
tok, err := OAuth2Config.Exchange(ctx, code, oauth2.VerifierOption(cv))
// exchange code for api token
var token oauth.Token
if err == nil {
data := map[string]string{
"idpToken": tok.AccessToken,
}
uri := fmt.Sprintf("%s/api/token/v2/cat-with-b2c-access-token", TokenURI)
var req *http.Request
req, err = request.New(http.MethodPost, uri, request.MarshalJSON(data), map[string]string{
"Content-type": request.JSONContent,
"Application-Id": ApplicationID,
})
if err == nil {
err = v.DoJSON(req, &token)
}
}
return &token, err
}
// RefreshToken implements oauth.TokenRefresher
func (v *Identity) RefreshToken(token *oauth2.Token) (*oauth2.Token, error) {
data := map[string]string{
"refresh_token": token.RefreshToken,
}
uri := fmt.Sprintf("%s/api/token/v2/cat-with-refresh-token", TokenURI)
req, err := request.New(http.MethodPost, uri, request.MarshalJSON(data), map[string]string{
"Content-type": request.JSONContent,
"Application-Id": ApplicationID,
})
var res *oauth.Token
if err == nil {
err = v.DoJSON(req, &res)
}
if err != nil {
res, err = v.login()
}
return (*oauth2.Token)(res), err
}