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"
|
|
|
|
"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)
|
|
|
|
ipAddressComponents := strings.Split(ipAddress, ":")
|
|
|
|
ipAddressComponents[len(ipAddressComponents)-1] = ""
|
|
|
|
clientID := strings.Join(ipAddressComponents, ":") + req.UserAgent()
|
|
|
|
|
|
|
|
// 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
|
2020-06-23 04:11:56 +03:00
|
|
|
xForwardedFor := req.Header.Get("X-FORWARDED-FOR")
|
|
|
|
if xForwardedFor != "" {
|
2020-10-08 06:42:02 +03:00
|
|
|
return xForwardedFor
|
2020-06-23 04:11:56 +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
|
|
|
}
|