feat: 实现 Admin 采购员账号管理 (#51)

This commit is contained in:
chengma
2026-08-09 13:50:55 +08:00
parent 771e2ee616
commit eea0d65ef8
12 changed files with 909 additions and 20 deletions
+47 -19
View File
@@ -32,6 +32,20 @@ var (
dummyPasswordHash, _ = bcrypt.GenerateFromPassword([]byte("not-a-real-password"), bcrypt.DefaultCost)
)
type validationError struct{ message string }
func (e *validationError) Error() string { return e.message }
// IsValidationError 让 Handler 区分可直接展示的表单错误和不可泄露的内部错误。
func IsValidationError(err error) bool {
var target *validationError
return errors.As(err, &target)
}
func invalidInput(message string, args ...any) error {
return &validationError{message: fmt.Sprintf(message, args...)}
}
// HasUsers 判断首次初始化入口是否已经永久关闭。
func HasUsers(db *sql.DB) (bool, error) {
count, err := repository.CountUsers(db)
@@ -41,27 +55,12 @@ func HasUsers(db *sql.DB) (bool, error) {
// SetupInitialAdmin 校验表单、哈希密码并在事务中创建首位管理员。
func SetupInitialAdmin(db *sql.DB, username, password, confirmation string, now time.Time) error {
username = strings.TrimSpace(username)
if username == "" {
return fmt.Errorf("用户名不能为空")
if err := validateUsername(username); err != nil {
return err
}
if len([]rune(username)) > maxUsernameLen {
return fmt.Errorf("用户名不能超过 %d 个字符", maxUsernameLen)
}
if len([]rune(password)) < minimumPasswordLen {
return fmt.Errorf("密码至少需要 %d 个字符", minimumPasswordLen)
}
// bcrypt 最多接受 72 字节。中文等字符可能占多个字节,因此不能只靠
// HTML 的 maxlength;服务端需要在哈希前给出可理解的校验错误。
if len([]byte(password)) > 72 {
return fmt.Errorf("密码不能超过 72 个字节")
}
if password != confirmation {
return fmt.Errorf("两次输入的密码不一致")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
hash, err := hashConfirmedPassword(password, confirmation)
if err != nil {
return fmt.Errorf("生成密码哈希失败: %w", err)
return err
}
userID, err := randomID("USR-", 16)
if err != nil {
@@ -75,6 +74,35 @@ func SetupInitialAdmin(db *sql.DB, username, password, confirmation string, now
})
}
func validateUsername(username string) error {
if username == "" {
return invalidInput("用户名不能为空")
}
if len([]rune(username)) > maxUsernameLen {
return invalidInput("用户名不能超过 %d 个字符", maxUsernameLen)
}
return nil
}
func hashConfirmedPassword(password, confirmation string) ([]byte, error) {
if len([]rune(password)) < minimumPasswordLen {
return nil, invalidInput("密码至少需要 %d 个字符", minimumPasswordLen)
}
// bcrypt 最多接受 72 字节。中文等字符可能占多个字节,因此不能只靠
// HTML 的 maxlength;服务端需要在哈希前给出可理解的校验错误。
if len([]byte(password)) > 72 {
return nil, invalidInput("密码不能超过 72 个字节")
}
if password != confirmation {
return nil, invalidInput("两次输入的密码不一致")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, fmt.Errorf("生成密码哈希失败: %w", err)
}
return hash, nil
}
// Login 校验统一凭据并创建一个固定 12 小时有效的 Session。
// 返回的 token 原文只交给 Cookie,数据库仅保存 SHA-256。
func Login(db *sql.DB, username, password string, now time.Time) (token string, user *model.User, expiresAt time.Time, err error) {