-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
261 lines (216 loc) · 6 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
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
package getstream
import (
"bytes"
"crypto"
"crypto/hmac"
"encoding/hex"
"errors"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
const (
// DefaultBaseURL is the default base URL for the stream chat api.
// It works like CDN style and connects you to the closest production server.
// By default, there is no real reason to change it. Use it only if you know what you are doing.
DefaultBaseURL = "https://chat.stream-io-api.com"
defaultTimeout = 6 * time.Second
)
func PtrTo[T any](v T) *T {
return &v
}
type Client struct {
apiKey string
apiSecret []byte
authToken string
baseUrl string
defaultTimeout time.Duration
httpClient *http.Client
logger Logger
}
func (c *Client) HttpClient() *http.Client {
return c.httpClient
}
func (c *Client) Logger() Logger {
return c.logger
}
func (c *Client) ApiKey() string {
return c.apiKey
}
func (c *Client) BaseUrl() string {
return c.baseUrl
}
func (c *Client) DefaultTimeout() time.Duration {
return c.defaultTimeout
}
type ClientOption func(c *Client)
// WithTimeout sets a custom timeout for all API requests
func WithTimeout(t time.Duration) ClientOption {
return func(c *Client) {
c.defaultTimeout = t
}
}
// WithBaseUrl sets the base URL for the client.
func WithBaseUrl(baseURL string) ClientOption {
return func(c *Client) {
c.baseUrl = baseURL
}
}
// WithLogger sets a custom logger for the client.
func WithLogger(logger Logger) ClientOption {
return func(c *Client) {
c.logger = logger
}
}
// With authToken sets the auth token for the client.
func WithAuthToken(authToken string) ClientOption {
return func(c *Client) {
c.authToken = authToken
}
}
type tokenOptions struct {
claims *Claims
expiration *time.Duration
}
type TokenOption func(*tokenOptions)
func WithExpiration(d time.Duration) TokenOption {
return func(t *tokenOptions) {
t.expiration = &d
}
}
func WithClaims(claims Claims) TokenOption {
return func(t *tokenOptions) {
t.claims = &claims
}
}
const (
EnvStreamApiKey = "STREAM_API_KEY"
EnvStreamApiSecret = "STREAM_API_SECRET"
EnvStreamBaseUrl = "STREAM_BASE_URL"
EnvStreamHttpTimeout = "STREAM_HTTP_TIMEOUT"
)
func newClientFromEnvVars(options ...ClientOption) (*Client, error) {
apiKey := os.Getenv(EnvStreamApiKey)
if apiKey == "" {
return nil, errors.New(EnvStreamApiKey + " is empty")
}
apiSecret := os.Getenv(EnvStreamApiSecret)
if apiSecret == "" {
return nil, errors.New(EnvStreamApiSecret + " is empty")
}
return newClient(apiKey, apiSecret, options...)
}
func newClient(apiKey, apiSecret string, options ...ClientOption) (*Client, error) {
if apiKey == "" {
return nil, errors.New("API key is empty")
}
if apiSecret == "" {
return nil, errors.New("API secret is empty")
}
baseURL := DefaultBaseURL
if baseURLEnv := os.Getenv(EnvStreamBaseUrl); strings.HasPrefix(baseURLEnv, "http") {
baseURL = baseURLEnv
}
client := &Client{
apiKey: apiKey,
apiSecret: []byte(apiSecret),
baseUrl: baseURL,
defaultTimeout: defaultTimeout,
}
if timeoutEnv := os.Getenv(EnvStreamHttpTimeout); timeoutEnv != "" {
i, err := strconv.Atoi(timeoutEnv)
if err != nil {
return nil, fmt.Errorf("cannot convert "+EnvStreamHttpTimeout+" into a valid timeout %w", err)
}
client.defaultTimeout = time.Duration(i) * time.Second
}
for _, fn := range options {
fn(client)
}
// Set default logger if not provided
if client.logger == nil {
client.logger = DefaultLoggerInstance
}
client.httpClient = &http.Client{
Timeout: client.defaultTimeout,
}
if client.authToken == "" {
token, err := client.createTokenWithClaims(jwt.MapClaims{"server": true})
if err != nil {
return nil, err
}
client.authToken = token
}
return client, nil
}
// Claims contains optional parameters for token creation.
type Claims struct {
Role string // Role assigned to the user
ChannelCIDs []string // Channel IDs the user has access to
CallCIDs []string // Call IDs the user has access to
CustomClaims map[string]interface{} // Additional custom claims
}
func (c *Client) createToken(userID string, claims *Claims, expiration *time.Duration) (string, error) {
if userID == "" {
return "", errors.New("user ID is required")
}
now := time.Now().Unix()
jwtClaims := jwt.MapClaims{
"user_id": userID,
"iat": now,
}
if expiration != nil && *expiration > 0 {
jwtClaims["exp"] = now + int64(expiration.Seconds())
}
if claims != nil {
for key, value := range claims.CustomClaims {
jwtClaims[key] = value
}
if claims.Role != "" {
jwtClaims["role"] = claims.Role
}
if len(claims.ChannelCIDs) > 0 {
jwtClaims["channel_cids"] = claims.ChannelCIDs
}
if len(claims.CallCIDs) > 0 {
jwtClaims["call_cids"] = claims.CallCIDs
}
}
return c.createTokenWithClaims(jwtClaims)
}
func (c *Client) createCallToken(userID string, claims *Claims, expiration *time.Duration) (string, error) {
if userID == "" {
return "", errors.New("user ID is required")
}
// Ensure that CallCIDs are included for call tokens
if claims == nil {
claims = &Claims{}
}
if len(claims.CallCIDs) == 0 {
return "", errors.New("call_cids are required for call tokens")
}
return c.createToken(userID, claims, expiration)
}
// createToken signs the JWT with the provided claims.
//
// Parameters:
// - claims (jwt.MapClaims): The claims to include in the token.
//
// Returns:
// - (string): The signed JWT token.
// - (error): An error object if signing fails.
func (c *Client) createTokenWithClaims(claims jwt.MapClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(c.apiSecret)
}
// VerifyWebhook validates if hmac signature is correct for message body.
func (c *Client) VerifyWebhook(body, signature []byte) (valid bool) {
mac := hmac.New(crypto.SHA256.New, c.apiSecret)
_, _ = mac.Write(body)
expectedMAC := hex.EncodeToString(mac.Sum(nil))
return bytes.Equal(signature, []byte(expectedMAC))
}