-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
91 lines (76 loc) · 2.5 KB
/
auth.go
File metadata and controls
91 lines (76 loc) · 2.5 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package bbapi
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"strings"
gkhttp "github.com/raykavin/gokit/http"
)
const defaultClientCredentialsGrantType = "client_credentials"
// TokenResponse is the OAuth2 access token response from Banco do Brasil.
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope,omitempty"`
}
// ClientCredentialsRequest holds OAuth client credentials for Banco do Brasil.
type ClientCredentialsRequest struct {
GrantType string
ClientID string
ClientSecret string
Scope string
}
// Authenticate uses the credentials configured on the client and caches the
// access token for future API calls.
func (c *Client) Authenticate(ctx context.Context) (*TokenResponse, error) {
return c.AuthenticateClientCredentials(ctx, ClientCredentialsRequest{
ClientID: c.config.ClientID,
ClientSecret: c.config.ClientSecret,
Scope: c.config.scopeString(),
})
}
// AuthenticateClientCredentials performs the OAuth2 client_credentials flow.
func (c *Client) AuthenticateClientCredentials(
ctx context.Context,
req ClientCredentialsRequest,
) (*TokenResponse, error) {
clientID := strings.TrimSpace(req.ClientID)
if clientID == "" {
clientID = c.config.ClientID
}
clientSecret := strings.TrimSpace(req.ClientSecret)
if clientSecret == "" {
clientSecret = c.config.ClientSecret
}
form := url.Values{}
form.Set("grant_type", defaultString(req.GrantType, defaultClientCredentialsGrantType))
form.Set("client_id", clientID)
form.Set("client_secret", clientSecret)
if scope := strings.TrimSpace(req.Scope); scope != "" {
form.Set("scope", scope)
}
credentials := base64.StdEncoding.EncodeToString([]byte(clientID + ":" + clientSecret))
headers := map[string]string{gkhttp.HeaderAuthorization: "Basic " + credentials}
raw, statusCode, err := c.doFormDirect(ctx, c.authURL(), []byte(form.Encode()), headers)
if err != nil {
return nil, fmt.Errorf("bbapi: authenticate: %w", err)
}
if statusCode >= 400 {
return nil, parseAPIError(statusCode, raw)
}
var tokenResponse TokenResponse
if err := json.Unmarshal(raw, &tokenResponse); err != nil {
return nil, fmt.Errorf("bbapi: authenticate: decode response: %w", err)
}
c.SetTokenResponse(&tokenResponse)
return &tokenResponse, nil
}
func defaultString(value string, fallback string) string {
if strings.TrimSpace(value) == "" {
return fallback
}
return value
}