authorizer/server/utils/validator.go

89 lines
2.1 KiB
Go
Raw Normal View History

2021-07-12 18:22:16 +00:00
package utils
import (
"net/mail"
"regexp"
"strings"
"github.com/authorizerdev/authorizer/server/constants"
2022-01-17 06:02:13 +00:00
"github.com/authorizerdev/authorizer/server/envstore"
)
2021-07-12 18:22:16 +00:00
2022-01-17 06:02:13 +00:00
// IsValidEmail validates email
2021-07-12 18:22:16 +00:00
func IsValidEmail(email string) bool {
_, err := mail.ParseAddress(email)
return err == nil
}
2022-01-17 06:02:13 +00:00
// IsValidOrigin validates origin based on ALLOWED_ORIGINS
func IsValidOrigin(url string) bool {
2022-02-28 02:25:01 +00:00
allowedOrigins := envstore.EnvStoreObj.GetSliceStoreEnvVariable(constants.EnvKeyAllowedOrigins)
if len(allowedOrigins) == 1 && allowedOrigins[0] == "*" {
return true
}
hasValidURL := false
hostName, port := GetHostParts(url)
currentOrigin := hostName + ":" + port
2022-01-17 06:02:13 +00:00
for _, origin := range allowedOrigins {
replacedString := origin
// if has regex whitelisted domains
if strings.Contains(origin, "*") {
replacedString = strings.Replace(origin, ".", "\\.", -1)
replacedString = strings.Replace(replacedString, "*", ".*", -1)
if strings.HasPrefix(replacedString, ".*") {
replacedString += "\\b"
}
if strings.HasSuffix(replacedString, ".*") {
replacedString = "\\b" + replacedString
}
}
if matched, _ := regexp.MatchString(replacedString, currentOrigin); matched {
hasValidURL = true
break
}
}
return hasValidURL
}
2022-01-17 06:02:13 +00:00
// IsValidRoles validates roles
func IsValidRoles(userRoles []string, roles []string) bool {
valid := true
for _, role := range roles {
2021-10-19 07:27:59 +00:00
if !StringSliceContains(userRoles, role) {
valid = false
break
}
}
return valid
}
2022-01-17 06:02:13 +00:00
// IsValidVerificationIdentifier validates verification identifier that is used to identify
// the type of verification request
func IsValidVerificationIdentifier(identifier string) bool {
2022-01-17 06:02:13 +00:00
if identifier != constants.VerificationTypeBasicAuthSignup && identifier != constants.VerificationTypeForgotPassword && identifier != constants.VerificationTypeUpdateEmail {
return false
}
return true
}
2022-01-17 06:02:13 +00:00
// IsStringArrayEqual validates if string array are equal.
// This does check if the order is same
func IsStringArrayEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}