forked from travelgateX/go-jwt-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
60 lines (50 loc) · 1.19 KB
/
client.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
package jwt
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type client interface {
GetBearer(userID, authHeader string) (string, error)
}
type GetBearerResponseStruct struct {
Email string `json:"email,omitempty"`
Token string `json:"token,omitempty"`
Status int `json:"status,omitempty"`
ErrorDescription string `json:"errorDescription,omitempty"`
}
type fetcherClient struct {
cli http.Client
url string
}
func newClient(url string) client {
cli := http.Client{}
return &fetcherClient{cli, url}
}
// GetBearer returns user bearer
func (a *fetcherClient) GetBearer(userID, authHeader string) (string, error) {
req, err := http.NewRequest("GET", a.url, nil)
if err != nil {
return "", err
}
req.Header.Add("Authorization", authHeader)
res, err := a.cli.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
resJSON := GetBearerResponseStruct{}
err = json.Unmarshal(body, &resJSON)
if err != nil {
return "", err
}
if resJSON.ErrorDescription != "" {
return "", fmt.Errorf("error fetching permissions data: %v", resJSON.ErrorDescription)
}
return resJSON.Token, nil
}