-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.go
More file actions
77 lines (69 loc) · 2.04 KB
/
Copy pathtoken.go
File metadata and controls
77 lines (69 loc) · 2.04 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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/hashicorp/go-retryablehttp"
"golang.org/x/oauth2"
)
var (
tokenExtraHeaders = map[string]string{
"User-Agent": "Dalvik/2.1.0 (Linux; U; Android 14; SM-G991B Build/G991BXXUEGXJE",
}
tokenExtraValues = map[string]string{
"active_x1_account_count": "true",
"partner_id": "comcast",
"mso_partner_hint": "true",
"scope": "profile",
"rm_hint": "true",
}
)
type TokenExtra struct {
IDToken string `json:"id_token"`
ActivityID string `json:"activity_id"`
}
func tokenRequest(ctx context.Context, client *retryablehttp.Client, refreshToken, clientID, clientSecret, applicationID string) (*oauth2.Token, *TokenExtra, error) {
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("refresh_token", refreshToken)
data.Set("client_id", clientID)
data.Set("client_secret", clientSecret)
if applicationID != "" {
data.Set("application_id", applicationID)
}
for key, value := range tokenExtraValues {
data.Set(key, value)
}
req, err := retryablehttp.NewRequestWithContext(ctx, "POST", tokenURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for key, value := range tokenExtraHeaders {
req.Header.Set(key, value)
}
resp, err := client.Do(req)
if err != nil {
return nil, nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
// Check for HTTP errors
if resp.StatusCode != http.StatusOK {
return nil, nil, fmt.Errorf("token request failed with status %d: %s", resp.StatusCode, body)
}
// Parse the token response
var raw struct {
oauth2.Token
TokenExtra
}
if err := json.NewDecoder(bytes.NewReader(body)).Decode(&raw); err != nil {
return nil, nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &raw.Token, &raw.TokenExtra, nil
}