2020-06-23 03:11:56 +02:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2020-11-15 03:39:53 +01:00
|
|
|
"crypto/md5" //nolint
|
2020-10-07 08:14:33 +02:00
|
|
|
"encoding/hex"
|
|
|
|
"net"
|
2020-06-23 03:11:56 +02:00
|
|
|
"net/http"
|
2023-10-16 00:43:07 +02:00
|
|
|
"strings"
|
2020-10-07 08:14:33 +02:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2020-06-23 03:11:56 +02:00
|
|
|
)
|
|
|
|
|
2020-11-13 00:14:59 +01:00
|
|
|
// GenerateClientIDFromRequest generates a client id from the provided request.
|
2020-06-23 03:11:56 +02:00
|
|
|
func GenerateClientIDFromRequest(req *http.Request) string {
|
2020-10-07 08:14:33 +02:00
|
|
|
ipAddress := GetIPAddressFromRequest(req)
|
2021-08-05 10:53:04 +02:00
|
|
|
clientID := ipAddress + req.UserAgent()
|
2020-10-07 08:14:33 +02:00
|
|
|
|
|
|
|
// Create a MD5 hash of this ip + useragent
|
2020-11-15 03:39:53 +01:00
|
|
|
b := md5.Sum([]byte(clientID)) // nolint
|
|
|
|
return hex.EncodeToString(b[:])
|
2020-10-07 08:14:33 +02:00
|
|
|
}
|
2020-06-23 03:11:56 +02:00
|
|
|
|
2020-11-13 00:14:59 +01:00
|
|
|
// GetIPAddressFromRequest returns the IP address from a http request.
|
2020-10-07 08:14:33 +02:00
|
|
|
func GetIPAddressFromRequest(req *http.Request) string {
|
|
|
|
ipAddressString := req.RemoteAddr
|
2024-01-03 20:07:11 +01:00
|
|
|
|
2020-06-23 03:11:56 +02:00
|
|
|
xForwardedFor := req.Header.Get("X-FORWARDED-FOR")
|
|
|
|
if xForwardedFor != "" {
|
2024-01-03 20:07:11 +01:00
|
|
|
ipAddressString = strings.Split(xForwardedFor, ", ")[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
if !strings.Contains(ipAddressString, ":") {
|
|
|
|
return ipAddressString
|
|
|
|
}
|
|
|
|
|
|
|
|
if isIPv6(ipAddressString) && !strings.Contains(ipAddressString, "[") {
|
|
|
|
return ipAddressString
|
2020-06-23 03:11:56 +02:00
|
|
|
}
|
2024-01-03 20:07:11 +01:00
|
|
|
|
2020-10-07 08:14:33 +02:00
|
|
|
ip, _, err := net.SplitHostPort(ipAddressString)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorln(err)
|
|
|
|
return ""
|
|
|
|
}
|
2020-06-23 03:11:56 +02:00
|
|
|
|
2020-10-07 08:14:33 +02:00
|
|
|
return ip
|
2020-06-23 03:11:56 +02:00
|
|
|
}
|
2024-01-03 20:07:11 +01:00
|
|
|
|
|
|
|
func isIPv6(address string) bool {
|
|
|
|
return strings.Count(address, ":") >= 2
|
|
|
|
}
|