Fix token refresh

This commit is contained in:
andig 2022-01-27 15:26:48 +01:00
parent a0d69e7ae0
commit b4ffc30087
2 changed files with 27 additions and 20 deletions

View file

@ -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 {

View file

@ -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()
}