-
Notifications
You must be signed in to change notification settings - Fork 7
/
frontegg_client.go
265 lines (218 loc) · 6.93 KB
/
frontegg_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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package clients
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
// FronteggClient struct to encapsulate the http.Client with additional properties
type FronteggClient struct {
HTTPClient *http.Client
Token string
Email string
Endpoint string
TokenExpiry time.Time
Password string
}
// NewFronteggClient function for initializing a new Frontegg client with an auth token
func NewFronteggClient(ctx context.Context, password, endpoint string) (*FronteggClient, error) {
token, email, tokenExpiry, err := getToken(ctx, password, endpoint)
if err != nil {
return nil, fmt.Errorf("failed to get token: %v", err)
}
transport := &tokenTransport{
Token: token,
Transport: http.DefaultTransport,
}
client := &http.Client{Transport: transport}
return &FronteggClient{
HTTPClient: client,
Token: token,
Email: email,
Endpoint: endpoint,
TokenExpiry: tokenExpiry.Add(-time.Duration(0.5*float64(time.Until(tokenExpiry).Nanoseconds())) * time.Nanosecond),
Password: password,
}, nil
}
// tokenTransport struct to add the Authorization header to each request
type tokenTransport struct {
Token string
Transport http.RoundTripper
}
// RoundTrip method to execute the request with the token
func (t *tokenTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req2 := cloneRequest(req)
req2.Header.Set("Authorization", "Bearer "+t.Token)
return t.Transport.RoundTrip(req2)
}
// GetToken function to authenticate with the Frontegg API and retrieve a token
func getToken(ctx context.Context, password string, endpoint string) (string, string, time.Time, error) {
clientId, secretKey, err := parseAppPassword(password)
if err != nil {
return "", "", time.Time{}, err
}
adminEndpoint := fmt.Sprintf("%s/identity/resources/auth/v1/api-token", endpoint)
payload := map[string]string{
"clientId": clientId,
"secret": secretKey,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", "", time.Time{}, err
}
req, err := http.NewRequestWithContext(ctx, "POST", adminEndpoint, bytes.NewBuffer(payloadBytes))
if err != nil {
return "", "", time.Time{}, err
}
req.Header.Add("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", "", time.Time{}, err
}
defer resp.Body.Close()
// Read the response body into the 'body' variable
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", "", time.Time{}, err
}
if resp.StatusCode != http.StatusOK {
return "", "", time.Time{}, fmt.Errorf("authentication failed: %s", string(body))
}
var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil {
return "", "", time.Time{}, err
}
tokenString, ok := result["accessToken"].(string)
if !ok {
return "", "", time.Time{}, errors.New("access token not found in the response")
}
// Parse the token without verifying the signature.
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
return "", "", time.Time{}, fmt.Errorf("error parsing token: %v", err)
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return "", "", time.Time{}, errors.New("invalid token claims")
}
email, ok := claims["email"].(string)
if !ok {
return "", "", time.Time{}, errors.New("email claim not found in token")
}
var tokenExpiry time.Time
if expiresIn, ok := result["expiresIn"].(float64); ok {
tokenExpiry = time.Now().Add(time.Duration(expiresIn) * time.Second)
} else {
// Default expiry time if not provided in the response
tokenExpiry = time.Now().Add(1 * time.Hour)
}
return tokenString, email, tokenExpiry, nil
}
// Get the token from the FronteggClient
func (c *FronteggClient) GetToken() string {
return c.Token
}
// Get the email from the FronteggClient
func (c *FronteggClient) GetEmail() string {
return c.Email
}
// Get the endpoint from the FronteggClient
func (c *FronteggClient) GetEndpoint() string {
return c.Endpoint
}
// Get the token expiry from the FronteggClient
func (c *FronteggClient) GetTokenExpiry() time.Time {
return c.TokenExpiry
}
// Get the password from the FronteggClient
func (c *FronteggClient) GetPassword() string {
return c.Password
}
// cloneRequest creates a deep copy of an HTTP request to enable safe modifications
// while preserving concurrency safety, immutability, and reusability.
// https://stackoverflow.com/questions/62017146/http-request-clone-is-not-deep-clone
func cloneRequest(r *http.Request) *http.Request {
// Deep copy the request
r2 := new(http.Request)
*r2 = *r
// Deep copy the URL
r2.URL = new(url.URL)
*r2.URL = *r.URL
// Deep copy the Header
r2.Header = make(http.Header, len(r.Header))
for k, s := range r.Header {
r2.Header[k] = append([]string(nil), s...)
}
return r2
}
func parseAppPassword(password string) (string, string, error) {
strippedPassword := strings.TrimPrefix(password, "mzp_")
var clientId, secretKey string
re := regexp.MustCompile("[^0-9a-fA-F]")
filteredChars := re.ReplaceAllString(strippedPassword, "")
if len(filteredChars) < 64 {
return "", "", fmt.Errorf("invalid app password length: %d", len(filteredChars))
}
clientId = formatDashlessUuid(filteredChars[0:32])
secretKey = formatDashlessUuid(filteredChars[32:])
return clientId, secretKey, nil
}
func formatDashlessUuid(dashlessUuid string) string {
parts := []string{
dashlessUuid[0:8],
dashlessUuid[8:12],
dashlessUuid[12:16],
dashlessUuid[16:20],
dashlessUuid[20:],
}
return strings.Join(parts, "-")
}
func (c *FronteggClient) NeedsTokenRefresh() error {
if time.Now().After(c.TokenExpiry) {
return fmt.Errorf("token expired and needs refresh")
}
return nil
}
func (c *FronteggClient) RefreshToken() error {
log.Printf("[DEBUG] Refreshing Frontegg: %v\n", c)
token, email, tokenExpiry, err := getToken(context.Background(), c.Password, c.Endpoint)
if err != nil {
return fmt.Errorf("failed to get token: %v", err)
}
transport := &tokenTransport{
Token: token,
Transport: http.DefaultTransport,
}
client := &http.Client{Transport: transport}
c.HTTPClient = client
c.Token = token
c.Email = email
c.TokenExpiry = tokenExpiry.Add(-time.Duration(0.5*float64(time.Until(tokenExpiry).Nanoseconds())) * time.Nanosecond)
return nil
}
// Helper function to handle API errors
func HandleApiError(resp *http.Response) error {
responseBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode == http.StatusNotFound {
return nil
}
return fmt.Errorf("API error: %s - %s", resp.Status, string(responseBody))
}
// Helper function to perform HTTP requests
func FronteggRequest(ctx context.Context, client *FronteggClient, method, url string, body []byte) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
return client.HTTPClient.Do(req)
}