aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/cli/auth/token.go
blob: d6f5e6dfa43b3377cde31d29ea3f840e87530adc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

package auth

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
)

type TokenResponse struct {
	AccessToken string `json:"access_token"`
	IDToken     string `json:"id_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int    `json:"expires_in"`
}

type TokenRetriever struct {
	Authenticator *Authenticator
	Secrets       SecretStore
	Client        *http.Client
}

// Delete deletes the given system from the secrets' storage.
func (t *TokenRetriever) Delete(system string) error {
	return t.Secrets.Delete(SecretsNamespace, system)
}

// Refresh gets a new access token from the provided refresh token,
// The request is used the default client_id and endpoint for device authentication.
func (t *TokenRetriever) Refresh(ctx context.Context, system string) (TokenResponse, error) {
	// get stored refresh token:
	refreshToken, err := t.Secrets.Get(SecretsNamespace, system)
	if err != nil {
		return TokenResponse{}, fmt.Errorf("cannot get the stored refresh token: %w", err)
	}
	if refreshToken == "" {
		return TokenResponse{}, errors.New("cannot use the stored refresh token: the token is empty")
	}
	// get access token:
	r, err := t.Client.PostForm(t.Authenticator.OauthTokenEndpoint, url.Values{
		"grant_type":    {"refresh_token"},
		"client_id":     {t.Authenticator.ClientID},
		"refresh_token": {refreshToken},
	})
	if err != nil {
		return TokenResponse{}, fmt.Errorf("cannot get a new access token from the refresh token: %w", err)
	}

	defer r.Body.Close()
	if r.StatusCode != http.StatusOK {
		b, _ := io.ReadAll(r.Body)
		res := struct {
			Description string `json:"error_description"`
		}{}
		if json.Unmarshal(b, &res) == nil {
			return TokenResponse{}, errors.New(strings.ToLower(strings.TrimSuffix(res.Description, ".")))
		}
		return TokenResponse{}, fmt.Errorf("cannot get a new access token from the refresh token: %s", string(b))
	}

	var res TokenResponse
	err = json.NewDecoder(r.Body).Decode(&res)
	if err != nil {
		return TokenResponse{}, fmt.Errorf("cannot decode response: %w", err)
	}

	return res, nil
}