-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.go
99 lines (79 loc) · 2.49 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
package rize
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/rizefinance/rize-go-sdk/internal"
)
// Handles all Auth related functionality
type authService service
// AuthTokenResponse is the response format received when fetching an Auth token
type AuthTokenResponse struct {
Token string `json:"token"`
}
// GetToken generates an authorization token if the existing token is expired or not found.
// Otherwise, it will return the existing active token,
func (a *authService) GetToken(ctx context.Context) (*AuthTokenResponse, error) {
// Check for missing or expired token
if a.client.TokenCache.Token == "" || isExpired(a.client.TokenCache) {
log.Println("Token is expired or does not exist. Fetching new token...")
refreshToken, err := a.buildRefreshToken()
if err != nil {
return nil, err
}
// Store the refresh token (valid for 30 seconds)
a.client.TokenCache.Token = refreshToken
res, err := a.client.doRequest(ctx, http.MethodPost, "auth", nil, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
response := &AuthTokenResponse{}
if err = json.Unmarshal(body, response); err != nil {
return nil, err
}
log.Printf("Token response %+v\n", response)
// Validate token exists
if response.Token == "" {
return nil, fmt.Errorf("Error fetching auth token")
}
// Save token to client. Auth token is valid for 24hrs
a.client.TokenCache.Timestamp = time.Now().Unix()
a.client.TokenCache.Token = response.Token
return response, nil
}
log.Println("Token is valid. Using existing auth token...")
return &AuthTokenResponse{Token: a.client.TokenCache.Token}, nil
}
// Generates a JWT refresh token
func (a *authService) buildRefreshToken() (string, error) {
// Encode JWT token with current time and programUID
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"iat": time.Now().Unix(),
"sub": a.client.cfg.ProgramUID,
})
// Sign JWT token with the HMAC key
signedToken, err := token.SignedString([]byte(a.client.cfg.HMACKey))
if err != nil {
return "", err
}
log.Printf("Signed token %s\n", signedToken)
return signedToken, nil
}
// Checks to see if the current Auth token should be refreshed
func isExpired(tc *TokenCache) bool {
currentTime := time.Now().Unix()
if tc.Timestamp == 0 || ((currentTime - tc.Timestamp) > internal.TokenMaxAge) {
return true
}
return false
}