Polestar: use oauth2 (#28604)
This commit is contained in:
parent
82001f3c33
commit
13152b4243
1 changed files with 31 additions and 91 deletions
|
|
@ -1,8 +1,8 @@
|
|||
package polestar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
|
|
@ -11,72 +11,55 @@ import (
|
|||
"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/net/publicsuffix"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// https://github.com/TA2k/ioBroker.polestar
|
||||
|
||||
// OAuth endpoints and credentials
|
||||
const (
|
||||
OAuthURI = "https://polestarid.eu.polestar.com"
|
||||
ClientID = "l3oopkc_10"
|
||||
RedirectURI = "https://www.polestar.com/sign-in-callback"
|
||||
)
|
||||
|
||||
type Identity struct {
|
||||
*request.Helper
|
||||
oauth2.TokenSource
|
||||
user, password string
|
||||
log *util.Logger
|
||||
var OAuth2Config = &oauth2.Config{
|
||||
ClientID: ClientID,
|
||||
RedirectURL: RedirectURI,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: OAuthURI + "/as/authorization.oauth2",
|
||||
TokenURL: OAuthURI + "/as/token.oauth2",
|
||||
AuthStyle: oauth2.AuthStyleInParams,
|
||||
},
|
||||
Scopes: []string{"openid", "profile", "email"},
|
||||
}
|
||||
|
||||
type Identity struct {
|
||||
*request.Helper
|
||||
user, password string
|
||||
}
|
||||
|
||||
// NewIdentity creates Polestar identity
|
||||
func NewIdentity(log *util.Logger, user, password string) (oauth2.TokenSource, error) {
|
||||
v := &Identity{
|
||||
Helper: request.NewHelper(log),
|
||||
user: user,
|
||||
password: password,
|
||||
log: log,
|
||||
}
|
||||
|
||||
jar, err := cookiejar.New(&cookiejar.Options{
|
||||
PublicSuffixList: publicsuffix.List,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v.Client.Jar = jar
|
||||
|
||||
// Get initial token
|
||||
token, err := v.login()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
v.TokenSource = oauth.RefreshTokenSource(token, v.refreshToken)
|
||||
|
||||
return v, nil
|
||||
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, v.Client)
|
||||
return oauth2.ReuseTokenSource(token, OAuth2Config.TokenSource(ctx, token)), nil
|
||||
}
|
||||
|
||||
func (v *Identity) login() (*oauth2.Token, error) {
|
||||
v.Client.Jar, _ = cookiejar.New(nil)
|
||||
|
||||
cv := oauth2.GenerateVerifier()
|
||||
|
||||
data := url.Values{
|
||||
"client_id": {ClientID},
|
||||
"redirect_uri": {RedirectURI},
|
||||
"response_type": {"code"},
|
||||
"scope": {"openid profile email"},
|
||||
"state": {lo.RandomString(16, lo.AlphanumericCharset)},
|
||||
"code_challenge": {oauth2.S256ChallengeFromVerifier(cv)},
|
||||
"code_challenge_method": {"S256"},
|
||||
}
|
||||
|
||||
// Request authorization URL with browser-like headers
|
||||
uri := fmt.Sprintf("%s/as/authorization.oauth2?%s", OAuthURI, data.Encode())
|
||||
uri := OAuth2Config.AuthCodeURL(lo.RandomString(16, lo.AlphanumericCharset), oauth2.S256ChallengeOption(cv))
|
||||
req, _ := request.New(http.MethodGet, uri, nil, map[string]string{
|
||||
"Accept": "text/html,application/xhtml+xml,application/xml;",
|
||||
})
|
||||
|
|
@ -87,28 +70,28 @@ func (v *Identity) login() (*oauth2.Token, error) {
|
|||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Extract resume path from HTML response
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
matches := regexp.MustCompile(`(?:url|action):\s*"(.+?)"`).FindStringSubmatch(string(body))
|
||||
|
||||
if len(matches) < 2 {
|
||||
return nil, errors.New("could not find resume path")
|
||||
}
|
||||
|
||||
// Submit credentials to login endpoint
|
||||
data = url.Values{
|
||||
resumePath := matches[1]
|
||||
if !strings.HasPrefix(resumePath, "http") {
|
||||
resumePath = OAuthURI + "/" + strings.TrimLeft(resumePath, "/")
|
||||
}
|
||||
|
||||
data := url.Values{
|
||||
"pf.username": {v.user},
|
||||
"pf.pass": {v.password},
|
||||
"client_id": {ClientID},
|
||||
}
|
||||
|
||||
uri = OAuthURI + "/" + strings.TrimLeft(matches[1], "/") // Remove leading /
|
||||
|
||||
req, _ = request.New(http.MethodPost, uri, strings.NewReader(data.Encode()), map[string]string{
|
||||
req, _ = request.New(http.MethodPost, resumePath, strings.NewReader(data.Encode()), map[string]string{
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Accept": "application/json",
|
||||
})
|
||||
|
|
@ -124,52 +107,9 @@ func (v *Identity) login() (*oauth2.Token, error) {
|
|||
return nil, errors.New("missing authorization code")
|
||||
}
|
||||
|
||||
// Exchange code for token
|
||||
data = url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"code_verifier": {cv},
|
||||
"client_id": {ClientID},
|
||||
"redirect_uri": {RedirectURI},
|
||||
}
|
||||
cctx := context.WithValue(context.Background(), oauth2.HTTPClient, v.Client)
|
||||
ctx, cancel := context.WithTimeout(cctx, request.Timeout)
|
||||
defer cancel()
|
||||
|
||||
var token oauth2.Token
|
||||
req, _ = request.New(http.MethodPost, OAuthURI+"/as/token.oauth2",
|
||||
strings.NewReader(data.Encode()),
|
||||
map[string]string{
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
|
||||
if err := v.DoJSON(req, &token); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return util.TokenWithExpiry(&token), nil
|
||||
}
|
||||
|
||||
// refreshToken obtains a renewed oauth token
|
||||
func (v *Identity) refreshToken(token *oauth2.Token) (*oauth2.Token, error) {
|
||||
data := url.Values{
|
||||
"grant_type": {"refresh_token"},
|
||||
"refresh_token": {token.RefreshToken},
|
||||
"client_id": {ClientID},
|
||||
}
|
||||
|
||||
req, _ := request.New(http.MethodPost, OAuthURI+"/as/token.oauth2",
|
||||
strings.NewReader(data.Encode()),
|
||||
map[string]string{
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
)
|
||||
|
||||
var res oauth2.Token
|
||||
if err := v.DoJSON(req, &res); err == nil {
|
||||
return util.TokenWithExpiry(&res), nil
|
||||
}
|
||||
|
||||
// Full login as fallback
|
||||
return v.login()
|
||||
return OAuth2Config.Exchange(ctx, code, oauth2.VerifierOption(cv))
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue