mirror of
https://github.com/netbirdio/netbird.git
synced 2026-04-16 15:26:40 +00:00
53 lines
1.5 KiB
Go
53 lines
1.5 KiB
Go
package accesslog
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/rs/xid"
|
|
|
|
"github.com/netbirdio/netbird/proxy/internal/auth"
|
|
"github.com/netbirdio/netbird/proxy/internal/proxy"
|
|
)
|
|
|
|
func (l *Logger) Middleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Use a response writer wrapper so we can access the status code later.
|
|
sw := &statusWriter{
|
|
w: w,
|
|
status: http.StatusOK, // Default status is OK unless otherwise modified.
|
|
}
|
|
|
|
// Get the source IP before passing the request on as the proxy will modify
|
|
// headers that we wish to use to gather that information on the request.
|
|
sourceIp := extractSourceIP(r)
|
|
|
|
start := time.Now()
|
|
next.ServeHTTP(sw, r)
|
|
duration := time.Since(start)
|
|
|
|
host, _, err := net.SplitHostPort(r.Host)
|
|
if err != nil {
|
|
// Fallback to just using the full host value.
|
|
host = r.Host
|
|
}
|
|
|
|
entry := logEntry{
|
|
ID: xid.New().String(),
|
|
ServiceId: proxy.ServiceIdFromContext(r.Context()),
|
|
AccountID: proxy.AccountIdFromContext(r.Context()),
|
|
Host: host,
|
|
Path: r.URL.Path,
|
|
DurationMs: duration.Milliseconds(),
|
|
Method: r.Method,
|
|
ResponseCode: int32(sw.status),
|
|
SourceIp: sourceIp,
|
|
AuthMechanism: auth.MethodFromContext(r.Context()).String(),
|
|
UserId: auth.UserFromContext(r.Context()),
|
|
AuthSuccess: sw.status != http.StatusUnauthorized && sw.status != http.StatusForbidden,
|
|
}
|
|
l.log(r.Context(), entry)
|
|
})
|
|
}
|