forked from PinataCloud/pinata-go-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
90 lines (78 loc) · 1.63 KB
/
auth.go
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
package main
import (
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"time"
)
func SaveJWT() error {
jwt, err := GetInput("Enter your Pinata JWT")
if err != nil {
return err
}
if jwt == "" {
return errors.New("JWT cannot be empty")
}
home, err := os.UserHomeDir()
if err != nil {
return err
}
p := filepath.Join(home, ".pinata-files-cli")
err = os.WriteFile(p, []byte(jwt), 0600)
if err != nil {
return err
}
host := GetHost()
url := fmt.Sprintf("https://%s/data/testAuthentication", host)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+jwt)
client := &http.Client{
Timeout: time.Duration(time.Second * 3),
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
status := resp.StatusCode
if status != 200 {
return errors.New("Authentication failed, make sure you are using the Pinata JWT")
}
fmt.Println("Authentication Successful!")
err = SetGateway("")
if err != nil {
return err
}
return nil
}
func findToken() ([]byte, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, err
}
dotFilePath := filepath.Join(homeDir, ".pinata-files-cli")
JWT, err := os.ReadFile(dotFilePath)
if err != nil {
if os.IsNotExist(err) {
return nil, errors.New("JWT not found. Please authorize first using the 'auth' command")
} else {
return nil, err
}
}
return JWT, err
}
func GetHost() string {
return GetEnv("PINATA_HOST", "api.pinata.cloud")
}
func GetEnv(key, defaultValue string) string {
value := os.Getenv(key)
if len(value) == 0 {
return defaultValue
}
return value
}