Use realIP
All checks were successful
Build and Push Docker Image on Tag / Build and Push Docker Image (push) Successful in 15m31s

Code was copied from https://github.com/go-chi/chi/blob/master/middleware/realip.go
This commit is contained in:
2025-02-01 17:07:24 +01:00
parent 5a0da6560d
commit f519b94392
3 changed files with 24 additions and 2 deletions

View File

@ -277,7 +277,7 @@ func (app *application) createVotesHandleKnownVotersElection(w http.ResponseWrit
} }
func (app *application) createVotesHandleUnknownVotersElection(w http.ResponseWriter, r *http.Request, election *models.Election) (string, error) { func (app *application) createVotesHandleUnknownVotersElection(w http.ResponseWriter, r *http.Request, election *models.Election) (string, error) {
voterIdentity := r.RemoteAddr voterIdentity := realIP(r)
voterExists, err := app.voters.Exists(voterIdentity, election.ID) voterExists, err := app.voters.Exists(voterIdentity, election.ID)
if err != nil { if err != nil {

View File

@ -5,7 +5,9 @@ import (
"code.dlmw.ch/dlmw/qv/internal/validator" "code.dlmw.ch/dlmw/qv/internal/validator"
"encoding/json" "encoding/json"
"io" "io"
"net"
"net/http" "net/http"
"strings"
) )
func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) { func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) {
@ -67,3 +69,23 @@ func (app *application) unmarshalRequest(r *http.Request, dst any) error {
return nil return nil
} }
func realIP(r *http.Request) string {
var ip string
if tcip := r.Header.Get(http.CanonicalHeaderKey("True-Client-IP")); tcip != "" {
ip = tcip
} else if xrip := r.Header.Get(http.CanonicalHeaderKey("X-Real-IP")); xrip != "" {
ip = xrip
} else if xff := r.Header.Get(http.CanonicalHeaderKey("X-Forwarded-For")); xff != "" {
i := strings.Index(xff, ",")
if i == -1 {
i = len(xff)
}
ip = xff[:i]
}
if ip == "" || net.ParseIP(ip) == nil {
return ""
}
return ip
}

View File

@ -20,7 +20,7 @@ func (app *application) recoverPanic(next http.Handler) http.Handler {
func (app *application) logRequest(next http.Handler) http.Handler { func (app *application) logRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var ( var (
ip = r.RemoteAddr ip = realIP(r)
proto = r.Proto proto = r.Proto
method = r.Method method = r.Method
uri = r.URL.RequestURI() uri = r.URL.RequestURI()