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
|
2020-06-23 03:11:56 +02:00
|
|
|
xForwardedFor := req.Header.Get("X-FORWARDED-FOR")
|
|
|
|
if xForwardedFor != "" {
|
2023-10-16 00:43:07 +02:00
|
|
|
clientIpString := strings.Split(xForwardedFor, ", ")[0]
|
2023-10-19 02:01:03 +02:00
|
|
|
if strings.Contains(clientIpString, ":") {
|
|
|
|
ip, _, err := net.SplitHostPort(clientIpString)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorln(err)
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return ip
|
2023-10-16 00:43:07 +02:00
|
|
|
}
|
2023-10-19 02:01:03 +02:00
|
|
|
return clientIpString
|
2020-06-23 03:11:56 +02: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
|
|
|
}
|