- 新增 service.VerifyAppUserPassword:bcrypt 直接比对;明文定长比较,命中后条件更新升级为 bcrypt(WHERE password=旧值,避免并发覆盖) - 登录、解绑设备鉴权、修改口令三处统一走该函数 - 注册与改密的新口令入库前 bcrypt 哈希(此前注册写明文、重置写哈希,库里是混合状态) - 实测:明文用户首次登录成功并落库为 $2a$ 哈希;二次登录走 bcrypt;错误口令拒绝;新注册与改密均为哈希
56 lines
1.8 KiB
Go
56 lines
1.8 KiB
Go
package service
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"log"
|
|
"strings"
|
|
|
|
"verification-platform-backend/internal/database"
|
|
"verification-platform-backend/internal/model"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// IsBcryptHash 判断库里的口令字段是不是 bcrypt 哈希
|
|
func IsBcryptHash(s string) bool {
|
|
return strings.HasPrefix(s, "$2a$") || strings.HasPrefix(s, "$2b$") || strings.HasPrefix(s, "$2y$")
|
|
}
|
|
|
|
// HashAppUserPassword 终端用户新口令入库前的统一哈希
|
|
func HashAppUserPassword(plain string) (string, error) {
|
|
h, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost)
|
|
return string(h), err
|
|
}
|
|
|
|
// VerifyAppUserPassword 校验终端用户口令,兼容历史明文
|
|
//
|
|
// 历史原因 app_users.password 里混着明文和 bcrypt(注册写明文、重置写哈希)。
|
|
// 这里两条都认:bcrypt 直接比对;明文用定长比较,命中后顺手升级成 bcrypt。
|
|
// 升级用 WHERE password = 旧值 做条件更新,避免并发把别人刚写的哈希覆盖回去。
|
|
// 升级写库失败不影响本次登录结果——放行,等下次再升。
|
|
func VerifyAppUserPassword(user *model.AppUser, plain string) bool {
|
|
if user == nil || user.Password == "" {
|
|
return false
|
|
}
|
|
if IsBcryptHash(user.Password) {
|
|
return bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(plain)) == nil
|
|
}
|
|
if subtle.ConstantTimeCompare([]byte(user.Password), []byte(plain)) != 1 {
|
|
return false
|
|
}
|
|
h, err := HashAppUserPassword(plain)
|
|
if err != nil {
|
|
log.Printf("[appuser] 口令升级失败 user=%d: %v", user.ID, err)
|
|
return true
|
|
}
|
|
res := database.DB.Model(&model.AppUser{}).
|
|
Where("id = ? AND password = ?", user.ID, user.Password).
|
|
Update("password", h)
|
|
if res.Error != nil {
|
|
log.Printf("[appuser] 口令升级写库失败 user=%d: %v", user.ID, res.Error)
|
|
return true
|
|
}
|
|
user.Password = h
|
|
return true
|
|
}
|