Skip to content

Commit

Permalink
Try to get client IP
Browse files Browse the repository at this point in the history
  • Loading branch information
Piszmog committed May 10, 2024
1 parent 2bfd96d commit f3ff899
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 2 deletions.
8 changes: 8 additions & 0 deletions server/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion server/handler/signin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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."))
Expand Down
2 changes: 1 addition & 1 deletion server/handler/signup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit f3ff899

Please sign in to comment.