package models import ( "time" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" ) // 账号状态常量。 const ( StatusDisabled = 0 // 禁用 StatusNormal = 1 // 正常 StatusLocked = 2 // 锁定 StatusUnactivated = 3 // 未激活 ) // 角色常量。 const ( RoleAdmin = "admin" RoleAuthor = "author" ) // User 表示博客用户(作者 / 管理员)。 type User struct { gorm.Model Username string `gorm:"uniqueIndex;not null;size:255" json:"username"` Password string `gorm:"not null" json:"-"` DisplayName string `gorm:"size:255" json:"display_name"` Avatar string `gorm:"size:512" json:"avatar"` Birthday *time.Time `json:"birthday"` Gender string `gorm:"size:16" json:"gender"` Email string `gorm:"size:255" json:"email"` Status int `gorm:"default:1" json:"status"` Role string `gorm:"size:32;default:author" json:"role"` Articles []Article `gorm:"foreignKey:AuthorID" json:"-"` } // bcryptCost 是新密码哈希时使用的工作因子(SECURITY_TODO #17)。 // 现有哈希保留其原有成本——CompareHashAndPassword 会按哈希自适应—— // 并在用户下次修改密码时自然升级。 const bcryptCost = 12 // SetPassword 使用 bcrypt 对明文密码进行哈希并存储。 func (u *User) SetPassword(plain string) error { hash, err := bcrypt.GenerateFromPassword([]byte(plain), bcryptCost) if err != nil { return err } u.Password = string(hash) return nil } // CheckPassword 将明文密码与存储的 bcrypt 哈希进行比对。 func (u *User) CheckPassword(plain string) bool { err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(plain)) return err == nil }