Download this file
| 1 | package notifications |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | // Rastrillo reauthorizes on reconnect. Notification streams must also check |
| 10 | // device and subscription expiry before every write on an existing connection. |
| 11 | func GuardLive(next http.Handler, allow func(*http.Request, string) bool) http.Handler { |
| 12 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 13 | var keys []string |
| 14 | for _, token := range r.URL.Query()["t"] { |
| 15 | topic, _, _ := strings.Cut(token, "@") |
| 16 | if key, ok := strings.CutPrefix(topic, "notifications/"); ok { |
| 17 | keys = append(keys, key) |
| 18 | } |
| 19 | } |
| 20 | if len(keys) == 0 { |
| 21 | next.ServeHTTP(w, r) |
| 22 | return |
| 23 | } |
| 24 | next.ServeHTTP(&guardedWriter{ResponseWriter: w, allowed: func() bool { |
| 25 | for _, key := range keys { |
| 26 | if !allow(r, key) { |
| 27 | return false |
| 28 | } |
| 29 | } |
| 30 | return true |
| 31 | }}, r) |
| 32 | }) |
| 33 | } |
| 34 | |
| 35 | type guardedWriter struct { |
| 36 | http.ResponseWriter |
| 37 | allowed func() bool |
| 38 | } |
| 39 | |
| 40 | func (w *guardedWriter) Write(p []byte) (int, error) { |
| 41 | if !w.allowed() { |
| 42 | return 0, errors.New("notification stream revoked") |
| 43 | } |
| 44 | return w.ResponseWriter.Write(p) |
| 45 | } |
| 46 | func (w *guardedWriter) Flush() { _ = http.NewResponseController(w.ResponseWriter).Flush() } |
| 47 | func (w *guardedWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 48 | |