Skip to content

Commit

Permalink
Update refresh token call in client
Browse files Browse the repository at this point in the history
Signed-off-by: Marek Aufart <[email protected]>
  • Loading branch information
aufi committed Feb 6, 2024
1 parent dab0f9e commit 4860b42
Showing 1 changed file with 28 additions and 23 deletions.
51 changes: 28 additions & 23 deletions binding/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -681,31 +681,24 @@ func (r *Client) send(rb func() (*http.Request, error)) (response *http.Response
err = liberr.Wrap(err)
return
}
} else if r.refreshToken(response.StatusCode, request.URL.Path) {
unAuthErr := errors.New("401 Unauthorized")
if i < r.Retry {
Log.Info("|401| Unauthorized, refreshing auth token.")
token := api.Login{Refresh: r.token.Refresh}
refreshErr := r.Post(api.AuthRefreshRoot, &token)
if refreshErr != nil {
Log.Error(refreshErr, "Token refresh failed.")
time.Sleep(RetryDelay)
} else {
r.SetToken(token)
}
continue
} else {
r.Error = liberr.Wrap(unAuthErr)
err = r.Error
return
}
} else {
Log.Info(
fmt.Sprintf(
"|%d| %s %s",
response.StatusCode,
request.Method,
request.URL.Path))
if response.StatusCode == http.StatusUnauthorized {
refreshed, nErr := r.refreshToken(request)
if nErr != nil {
r.Error = liberr.Wrap(nErr)
err = r.Error
return
}
if refreshed {
continue
}
}
break
}
}
Expand Down Expand Up @@ -817,9 +810,21 @@ func (f *Field) disposition() (d string) {
return
}

func (r *Client) refreshToken(status int, path string) (refresh bool) {
if status == 401 && !strings.HasSuffix(path, api.AuthRefreshRoot) && r.token.Refresh != "" {
refresh = true
}
return
// refreshToken refreshes the token.
func (r *Client) refreshToken(request *http.Request) (refreshed bool, err error) {
if r.token.Token == "" ||
strings.HasSuffix(request.URL.Path, api.AuthRefreshRoot) {
return
}
login := &api.Login{Refresh: r.token.Refresh}
err = r.Post(api.AuthRefreshRoot, login)
if err == nil {
r.token.Token = login.Token
refreshed = true
return
}
if errors.Is(err, &RestError{}) {
err = nil
}
return
}

0 comments on commit 4860b42

Please sign in to comment.