62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package slash
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type oauth struct {
|
|
AccessToken string `json:"access_token"`
|
|
TokenType string `json:"token_type"`
|
|
ExpiresIn int `json:"expires_in"`
|
|
Scope string `json:"scope"`
|
|
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
func (o oauth) header() string {
|
|
return fmt.Sprintf("%s %s", o.TokenType, o.AccessToken)
|
|
}
|
|
|
|
func (c *Client) checkToken(ctx context.Context) error {
|
|
if time.Now().Before(c.oauth.ExpiresAt) {
|
|
return nil
|
|
}
|
|
|
|
data := url.Values{
|
|
"grant_type": []string{"client_credentials"},
|
|
"scope": []string{"applications.commands.update"},
|
|
}
|
|
|
|
endpoint := baseEndpoint + "oauth2/token"
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(data.Encode()))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
req.SetBasicAuth(c.clientID, c.clientSecret)
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return errors.New("could not get client credentials token")
|
|
}
|
|
|
|
var oauth oauth
|
|
if err := json.NewDecoder(resp.Body).Decode(&oauth); err != nil {
|
|
return err
|
|
}
|
|
oauth.ExpiresAt = time.Now().Add(time.Second * time.Duration(oauth.ExpiresIn))
|
|
c.oauth = oauth
|
|
return nil
|
|
}
|