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"
|
2020-04-29 10:08:00 +03:00
|
|
|
"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())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-09 14:57:14 +03:00
|
|
|
// 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())
|
|
|
|
|
2021-12-21 14:29:44 +03:00
|
|
|
if checkDomains(GetSaasDomains(), mainDomain) {
|
2021-07-27 14:29:05 +03:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2021-12-21 14:29:44 +03:00
|
|
|
if checkDomains(GetBoxDomains(), parseURL.Hostname()) {
|
2021-07-27 14:29:05 +03:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2021-12-21 14:29:44 +03:00
|
|
|
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
|
|
|
|
}
|