MCPcopy
hub / github.com/benbjohnson/wtf / authenticate

Method authenticate

http/server.go:273–312  ·  view source on GitHub ↗

authenticate is middleware for loading session data from a cookie or API key header.

(next http.Handler)

Source from the content-addressed store, hash-verified

271
272// authenticate is middleware for loading session data from a cookie or API key header.
273func (s *Server) authenticate(next http.Handler) http.Handler {
274 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
275 // Login via API key, if available.
276 if v := r.Header.Get("Authorization"); strings.HasPrefix(v, "Bearer ") {
277 apiKey := strings.TrimPrefix(v, "Bearer ")
278
279 // Lookup user by API key. Display error if not found.
280 // Otherwise set
281 users, _, err := s.UserService.FindUsers(r.Context(), wtf.UserFilter{APIKey: &apiKey})
282 if err != nil {
283 Error(w, r, err)
284 return
285 } else if len(users) == 0 {
286 Error(w, r, wtf.Errorf(wtf.EUNAUTHORIZED, "Invalid API key."))
287 return
288 }
289
290 // Update request context to include authenticated user.
291 r = r.WithContext(wtf.NewContextWithUser(r.Context(), users[0]))
292
293 // Delegate to next HTTP handler.
294 next.ServeHTTP(w, r)
295 return
296 }
297
298 // Read session from secure cookie.
299 session, _ := s.session(r)
300
301 // Read user, if available. Ignore if fetching assets.
302 if session.UserID != 0 {
303 if user, err := s.UserService.FindUserByID(r.Context(), session.UserID); err != nil {
304 log.Printf("cannot find session user: id=%d err=%s", session.UserID, err)
305 } else {
306 r = r.WithContext(wtf.NewContextWithUser(r.Context(), user))
307 }
308 }
309
310 next.ServeHTTP(w, r)
311 })
312}
313
314// requireNoAuth is middleware for requiring no authentication.
315// This is used if a user goes to log in but is already logged in.

Callers

nothing calls this directly

Calls 7

sessionMethod · 0.95
ErrorfFunction · 0.92
NewContextWithUserFunction · 0.92
ServeHTTPMethod · 0.80
ErrorFunction · 0.70
FindUsersMethod · 0.65
FindUserByIDMethod · 0.65

Tested by

no test coverage detected