-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
middleware.go
88 lines (77 loc) · 2.47 KB
/
middleware.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
package http
import (
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog"
"net/http"
"runtime/debug"
"strings"
"time"
)
func (s Server) IsAuthenticated(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token := r.Header.Get("X-API-Token"); token != "" {
// check header
if !s.apiService.ValidateAPIKey(r.Context(), token) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
} else if key := r.URL.Query().Get("apikey"); key != "" {
// check query param lke ?apikey=TOKEN
if !s.apiService.ValidateAPIKey(r.Context(), key) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
} else {
// check session
session, _ := s.cookieStore.Get(r, "user_session")
// Check if user is authenticated
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
}
next.ServeHTTP(w, r)
})
}
func LoggerMiddleware(logger *zerolog.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
log := logger.With().Logger()
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
defer func() {
t2 := time.Now()
// Recover and record stack traces in case of a panic
if rec := recover(); rec != nil {
log.Error().
Str("type", "error").
Timestamp().
Interface("recover_info", rec).
Bytes("debug_stack", debug.Stack()).
Msg("log system error")
http.Error(ww, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
if !strings.Contains("/api/healthz/liveness|/api/healthz/readiness", r.URL.Path) {
// log end request
log.Trace().
Str("type", "access").
Timestamp().
Fields(map[string]interface{}{
"remote_ip": r.RemoteAddr,
"url": r.URL.Path,
"proto": r.Proto,
"method": r.Method,
"user_agent": r.Header.Get("User-Agent"),
"status": ww.Status(),
"latency_ms": float64(t2.Sub(t1).Nanoseconds()) / 1000000.0,
"bytes_in": r.Header.Get("Content-Length"),
"bytes_out": ww.BytesWritten(),
}).
Msg("incoming_request")
}
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
}