diff --git a/vehicle/mercedes/identity.go b/vehicle/mercedes/identity.go index 916dfb203..4079166b5 100644 --- a/vehicle/mercedes/identity.go +++ b/vehicle/mercedes/identity.go @@ -30,8 +30,8 @@ type Identity struct { log *util.Logger *ReuseTokenSource sessionSecret []byte - authC chan<- bool oc *oauth2.Config + authC chan<- bool } func generateSecret() ([]byte, error) { @@ -47,17 +47,25 @@ func NewIdentity(log *util.Logger, id, secret string, options ...IdentityOptions return nil, fmt.Errorf("failed to initialize OIDC provider: %s", err) } - v := &Identity{ - log: log, - oc: &oauth2.Config{ - ClientID: id, - ClientSecret: secret, - Endpoint: provider.Endpoint(), - Scopes: []string{oidc.ScopeOfflineAccess, "mb:vehicle:mbdata:evstatus"}, - }, + oc := &oauth2.Config{ + ClientID: id, + ClientSecret: secret, + Endpoint: provider.Endpoint(), + Scopes: []string{oidc.ScopeOfflineAccess, "mb:vehicle:mbdata:evstatus"}, } - v.ReuseTokenSource = &ReuseTokenSource{cb: v.invalidToken} + v := &Identity{ + log: log, + oc: oc, + } + + ts := &ReuseTokenSource{ + oc: oc, + cb: v.invalidToken, + } + ts.Apply(nil) + + v.ReuseTokenSource = ts v.sessionSecret, err = generateSecret() for _, o := range options { diff --git a/vehicle/mercedes/tokensource.go b/vehicle/mercedes/tokensource.go index d67a1aa63..003b837aa 100644 --- a/vehicle/mercedes/tokensource.go +++ b/vehicle/mercedes/tokensource.go @@ -1,17 +1,16 @@ package mercedes import ( - "fmt" + "context" "sync" "golang.org/x/oauth2" ) -var ErrNotLoggedIn = fmt.Errorf("not logged in") - type ReuseTokenSource struct { mu sync.Mutex - t *oauth2.Token + oc *oauth2.Config + ts oauth2.TokenSource cb func() } @@ -19,17 +18,17 @@ func (ts *ReuseTokenSource) Token() (*oauth2.Token, error) { ts.mu.Lock() defer ts.mu.Unlock() - if ts.t.Valid() { - return ts.t, nil + t, err := ts.ts.Token() + if err != nil || !t.Valid() { + // invalid token callback + ts.cb() } - ts.cb() // invalid token callback - - return nil, ErrNotLoggedIn + return t, err } func (ts *ReuseTokenSource) Apply(t *oauth2.Token) { ts.mu.Lock() - ts.t = t + ts.ts = ts.oc.TokenSource(context.Background(), t) ts.mu.Unlock() }