enbas/internal/client/token.go
Dan Anglin c6c711c29b
fix: update error handling
Changes:

- Move InvalidListRepliesPolicyError, InvalidTimelineCategory,
  InvalidStatusVisibility and InvalidStatusContentTypeError type to the
  model package.
- Clean up some code in regards to the parsing of the Enum types.
- Clean up the error messages sent back to the user.
- Use colons instead of semicolons when unwrapping error messages.
- Print errors to Standard Error (os.Stderr)
2024-06-02 11:35:43 +01:00

64 lines
1.5 KiB
Go

// SPDX-FileCopyrightText: 2024 Dan Anglin <d.n.i.anglin@gmail.com>
//
// SPDX-License-Identifier: GPL-3.0-or-later
package client
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"codeflow.dananglin.me.uk/apollo/enbas/internal"
)
var errEmptyAccessToken = errors.New("received an empty access token")
type tokenRequest struct {
RedirectUri string `json:"redirect_uri"`
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 {
params := tokenRequest{
RedirectUri: internal.RedirectUri,
ClientID: g.Authentication.ClientID,
ClientSecret: g.Authentication.ClientSecret,
GrantType: "authorization_code",
Code: code,
}
data, err := json.Marshal(params)
if err != nil {
return fmt.Errorf("unable to marshal the request body: %w", err)
}
requestBody := bytes.NewBuffer(data)
url := g.Authentication.Instance + "/oauth/token"
var response tokenResponse
if err := g.sendRequest(http.MethodPost, url, requestBody, &response); err != nil {
return fmt.Errorf("received an error after sending the token request: %w", err)
}
if response.AccessToken == "" {
return errEmptyAccessToken
}
g.Authentication.AccessToken = response.AccessToken
return nil
}