authorizer/server/parsers/url.go

102 lines
2.2 KiB
Go
Raw Normal View History

2022-05-30 06:24:16 +00:00
package parsers
import (
"net/url"
"strings"
2022-01-31 06:05:24 +00:00
"github.com/gin-gonic/gin"
"github.com/authorizerdev/authorizer/server/constants"
2022-05-30 03:49:55 +00:00
"github.com/authorizerdev/authorizer/server/memorystore"
)
2022-01-31 06:05:24 +00:00
// GetHost returns hostname from request context
// if EnvKeyAuthorizerURL is set it is given highest priority.
// if X-Authorizer-URL header is set it is given second highest priority
// if above 2 are not set the requesting host name is used
2022-01-31 06:05:24 +00:00
func GetHost(c *gin.Context) string {
authorizerURL, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL)
if err != nil {
authorizerURL = ""
}
if authorizerURL != "" {
return authorizerURL
}
authorizerURL = c.Request.Header.Get("X-Authorizer-URL")
if authorizerURL != "" {
return authorizerURL
}
2022-01-31 09:00:13 +00:00
scheme := c.Request.Header.Get("X-Forwarded-Proto")
if scheme != "https" {
scheme = "http"
2022-01-31 06:05:24 +00:00
}
2022-01-31 09:00:13 +00:00
host := c.Request.Host
return scheme + "://" + host
2022-01-31 06:05:24 +00:00
}
// GetHostName function returns hostname and port
func GetHostParts(uri string) (string, string) {
tempURI := uri
if !strings.HasPrefix(tempURI, "http://") && !strings.HasPrefix(tempURI, "https://") {
tempURI = "https://" + tempURI
}
u, err := url.Parse(tempURI)
if err != nil {
return "localhost", "8080"
}
host := u.Hostname()
port := u.Port()
return host, port
}
// GetDomainName function to get domain name
func GetDomainName(uri string) string {
tempURI := uri
if !strings.HasPrefix(tempURI, "http://") && !strings.HasPrefix(tempURI, "https://") {
tempURI = "https://" + tempURI
}
u, err := url.Parse(tempURI)
if err != nil {
return `localhost`
}
2021-07-21 23:52:53 +00:00
host := u.Hostname()
2021-07-28 18:23:54 +00:00
// code to get root domain in case of sub-domains
hostParts := strings.Split(host, ".")
hostPartsLen := len(hostParts)
if hostPartsLen == 1 {
return host
}
if hostPartsLen == 2 {
if hostParts[0] == "www" {
return hostParts[1]
} else {
return host
}
}
if hostPartsLen > 2 {
return strings.Join(hostParts[hostPartsLen-2:], ".")
}
2021-07-21 23:52:53 +00:00
return host
}
// GetAppURL to get /app/ url if not configured by user
func GetAppURL(gc *gin.Context) string {
2022-05-30 06:24:16 +00:00
envAppURL, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyAppURL)
if envAppURL == "" || err != nil {
2022-03-15 04:27:09 +00:00
envAppURL = GetHost(gc) + "/app"
}
return envAppURL
}