2020-06-23 03:11:56 +02:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2020-10-07 08:14:33 +02:00
|
|
|
"crypto/md5"
|
|
|
|
"encoding/hex"
|
|
|
|
"net"
|
2020-06-23 03:11:56 +02:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
2020-10-07 08:14:33 +02:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2020-06-23 03:11:56 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
//GenerateClientIDFromRequest generates a client id from the provided request
|
|
|
|
func GenerateClientIDFromRequest(req *http.Request) string {
|
2020-10-07 08:14:33 +02: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
|
|
|
|
hasher := md5.New()
|
|
|
|
hasher.Write([]byte(clientID))
|
|
|
|
return hex.EncodeToString(hasher.Sum(nil))
|
|
|
|
}
|
2020-06-23 03:11:56 +02:00
|
|
|
|
2020-10-07 08:14:33 +02:00
|
|
|
// GetIPAddressFromRequest returns the IP address from a http request
|
|
|
|
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 != "" {
|
2020-10-08 05:42:02 +02:00
|
|
|
return xForwardedFor
|
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
|
|
|
}
|