-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgettoken.go
More file actions
61 lines (48 loc) · 1.45 KB
/
Copy pathgettoken.go
File metadata and controls
61 lines (48 loc) · 1.45 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
package envoy
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
func GetToken(ctx context.Context, username, password, serialNumber string) (string, error) {
client := &http.Client{}
loginURL := "https://entrez.enphaseenergy.com/login"
payload := fmt.Sprintf("user[email]=%s&user[password]=%s", username, password)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, loginURL, bytes.NewBufferString(payload))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("cloud login failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusFound {
return "", fmt.Errorf("login failed with status: %s", resp.Status)
}
tokenURL := fmt.Sprintf("https://entrez.enphaseenergy.com/installs/get_token?serial_num=%s", serialNumber)
req, _ = http.NewRequestWithContext(ctx, http.MethodGet, tokenURL, nil)
for _, cookie := range resp.Cookies() {
req.AddCookie(cookie)
}
resp, err = client.Do(req)
if err != nil {
return "", fmt.Errorf("token request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var tokenResponse struct {
Token string `json:"token"`
}
if err := json.Unmarshal(body, &tokenResponse); err != nil {
return string(body), nil
}
return tokenResponse.Token, nil
}