Files
Agent-System/internal/auth/crypto.go
T
weichen 39f8c1d134 feat(auth): admin password reset API and credential guards
Implement T20-F4-B reset-password endpoint with one-time temp password,
audit table, frontend wiring, login error envelope parsing, and
CreateUser fail-closed for empty password hashes. Recovered test chenwei
via env write (password out of band).
2026-09-24 04:18:58 +00:00

45 lines
1.2 KiB
Go

package auth
import (
"crypto/rand"
"fmt"
"math/big"
"golang.org/x/crypto/bcrypt"
)
// tempPasswordAlphabet excludes ambiguous characters (0/O, 1/l/I).
const tempPasswordAlphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"
// HashPassword 使用 bcrypt 对明文密码进行安全加盐哈希
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(bytes), nil
}
// CheckPassword 校验明文密码与 bcrypt 哈希是否匹配
func CheckPassword(hashed, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hashed), []byte(password))
return err == nil
}
// GenerateTempPassword returns a cryptographically random temporary password.
func GenerateTempPassword(length int) (string, error) {
if length <= 0 {
length = 16
}
out := make([]byte, length)
max := big.NewInt(int64(len(tempPasswordAlphabet)))
for i := range out {
n, err := rand.Int(rand.Reader, max)
if err != nil {
return "", fmt.Errorf("generate temp password: %w", err)
}
out[i] = tempPasswordAlphabet[n.Int64()]
}
return string(out), nil
}