Files
go-auth/credentials/validation.go
2026-03-01 03:04:43 +01:00

43 lines
1.1 KiB
Go

package credentials
import (
"regexp"
"strings"
)
var emailRegex = regexp.MustCompile(`^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$`)
var usernameAllowedRegex = regexp.MustCompile(`^[A-Za-z0-9._-]{3,20}$`)
const bcryptMaxPasswordBytes = 72
// At least one letter.
var passwordLetterRegex = regexp.MustCompile(`[A-Za-z]`)
// At least one number or special symbol (non-letter).
var passwordNonLetterRegex = regexp.MustCompile(`[^A-Za-z]`)
func IsValidEmail(email string) bool {
return emailRegex.MatchString(email)
}
func IsValidUsername(username string) bool {
if !usernameAllowedRegex.MatchString(username) {
return false
}
return !strings.Contains(username, "..") &&
!strings.Contains(username, "--") &&
!strings.Contains(username, "__")
}
func IsValidPassword(password string) bool {
return len(password) >= 12 &&
IsPasswordWithinBcryptLimit(password) &&
passwordLetterRegex.MatchString(password) &&
passwordNonLetterRegex.MatchString(password)
}
func IsPasswordWithinBcryptLimit(password string) bool {
return len([]byte(password)) <= bcryptMaxPasswordBytes
}