chore: simplify random state generation

This commit is contained in:
andig 2023-06-07 18:45:05 +02:00
parent 39a404c51f
commit 44c17a60f9
2 changed files with 5 additions and 14 deletions

View file

@ -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=")

View file

@ -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"),