Files
Ydisks-Xianyu-Helper/internal/db/password.go
T
ChristandClaude Opus 4.8 980de41b53 chore: 重构配套改动 + 包文档 + 构建产物清理
automation 重构期间的配套修改:
- browser:订单抓取/密码登录/二维码刷新/stealth 等适配新流程,删 search.go
- db:cookies/orders_ext/extras/sessions/users/password/repository 等调整
- xianyu:mtop client、protocol(sign/decrypt/msgpack/cookies)、qrlogin、ws、ua
- server:admin/analytics/auth/cookie/helpers/item/item_publish_batch handlers
- frontend:App/Dashboard/ItemList/Rules/Sidebar/api/types,删 Keywords/TestPage
- auth、notify、webui、go.mod 等

本次会话补充:
- cmd/server、cmd/init-admin 改为 // Package main 开头的标准包文档
- .gitignore 加 internal/webui/static/assets/(hash 化构建产物不入库)
- internal/webui/static/index.html 重新构建

全量 go build/vet/test + race + 前端 test/build 通过。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-30 21:41:03 +08:00

56 lines
1.6 KiB
Go

package db
import (
"crypto/sha256"
"encoding/hex"
"errors"
"strings"
"golang.org/x/crypto/bcrypt"
)
// ErrPasswordMismatch 密码不匹配。
var ErrPasswordMismatch = errors.New("密码错误")
// HashPassword 用 bcrypt 哈希明文密码(新用户/改密码用)。
func HashPassword(plain string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(b), nil
}
// legacySHA256 兼容旧数据库中的 SHA-256 密码摘要。
func legacySHA256(plain string) string {
sum := sha256.Sum256([]byte(plain))
return hex.EncodeToString(sum[:])
}
// isLegacyHash 判断是否为老的无盐 SHA-256 哈希(64 位十六进制)。
// bcrypt 哈希以 $2 开头,据此区分。
func isLegacyHash(h string) bool {
return len(h) == 64 && !strings.HasPrefix(h, "$2")
}
// VerifyPassword 校验明文与存储哈希。
// - bcrypt 哈希:bcrypt.CompareHashAndPassword
// - 老 SHA-256 哈希:逐字节对比(兼容老库)
//
// 返回 (matched, needsUpgrade)。needsUpgrade=true 表示命中老哈希、应升级到 bcrypt。
func VerifyPassword(stored, plain string) (matched bool, needsUpgrade bool, err error) {
if isLegacyHash(stored) {
if stored == legacySHA256(plain) {
return true, true, nil
}
return false, false, ErrPasswordMismatch
}
if err := bcrypt.CompareHashAndPassword([]byte(stored), []byte(plain)); err != nil {
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return false, false, ErrPasswordMismatch
}
return false, false, err
}
return true, false, nil
}