mg-transport-core/core/validator.go

81 lines
1.6 KiB
Go
Raw Normal View History

2019-09-04 15:22:27 +03:00
package core
import (
2021-07-27 14:29:05 +03:00
"net/url"
"strings"
2019-09-04 15:22:27 +03:00
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
2019-09-04 15:22:27 +03:00
)
2021-07-27 14:29:05 +03:00
// init here will register `validateCrmURL` function for gin validator.
2019-09-04 15:22:27 +03:00
func init() {
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
2021-07-27 14:29:05 +03:00
if err := v.RegisterValidation("validateCrmURL", validateCrmURL); err != nil {
2019-09-04 15:22:27 +03:00
panic("cannot register crm url validator: " + err.Error())
}
}
}
// validateCrmURL will validate CRM URL.
2019-12-12 09:35:05 +03:00
func validateCrmURL(fl validator.FieldLevel) bool {
2021-07-27 14:29:05 +03:00
domainName := fl.Field().String()
return isDomainValid(domainName)
}
func isDomainValid(crmURL string) bool {
parseURL, err := url.ParseRequestURI(crmURL)
if err != nil || nil == parseURL || !checkURLString(parseURL) {
return false
}
mainDomain := getMainDomain(parseURL.Hostname())
if checkDomains(GetSaasDomains(), mainDomain) {
2021-07-27 14:29:05 +03:00
return true
}
if checkDomains(GetBoxDomains(), parseURL.Hostname()) {
2021-07-27 14:29:05 +03:00
return true
}
return false
}
func checkDomains(crmDomains []Domain, domain string) bool {
2021-07-27 14:29:05 +03:00
if nil == crmDomains {
return false
}
for _, crmDomain := range crmDomains {
if crmDomain.Domain == domain {
return true
}
}
return false
}
func getMainDomain(hostname string) (mainDomain string) {
return strings.Join(strings.Split(hostname, ".")[1:], ".")
}
func checkURLString(parseURL *url.URL) bool {
if nil == parseURL {
return false
}
if parseURL.Scheme != "https" ||
parseURL.Port() != "" ||
(parseURL.Path != "/" && parseURL.Path != "") ||
len(parseURL.Query()) != 0 ||
parseURL.Fragment != "" ||
nil != parseURL.User {
return false
}
return true
}