From bd40a71a935abdd736c33c175a8c69c58541a9fd Mon Sep 17 00:00:00 2001 From: Drew DeVault Date: Sun, 18 Feb 2024 12:33:32 +0100 Subject: [PATCH] auth: add auth.IPAddress With support for X-Forwarded-For --- auth/middleware.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/auth/middleware.go b/auth/middleware.go index a5a3527e50698b312398897b8dcaf4ac1ade338e..3ac7315c5beb67a8b0dc5e20b4876e0e9a3efd9f 100644 --- a/auth/middleware.go +++ b/auth/middleware.go @@ -60,6 +60,7 @@ const ( type AuthContext struct { AuthMethod string + IPAddress string // Only filled out for non-anonymous authentication UserID int @@ -310,6 +311,23 @@ func internalAuth(internalNet []*net.IPNet, payload []byte, auth.InternalAuth = internalAuth + auth.IPAddress = r.RemoteAddr + var route []string + for _, val := range r.Header.Values("X-Forwarded-For") { + route = append(route, strings.Split(val, ",")...) + } + for _, val := range route { + ip := net.ParseIP(val) + if ip == nil { + continue + } + if ip.IsPrivate() { + continue + } + auth.IPAddress = ip.String() + break + } + ctx := context.WithValue(r.Context(), userCtxKey, auth) r = r.WithContext(ctx) next.ServeHTTP(w, r)