- 新增 service.VerifyAppUserPassword:bcrypt 直接比对;明文定长比较,命中后条件更新升级为 bcrypt(WHERE password=旧值,避免并发覆盖) - 登录、解绑设备鉴权、修改口令三处统一走该函数 - 注册与改密的新口令入库前 bcrypt 哈希(此前注册写明文、重置写哈希,库里是混合状态) - 实测:明文用户首次登录成功并落库为 $2a$ 哈希;二次登录走 bcrypt;错误口令拒绝;新注册与改密均为哈希
72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package service
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"verification-platform-backend/internal/model"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
func TestHashAndVerifyAppUserPassword(t *testing.T) {
|
|
h, err := HashAppUserPassword("123456")
|
|
if err != nil {
|
|
t.Fatalf("哈希失败: %v", err)
|
|
}
|
|
if !IsBcryptHash(h) {
|
|
t.Fatalf("哈希前缀不识别: %s", h[:7])
|
|
}
|
|
u := &model.AppUser{Password: h}
|
|
if !VerifyAppUserPassword(u, "123456") {
|
|
t.Fatal("正确口令未通过")
|
|
}
|
|
if VerifyAppUserPassword(u, "1234567") {
|
|
t.Fatal("错误口令通过了")
|
|
}
|
|
if VerifyAppUserPassword(nil, "123456") {
|
|
t.Fatal("nil 用户通过了")
|
|
}
|
|
if VerifyAppUserPassword(&model.AppUser{}, "x") {
|
|
t.Fatal("空口令用户通过了")
|
|
}
|
|
}
|
|
|
|
// 历史明文必须仍然认账(这里只测比对分支:口令不符时不触发写库)
|
|
func TestVerifyLegacyPlaintextMismatch(t *testing.T) {
|
|
u := &model.AppUser{Password: "plain-old"}
|
|
if VerifyAppUserPassword(u, "wrong") {
|
|
t.Fatal("明文错误口令通过了")
|
|
}
|
|
if IsBcryptHash("plain-old") {
|
|
t.Fatal("明文被误判成 bcrypt")
|
|
}
|
|
}
|
|
|
|
func TestIsBcryptHash(t *testing.T) {
|
|
cases := map[string]bool{
|
|
"$2a$10$abc": true,
|
|
"$2b$12$xyz": true,
|
|
"$2y$05$q": true,
|
|
"123456": false,
|
|
"": false,
|
|
"$2a": false,
|
|
}
|
|
for in, want := range cases {
|
|
if got := IsBcryptHash(in); got != want {
|
|
t.Fatalf("IsBcryptHash(%q)=%v 期望 %v", in, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestBcryptRoundTripCost(t *testing.T) {
|
|
// 成本不能被误改成 4 以下
|
|
h, err := bcrypt.GenerateFromPassword([]byte("x"), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c, err := bcrypt.Cost(h)
|
|
if err != nil || c != bcrypt.DefaultCost {
|
|
t.Fatalf("成本 %v 期望 %v (err=%v)", c, bcrypt.DefaultCost, err)
|
|
}
|
|
}
|