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