123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- 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
- }
|