-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathauth.go
117 lines (97 loc) · 2.45 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package api
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"github.com/spf13/viper"
)
type LoginRequest struct {
Otp string `json:"otp"`
}
type LoginResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
func FetchAccessToken() (*LoginResponse, error) {
api_url := viper.GetString("api_url")
client := &http.Client{}
r, err := http.NewRequest("POST", api_url+"/v1/auth/refresh", bytes.NewBuffer([]byte{}))
r.Header.Add("X-Refresh-Token", viper.GetString("refresh_token"))
if err != nil {
return nil, err
}
resp, err := client.Do(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, errors.New("invalid refresh token")
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var creds LoginResponse
err = json.Unmarshal(body, &creds)
return &creds, err
}
func LoginWithCode(code string) (*LoginResponse, error) {
api_url := viper.GetString("api_url")
req, err := json.Marshal(LoginRequest{Otp: code})
if err != nil {
return nil, err
}
resp, err := http.Post(api_url+"/v1/auth/otp/login", "application/json", bytes.NewReader(req))
if err != nil {
return nil, err
}
if resp.StatusCode == 403 {
return nil, errors.New("invalid login code, please refresh your browser then try again")
}
if resp.StatusCode != 200 {
return nil, errors.New(resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var creds LoginResponse
err = json.Unmarshal(body, &creds)
if err != nil {
return nil, err
}
return &creds, nil
}
func fetchWithAuth(method string, url string) ([]byte, error) {
body, code, err := fetchWithAuthAndPayload(method, url, []byte{})
if err != nil {
return nil, err
}
if code != 200 {
return nil, fmt.Errorf("failed to %s to %s\nResponse: %d %s", method, url, code, string(body))
}
return body, err
}
func fetchWithAuthAndPayload(method string, url string, payload []byte) ([]byte, int, error) {
api_url := viper.GetString("api_url")
client := &http.Client{}
r, err := http.NewRequest(method, api_url+url, bytes.NewBuffer(payload))
if err != nil {
return nil, 0, err
}
r.Header.Add("Authorization", "Bearer "+viper.GetString("access_token"))
resp, err := client.Do(r)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, 0, err
}
return body, resp.StatusCode, nil
}