clientId.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package utils
  2. import (
  3. "crypto/md5" //nolint
  4. "encoding/hex"
  5. "net"
  6. "net/http"
  7. "strings"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. // GenerateClientIDFromRequest generates a client id from the provided request.
  11. func GenerateClientIDFromRequest(req *http.Request) string {
  12. ipAddress := GetIPAddressFromRequest(req)
  13. clientID := ipAddress + req.UserAgent()
  14. // Create a MD5 hash of this ip + useragent
  15. b := md5.Sum([]byte(clientID)) // nolint
  16. return hex.EncodeToString(b[:])
  17. }
  18. // GetIPAddressFromRequest returns the IP address from a http request.
  19. func GetIPAddressFromRequest(req *http.Request) string {
  20. ipAddressString := req.RemoteAddr
  21. xForwardedFor := req.Header.Get("X-FORWARDED-FOR")
  22. if xForwardedFor != "" {
  23. clientIpString := strings.Split(xForwardedFor, ", ")[0]
  24. // If the IP has a prefix of ::ffff: then it's an IPv4 address.
  25. // Strip the prefix so we can parse it as an IPv4 address.
  26. clientIpString = strings.TrimPrefix(clientIpString, "::ffff:")
  27. if strings.Contains(clientIpString, ":") {
  28. ip, _, err := net.SplitHostPort(clientIpString)
  29. if err != nil {
  30. log.Errorln(err)
  31. return ""
  32. }
  33. return ip
  34. }
  35. return clientIpString
  36. }
  37. ip, _, err := net.SplitHostPort(ipAddressString)
  38. if err != nil {
  39. log.Errorln(err)
  40. return ""
  41. }
  42. return ip
  43. }