You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OneAuth/libs/utils/code_generate.go

82 lines
1.7 KiB
Go

package utils
import (
"crypto/rand"
"fmt"
"math/big"
"strings"
)
// GenerateCode 生成指定长度的数字验证码
func GenerateCode(length int) (string, error) {
if length <= 0 {
return "", fmt.Errorf("code length must be positive")
}
var code strings.Builder
for range length {
digit, err := rand.Int(rand.Reader, big.NewInt(10))
if err != nil {
return "", fmt.Errorf("failed to generate random digit: %w", err)
}
code.WriteString(digit.String())
}
return code.String(), nil
}
// GenerateAlphaNumericCode 生成字母数字混合验证码
func GenerateAlphaNumericCode(length int) (string, error) {
if length <= 0 {
return "", fmt.Errorf("code length must be positive")
}
const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var code strings.Builder
for range length {
index, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
if err != nil {
return "", fmt.Errorf("failed to generate random character: %w", err)
}
code.WriteByte(charset[index.Int64()])
}
return code.String(), nil
}
// ValidatePhoneNumber 简单的手机号验证
func ValidatePhoneNumber(phone string) bool {
if len(phone) < 10 || len(phone) > 15 {
return false
}
// 检查是否都是数字或以+开头
if phone[0] == '+' {
phone = phone[1:]
}
for _, char := range phone {
if char < '0' || char > '9' {
return false
}
}
return true
}
// NormalizePhoneNumber 标准化手机号
func NormalizePhoneNumber(phone string) string {
// 移除所有非数字字符,除了+号
var normalized strings.Builder
for i, char := range phone {
if char == '+' && i == 0 {
normalized.WriteRune(char)
} else if char >= '0' && char <= '9' {
normalized.WriteRune(char)
}
}
return normalized.String()
}