auth.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package api
  2. import "time"
  3. import "net/http"
  4. func (api *Client) ExchangeAuth() (*TokenPair, error) {
  5. result := &OAuthTokenResponse{}
  6. request := map[string] string {
  7. "client_id": api.options.ClientId,
  8. "client_secret": api.options.ClientSecret,
  9. "grant_type": "authorization_code",
  10. "code": api.options.AuthCode,
  11. "redirect_uri": api.options.RedirectURL,
  12. }
  13. err := api.doRequest("/oauth2/access_token", RequestOptions{
  14. Method: http.MethodPost,
  15. Body: request,
  16. Headers: makeHeaders(""),
  17. }, result)
  18. if err != nil {
  19. return nil, err
  20. }
  21. ret := &TokenPair{
  22. Access: result.AccessToken,
  23. Refresh: result.RefreshToken,
  24. }
  25. api.options.AccessToken = result.AccessToken
  26. api.options.RefreshToken = result.RefreshToken
  27. now := time.Now()
  28. api.options.ExpirationAt = now.Add(
  29. time.Second*time.Duration(result.ExpiresIn),
  30. )
  31. err = api.writeSecret()
  32. if err != nil {
  33. return nil, err
  34. }
  35. return ret, nil
  36. }
  37. func (api *Client) RefreshTokenIfExpired() error {
  38. if api.options.RefreshToken == "" {
  39. return nil
  40. }
  41. now := time.Now()
  42. if now.After(api.options.ExpirationAt) || now.Equal(api.options.ExpirationAt){
  43. _, err := api.RefreshToken()
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. return nil
  49. }
  50. func (api *Client) RefreshToken() (*OAuthTokenResponse, error) {
  51. result := new(OAuthTokenResponse)
  52. request := map[string]string{
  53. "client_id": api.options.ClientId,
  54. "client_secret": api.options.ClientSecret,
  55. "grant_type": "refresh_token",
  56. "refresh_token": api.options.RefreshToken,
  57. "redirect_uri": api.options.RedirectURL,
  58. }
  59. err := api.doRequest(
  60. "/oauth2/access_token",
  61. RequestOptions{
  62. Method: http.MethodPost,
  63. Body: request,
  64. Headers: makeHeaders(""),
  65. },
  66. result,
  67. )
  68. if err != nil {
  69. return nil, err
  70. }
  71. api.options.AccessToken = result.AccessToken
  72. api.options.RefreshToken = result.RefreshToken
  73. now := time.Now()
  74. api.options.ExpirationAt = now.Add(
  75. time.Second*time.Duration(result.ExpiresIn),
  76. )
  77. err = api.writeSecret()
  78. if err != nil {
  79. return nil, err
  80. }
  81. return result, nil
  82. }