user.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package models
  2. import (
  3. "gorm.io/gorm"
  4. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  5. )
  6. // BaseUser 密码登录基础用户
  7. type BaseUser struct {
  8. Username string `json:"username" gorm:"type:varchar(100);comment:用户名"`
  9. Salt string `json:"-" gorm:"type:varchar(255);comment:加盐;<-"`
  10. PasswordHash string `json:"-" gorm:"type:varchar(128);comment:密码hash;<-"`
  11. Password string `json:"password" gorm:"-"`
  12. }
  13. // SetPassword 设置密码
  14. func (u *BaseUser) SetPassword(value string) {
  15. u.Password = value
  16. u.generateSalt()
  17. u.PasswordHash = u.GetPasswordHash()
  18. }
  19. // GetPasswordHash 获取密码hash
  20. func (u *BaseUser) GetPasswordHash() string {
  21. passwordHash, err := pkg.SetPassword(u.Password, u.Salt)
  22. if err != nil {
  23. return ""
  24. }
  25. return passwordHash
  26. }
  27. // generateSalt 生成加盐值
  28. func (u *BaseUser) generateSalt() {
  29. u.Salt = pkg.GenerateRandomKey16()
  30. }
  31. // Verify 验证密码
  32. func (u *BaseUser) Verify(db *gorm.DB, tableName string) bool {
  33. db.Table(tableName).Where("username = ?", u.Username).First(u)
  34. return u.GetPasswordHash() == u.PasswordHash
  35. }