93 lines
2 KiB
Go
93 lines
2 KiB
Go
package api
|
|
|
|
import "time"
|
|
import "net/http"
|
|
|
|
func (api *Client) ExchangeAuth() (*TokenPair, error) {
|
|
result := &OAuthTokenResponse{}
|
|
request := map[string] string {
|
|
"client_id": api.options.ClientId,
|
|
"client_secret": api.options.ClientSecret,
|
|
"grant_type": "authorization_code",
|
|
"code": api.options.AuthCode,
|
|
"redirect_uri": api.options.RedirectURL,
|
|
}
|
|
|
|
err := api.doRequest("/oauth2/access_token", RequestOptions{
|
|
Method: http.MethodPost,
|
|
Body: request,
|
|
Headers: makeHeaders(""),
|
|
}, result)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
ret := &TokenPair{
|
|
Access: result.AccessToken,
|
|
Refresh: result.RefreshToken,
|
|
}
|
|
|
|
api.options.AccessToken = result.AccessToken
|
|
api.options.RefreshToken = result.RefreshToken
|
|
now := time.Now()
|
|
api.options.ExpirationAt = now.Add(
|
|
time.Second*time.Duration(result.ExpiresIn),
|
|
)
|
|
err = api.writeSecret()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return ret, nil
|
|
}
|
|
|
|
func (api *Client) RefreshTokenIfExpired() error {
|
|
if api.options.RefreshToken == "" {
|
|
return nil
|
|
}
|
|
|
|
now := time.Now()
|
|
if now.After(api.options.ExpirationAt) || now.Equal(api.options.ExpirationAt){
|
|
_, err := api.RefreshToken()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (api *Client) RefreshToken() (*OAuthTokenResponse, error) {
|
|
result := new(OAuthTokenResponse)
|
|
request := map[string]string{
|
|
"client_id": api.options.ClientId,
|
|
"client_secret": api.options.ClientSecret,
|
|
"grant_type": "refresh_token",
|
|
"refresh_token": api.options.RefreshToken,
|
|
"redirect_uri": api.options.RedirectURL,
|
|
}
|
|
|
|
err := api.doRequest(
|
|
"/oauth2/access_token",
|
|
RequestOptions{
|
|
Method: http.MethodPost,
|
|
Body: request,
|
|
Headers: makeHeaders(""),
|
|
},
|
|
result,
|
|
)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
api.options.AccessToken = result.AccessToken
|
|
api.options.RefreshToken = result.RefreshToken
|
|
now := time.Now()
|
|
api.options.ExpirationAt = now.Add(
|
|
time.Second*time.Duration(result.ExpiresIn),
|
|
)
|
|
err = api.writeSecret()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return result, nil
|
|
}
|