2024-02-25 06:41:13 +00:00
|
|
|
package client
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
type tokenRequest struct {
|
2024-06-25 12:39:39 +01:00
|
|
|
RedirectURI string `json:"redirect_uri"`
|
2024-02-25 06:41:13 +00:00
|
|
|
ClientID string `json:"client_id"`
|
|
|
|
ClientSecret string `json:"client_secret"`
|
|
|
|
GrantType string `json:"grant_type"`
|
|
|
|
Code string `json:"code"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type tokenResponse struct {
|
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
CreatedAt int `json:"created_at"`
|
|
|
|
Scope string `json:"scope"`
|
|
|
|
TokenType string `json:"token_type"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *Client) UpdateToken(code string) error {
|
2024-08-02 08:15:15 +01:00
|
|
|
tokenReq := tokenRequest{
|
2024-08-23 02:35:30 +01:00
|
|
|
RedirectURI: redirectURI,
|
2024-02-25 06:41:13 +00:00
|
|
|
ClientID: g.Authentication.ClientID,
|
|
|
|
ClientSecret: g.Authentication.ClientSecret,
|
|
|
|
GrantType: "authorization_code",
|
|
|
|
Code: code,
|
|
|
|
}
|
|
|
|
|
2024-08-02 08:15:15 +01:00
|
|
|
data, err := json.Marshal(tokenReq)
|
2024-02-25 06:41:13 +00:00
|
|
|
if err != nil {
|
2024-06-02 11:35:43 +01:00
|
|
|
return fmt.Errorf("unable to marshal the request body: %w", err)
|
2024-02-25 06:41:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
requestBody := bytes.NewBuffer(data)
|
|
|
|
url := g.Authentication.Instance + "/oauth/token"
|
|
|
|
|
|
|
|
var response tokenResponse
|
|
|
|
|
2024-08-02 08:15:15 +01:00
|
|
|
params := requestParameters{
|
|
|
|
httpMethod: http.MethodPost,
|
|
|
|
url: url,
|
|
|
|
requestBody: requestBody,
|
|
|
|
contentType: applicationJSON,
|
|
|
|
output: &response,
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := g.sendRequest(params); err != nil {
|
2024-06-02 11:35:43 +01:00
|
|
|
return fmt.Errorf("received an error after sending the token request: %w", err)
|
2024-02-25 06:41:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if response.AccessToken == "" {
|
2024-08-17 11:23:21 +01:00
|
|
|
return Error{"received an empty access token"}
|
2024-02-25 06:41:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
g.Authentication.AccessToken = response.AccessToken
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|