Diffdown is a real-time collaborative Markdown editor/previewer built on the AT Protocol diffdown.com
at main 42 lines 1.1 kB view raw
1package middleware 2 3import ( 4 "context" 5 "log" 6 "net/http" 7 "time" 8 9 "github.com/limeleaf/diffdown/internal/auth" 10) 11 12func Logger(next http.Handler) http.Handler { 13 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 14 start := time.Now() 15 next.ServeHTTP(w, r) 16 log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start)) 17 }) 18} 19 20// InjectUser adds user ID to context if logged in. Does not block. 21func InjectUser(next http.Handler) http.Handler { 22 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 23 userID := auth.GetUserID(r) 24 if userID != "" { 25 ctx := context.WithValue(r.Context(), auth.UserIDKey, userID) 26 r = r.WithContext(ctx) 27 } 28 next.ServeHTTP(w, r) 29 }) 30} 31 32// RequireAuth blocks unauthenticated requests. 33func RequireAuth(next http.Handler) http.Handler { 34 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 35 userID := auth.UserIDFromContext(r.Context()) 36 if userID == "" { 37 http.Redirect(w, r, "/auth/login", http.StatusSeeOther) 38 return 39 } 40 next.ServeHTTP(w, r) 41 }) 42}