-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
87 lines (82 loc) · 2.29 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
package sypht
import (
"encoding/base64"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
var gracePeriod = 10
// RefreshToken refreshes api token and updates Sypht client instance
func (s *Client) RefreshToken() (token string, err error) {
var req *http.Request
var payload *strings.Reader
if strings.Contains(s.config.authURL, "/oauth2") {
payload = strings.NewReader("client_id=" + s.config.clientID + "&grant_type=client_credentials")
basicAuthSlug := base64.StdEncoding.EncodeToString([]byte(strings.Join([]string{s.config.clientID, s.config.clientSecret}, ":")))
req, err = http.NewRequest("POST", s.config.authURL, payload)
if err != nil {
log.Println(err)
return
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Authorization", "Basic "+basicAuthSlug)
} else {
payload = strings.NewReader(strings.Join([]string{"{\n \"client_id\":\"",
s.config.clientID,
"\",\n \"client_secret\":\"",
s.config.clientSecret,
"\",\n \"audience\":\"https://api.sypht.com\",\n \"grant_type\":\"client_credentials\" \n}"}, ""))
req, err = http.NewRequest("POST", s.config.authURL, payload)
if err != nil {
log.Println(err)
return
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
}
res, err := s.httpClient.Do(req)
if err != nil {
log.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println(err)
return
}
var dat map[string]interface{}
err = json.Unmarshal(body, &dat)
if err != nil {
log.Panic("invalid credentials, please check your api key.")
}
tokenInterface, ok := dat["access_token"]
if !ok {
log.Panic("invalid credentials, please check your api key.")
}
token = string(tokenInterface.(string))
s.mutex.Lock()
s.apiToken = token
s.tokenUpdatedAt = time.Now()
s.mutex.Unlock()
return
}
func (s *Client) getToken() (token string) {
s.mutex.RLock()
if time.Since(s.tokenUpdatedAt) >= time.Hour*24-time.Minute*time.Duration(gracePeriod) {
s.mutex.RUnlock()
token, err := s.RefreshToken()
if err != nil {
log.Printf("Error refreshing token : %v", err)
}
return token
}
s.mutex.RLock()
token = s.apiToken
s.mutex.RUnlock()
return
}