-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.go
398 lines (321 loc) · 10.6 KB
/
lib.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package authlib
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"time"
"github.com/go-chi/chi/middleware"
"github.com/lafriks/ttlcache/v3"
"go.uber.org/zap"
)
type UserContextkey string
const SESSION_EXPIRY = 5 * time.Minute
const CTX_USER_KEY UserContextkey = "currentuser"
type AuthGateway struct {
Middlewares Middlewares
Handlers Handlers
// whoAmIURL string
logger *zap.SugaredLogger
cache *ttlcache.Cache[string, string]
}
type Middlewares struct {
loginPageURL string
serviceID string
sessionExpiry int
logger *zap.SugaredLogger
cache *ttlcache.Cache[string, string]
}
type Handlers struct {
loginPageURL string
homePageURL string
whoAmIURL string
userRefreshURL string
apikey string
serviceID string
CookiePath string
sessionExpiry int
logger *zap.SugaredLogger
cache *ttlcache.Cache[string, string]
}
type AuthGatewayOption struct {
Logger *zap.SugaredLogger
RedisURL string
LoginURL string
WhoAmIURL string
HomePageURL string
UserRefreshURL string
APIKey string
ServiceID string
Secret string
CookiePath string
SessionExpiry int
}
func NewAuthGateway(o AuthGatewayOption) (*AuthGateway, error) {
if o.LoginURL == "" {
return nil, fmt.Errorf("login_url must be specified in AuthGatewayOption")
}
if o.WhoAmIURL == "" {
return nil, fmt.Errorf("whoami_url must be specified in AuthGatewayOption")
}
if o.CookiePath == "" {
o.CookiePath = "/"
}
if o.Logger == nil {
logger, err := zap.NewProduction()
if err != nil {
return nil, err
}
o.Logger = logger.Sugar()
}
// if o.RedisURL == "" {
// return nil, fmt.Errorf("a valid redis url must be provided in AuthGatewayOption")
// }
//redis://<user>:<pass>@localhost:6379/<db>
// opt, err := redis.ParseURL(o.RedisURL)
// if err != nil {
// return nil, fmt.Errorf("auth_gateway_lib could not parse RedisURL provided: %s", err)
// }
// rdb := redis.NewClient(opt)
rdb := ttlcache.New[string, string]()
return &AuthGateway{
logger: o.Logger,
cache: rdb,
Middlewares: Middlewares{
loginPageURL: o.LoginURL,
cache: rdb,
logger: o.Logger,
serviceID: o.ServiceID,
sessionExpiry: o.SessionExpiry,
},
Handlers: Handlers{
loginPageURL: o.LoginURL,
whoAmIURL: o.WhoAmIURL,
homePageURL: o.HomePageURL,
apikey: o.APIKey,
serviceID: o.ServiceID,
cache: rdb,
logger: o.Logger,
CookiePath: o.CookiePath,
sessionExpiry: o.SessionExpiry,
userRefreshURL: o.UserRefreshURL,
}}, nil
}
func (h *Handlers) GetActiveDomain(r *http.Request) (string, error) {
requestLogger := h.logger.With("function name", "GetActiveDomain")
cookie, err := r.Cookie("sid")
if err != nil {
requestLogger.With("err", err).Errorf("Error occured while fetching sid cookie: %s", err)
return "", err
}
//sid cookie exists. let's fetch user
requestLogger.Info("sid cookie exists. Let's fetch user")
cacheEntry, err := h.cache.Get(cookie.Value)
if cacheEntry == nil {
requestLogger.Error("user not found in cache")
return "", fmt.Errorf("user not found in cache")
}
if err != nil {
requestLogger.Errorf("Error occured while fetching user json from cache: %s", err)
return "", err
}
user := User{}
userJSON := cacheEntry.Value()
err = json.Unmarshal([]byte(userJSON), &user)
if err != nil {
requestLogger.Errorf("Could not parse user json: %s", err)
requestLogger.Info("Continue without adding logged in user info")
return "", fmt.Errorf("could not parse user json: %s", err)
}
//User is valid.
return user.ActiveDomain, nil
}
func (h *Handlers) SetActiveDomain(
r *http.Request, activeDomain string) error {
requestLogger := h.logger.With(
"function name", "SetActiveDomain",
"domain", activeDomain)
cookie, err := r.Cookie("sid")
if err != nil {
requestLogger.With("err", err).Errorf("Error occured while fetching sid cookie: %s", err)
return err
}
//sid cookie exists. let's fetch user
requestLogger.Info("sid cookie exists. Let's fetch user")
cacheEntry, err := h.cache.Get(cookie.Value)
if cacheEntry == nil {
requestLogger.Error("user not found in cache")
return fmt.Errorf("user not found in cache")
}
if err != nil {
requestLogger.Errorf("Error occured while fetching user json from cache: %s", err)
return err
}
user := User{}
userJSON := cacheEntry.Value()
err = json.Unmarshal([]byte(userJSON), &user)
if err != nil {
requestLogger.Errorf("Could not parse user json: %s", err)
requestLogger.Info("Continue without adding logged in user info")
return fmt.Errorf("could not parse user json: %s", err)
}
//User is valid.
if _, ok := user.IAMRoles[activeDomain]; !ok {
return fmt.Errorf("user does not have access to this domain")
}
requestLogger.Info("Updating user's active domain")
user.ActiveDomain = activeDomain
usr, _ := json.Marshal(user)
// s.cache.Set(ctx, sessionID.String(), string(usr), SESSION_EXPIRY)
h.cache.Set(cookie.Value, string(usr), time.Duration(h.sessionExpiry))
return nil
}
func (h *Handlers) GetUser(tk string) (*User, error) {
u := User{}
requestLogger := h.logger
requestLogger.Debug("Constructing request to fetch details of logged in user . . .")
req, err := http.NewRequest("GET", h.whoAmIURL, nil)
if err != nil {
requestLogger.Error("Error occured while creating get request to fetch details of logged in user: %s", err)
return nil, fmt.Errorf("error creating user request: %s", err)
}
req.Header.Add("X-API-KEY", h.apikey)
whoAmIURL, _ := url.Parse(h.whoAmIURL)
q := whoAmIURL.Query()
q.Set("tk", tk)
q.Set("service", h.serviceID)
req.URL.RawQuery = q.Encode()
fmt.Printf("\nMaking WhoAmI request: %s\n\n", req.URL.RawQuery)
requestLogger.With(
"tk", tk,
"target", h.whoAmIURL,
"raw-url", req.URL.String(),
).Debug("Initiating request to fetch details of logged in user . . .")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
requestLogger.With(
"error", err,
"url_called", req.URL.String(),
).Error("Errored when sending request to the server")
return nil, fmt.Errorf("failed to fetch details of newly logged in user")
}
defer resp.Body.Close()
resp_body, _ := io.ReadAll(resp.Body)
requestLogger.Info("Auth server has responded")
requestLogger.Info("resp_body => %s", string(resp_body))
err = json.Unmarshal(resp_body, &u)
if err != nil {
requestLogger.With(
"error", err,
"url_called", req.URL.String(),
).Error("Could not parse response ")
return nil, fmt.Errorf("failed to fetch details of newly logged in user")
}
requestLogger.Info("Parsed Auth server response")
return &u, nil
}
func (s *Middlewares) LoginRequired(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ctx := context.Background()
redirectURL := struct {
URL string
}{
URL: fmt.Sprintf("%s?service=%s&next=%s%s", s.loginPageURL, s.serviceID, os.Getenv("URL_PREFIX"), r.URL.Path),
}
resp := JSONResponse{
Error: true,
Message: "user not logged in",
Data: redirectURL,
}
reqID := middleware.GetReqID(r.Context())
requestLogger := s.logger.With("request-id", reqID)
requestLogger.Info("Check if sid (session id) cookie exists")
cookie, err := r.Cookie("sid")
if err != nil {
requestLogger.Errorf("Error occured while fetching sid cookie: %s", err)
requestLogger.Infof("sid cookie not found. Redirecting to login screen: %s", redirectURL)
writeJSON(w, http.StatusUnauthorized, resp)
return
}
//sid cookie exists. let's fetch user
requestLogger.Info("sid cookie exists. Let's fetch user")
cacheEntry, err := s.cache.Get(cookie.Value)
if cacheEntry == nil {
requestLogger.Errorf("Error occured while fetching user json from cache: %s", err)
requestLogger.Infof("Error occured while fetching user from cache. Redirecting to login screen: %s", redirectURL)
writeJSON(w, http.StatusUnauthorized, resp)
return
}
userJSON := cacheEntry.Value()
// userJSON, err := s.cache.Get(ctx, cookie.Value).Result()
// if err != nil {
// requestLogger.Errorf("Error occured while fetching user json from cache: %s", err)
// requestLogger.Infof("Error occured while fetching user from cache. Redirecting to login screen: %s", redirectURL)
// writeJSON(w, http.StatusUnauthorized, resp)
// return
// }
user := User{}
err = json.Unmarshal([]byte(userJSON), &user)
if err != nil {
requestLogger.Errorf("Could not parse user json: %s", err)
requestLogger.Infof("Could not parse user JSON. Redirecting to login screen: %s", redirectURL)
writeJSON(w, http.StatusUnauthorized, resp)
return
}
//User is valid. Extend session expiry
s.cache.Set(cookie.Value, userJSON, time.Duration(s.sessionExpiry))
//create a new request context containing the authenticated user
ctxWithUser := context.WithValue(r.Context(), CTX_USER_KEY, user)
//create a new request using that new context
rWithUser := r.WithContext(ctxWithUser)
h.ServeHTTP(w, rWithUser)
})
}
func (s *Middlewares) AddLoggedInUserDetails(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := r.Header.Get("x-req-id")
requestLogger := s.logger.With("request-id", reqID)
requestLogger.Info("Check if sid (session id) cookie exists")
cookie, err := r.Cookie("sid")
if err != nil {
requestLogger.Errorf("Error occured while fetching sid cookie: %s", err)
requestLogger.Info("Continue without adding logged in user info")
h.ServeHTTP(w, r)
return
}
//sid cookie exists. let's fetch user
requestLogger.Info("sid cookie exists. Let's fetch user")
cacheEntry, err := s.cache.Get(cookie.Value)
if cacheEntry == nil {
// requestLogger.Errorf("Error occured while fetching user json from cache: %s", err)
requestLogger.Info("Continue without adding logged in user info")
h.ServeHTTP(w, r)
return
}
if err != nil {
requestLogger.Errorf("Error occured while fetching user json from cache: %s", err)
requestLogger.Info("Continue without adding logged in user info")
h.ServeHTTP(w, r)
return
}
user := User{}
userJSON := cacheEntry.Value()
err = json.Unmarshal([]byte(userJSON), &user)
if err != nil {
requestLogger.Errorf("Could not parse user json: %s", err)
requestLogger.Info("Continue without adding logged in user info")
h.ServeHTTP(w, r)
return
}
//User is valid.
//create a new request context containing the authenticated user
ctxWithUser := context.WithValue(r.Context(), CTX_USER_KEY, user)
//create a new request using that new context
rWithUser := r.WithContext(ctxWithUser)
h.ServeHTTP(w, rWithUser)
})
}