From f3ff899c9e3628d04bc19e23c441554b4e0b6dfb Mon Sep 17 00:00:00 2001 From: Randell Date: Thu, 9 May 2024 20:05:59 -0600 Subject: [PATCH] Try to get client IP --- server/handler/handler.go | 8 ++++++++ server/handler/signin.go | 2 +- server/handler/signup.go | 2 +- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/server/handler/handler.go b/server/handler/handler.go index a3c003b..368180f 100644 --- a/server/handler/handler.go +++ b/server/handler/handler.go @@ -45,3 +45,11 @@ func getUserID(r *http.Request) (int64, error) { } return userID, nil } + +func getClientIP(r *http.Request) string { + ip := r.Header.Get("X-FORWARD-FOR") + if ip != "" { + return ip + } + return r.RemoteAddr +} diff --git a/server/handler/signin.go b/server/handler/signin.go index 2a159b0..a0b5e14 100644 --- a/server/handler/signin.go +++ b/server/handler/signin.go @@ -67,7 +67,7 @@ func (h *Handler) Authenticate(w http.ResponseWriter, r *http.Request) { cookieValue = cookie.Value } - token, expiresAt, err := h.newSession(r.Context(), user.ID, r.UserAgent(), cookieValue, r.RemoteAddr) + token, expiresAt, err := h.newSession(r.Context(), user.ID, r.UserAgent(), cookieValue, getClientIP(r)) if err != nil { h.Logger.Error("failed to create session", "error", err) h.html(r.Context(), w, http.StatusInternalServerError, components.Alert(types.AlertTypeWarning, "Something went wrong", "Try again later.")) diff --git a/server/handler/signup.go b/server/handler/signup.go index 2efcb24..3093414 100644 --- a/server/handler/signup.go +++ b/server/handler/signup.go @@ -64,7 +64,7 @@ func (h *Handler) Register(w http.ResponseWriter, r *http.Request) { user := queries.InsertUserParams{ Email: email, Password: string(hashedPassword), - InitialIpAddress: r.RemoteAddr, + InitialIpAddress: getClientIP(r), } userID, err := h.Database.Queries().InsertUser(r.Context(), user) if err != nil {