From 44c17a60f9b7fd0e7d22d5abd072bafb2e8a4cf6 Mon Sep 17 00:00:00 2001 From: andig Date: Wed, 7 Jun 2023 18:45:05 +0200 Subject: [PATCH] chore: simplify random state generation --- cmd/token_tronity.go | 15 ++------------- vehicle/ford/identity.go | 4 +++- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/cmd/token_tronity.go b/cmd/token_tronity.go index 9055c6cef..d5e4cb1bc 100644 --- a/cmd/token_tronity.go +++ b/cmd/token_tronity.go @@ -2,11 +2,8 @@ package cmd import ( "context" - "crypto/rand" - "encoding/base64" "errors" "fmt" - "io" "net/http" "strings" "sync" @@ -16,19 +13,11 @@ import ( "github.com/evcc-io/evcc/util" "github.com/evcc-io/evcc/vehicle" "github.com/evcc-io/evcc/vehicle/tronity" + "github.com/samber/lo" "github.com/skratchdot/open-golang/open" "golang.org/x/oauth2" ) -// github.com/uhthomas/tesla -func state() string { - var b [9]byte - if _, err := io.ReadFull(rand.Reader, b[:]); err != nil { - panic(err) - } - return base64.RawURLEncoding.EncodeToString(b[:]) -} - func tokenExchangeHandler(oc *oauth2.Config, state string, resC chan *oauth2.Token) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if remote := r.URL.Query().Get("state"); state != remote { @@ -57,7 +46,7 @@ func tokenExchangeHandler(oc *oauth2.Config, state string, resC chan *oauth2.Tok } func tronityAuthorize(addr string, oc *oauth2.Config) (*oauth2.Token, error) { - state := state() + state := lo.RandomString(16, lo.AlphanumericCharset) uri := oc.AuthCodeURL(state, oauth2.AccessTypeOffline) uri = strings.ReplaceAll(uri, "scope=", "scopes=") diff --git a/vehicle/ford/identity.go b/vehicle/ford/identity.go index e1ded9cc0..fbf3acf52 100644 --- a/vehicle/ford/identity.go +++ b/vehicle/ford/identity.go @@ -15,6 +15,7 @@ import ( "github.com/evcc-io/evcc/util/oauth" "github.com/evcc-io/evcc/util/request" cv "github.com/nirasan/go-oauth-pkce-code-verifier" + "github.com/samber/lo" "golang.org/x/oauth2" ) @@ -66,7 +67,8 @@ func (v *Identity) login() (*oauth.Token, error) { return nil, err } - uri := OAuth2Config.AuthCodeURL("", + state := lo.RandomString(16, lo.AlphanumericCharset) + uri := OAuth2Config.AuthCodeURL(state, oauth2.SetAuthURLParam("max_age", "3600"), oauth2.SetAuthURLParam("code_challenge", cv.CodeChallengeS256()), oauth2.SetAuthURLParam("code_challenge_method", "S256"),