/ internal / gtsclient / token.go
token.go
 1  package gtsclient
 2  
 3  import (
 4  	"bytes"
 5  	"encoding/json"
 6  	"fmt"
 7  	"net/http"
 8  
 9  	"codeflow.dananglin.me.uk/apollo/enbas/internal/config"
10  )
11  
12  type tokenRequest struct {
13  	RedirectURI  string `json:"redirect_uri"`
14  	ClientID     string `json:"client_id"`
15  	ClientSecret string `json:"client_secret"`
16  	GrantType    string `json:"grant_type"`
17  	Code         string `json:"code"`
18  }
19  
20  type tokenResponse struct {
21  	AccessToken string `json:"access_token"`
22  	CreatedAt   int    `json:"created_at"`
23  	Scope       string `json:"scope"`
24  	TokenType   string `json:"token_type"`
25  }
26  
27  func (g *GTSClient) UpdateToken(code string, auth *config.Credentials) error {
28  	tokenReq := tokenRequest{
29  		RedirectURI:  redirectURI,
30  		ClientID:     g.authentication.ClientID,
31  		ClientSecret: g.authentication.ClientSecret,
32  		GrantType:    "authorization_code",
33  		Code:         code,
34  	}
35  
36  	data, err := json.Marshal(tokenReq)
37  	if err != nil {
38  		return fmt.Errorf("unable to marshal the request body: %w", err)
39  	}
40  
41  	requestBody := bytes.NewBuffer(data)
42  	url := g.authentication.Instance + "/oauth/token"
43  
44  	var response tokenResponse
45  
46  	params := requestParameters{
47  		httpMethod:  http.MethodPost,
48  		url:         url,
49  		requestBody: requestBody,
50  		contentType: applicationJSON,
51  		output:      &response,
52  	}
53  
54  	if err := g.sendRequest(params); err != nil {
55  		return fmt.Errorf("received an error after sending the token request: %w", err)
56  	}
57  
58  	if response.AccessToken == "" {
59  		return Error{"received an empty access token"}
60  	}
61  
62  	g.authentication.AccessToken = response.AccessToken
63  
64  	*auth = g.authentication
65  
66  	return nil
67  }