63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package models
|
|
|
|
import (
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
const PasswordCryptLevel = 12
|
|
|
|
type Account struct {
|
|
BaseModel
|
|
Username string `gorm:"column:username;not null;unique_index;comment:'用户名'" json:"username" form:"username"`
|
|
Password string `gorm:"column:password;comment:'密码'" form:"password" json:"-"`
|
|
Name string `form:"name" json:"name"`
|
|
IsActive bool `json:"-"`
|
|
}
|
|
|
|
func (a *Account) TableName() string {
|
|
return "user_accounts"
|
|
}
|
|
|
|
func (a *Account) GetUserByID(id uint) *Account {
|
|
DB.Model(&Account{}).First(a, id)
|
|
if a.ID > 0 {
|
|
return a
|
|
} else {
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// 设置密码加密
|
|
func (a *Account) SetPassword(password string) error {
|
|
p, err := bcrypt.GenerateFromPassword([]byte(password), PasswordCryptLevel)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
a.Password = string(p)
|
|
return nil
|
|
}
|
|
|
|
// IsPasswordEqual 验证密码是否匹配
|
|
func (a *Account) IsPasswordEqual(password string) bool {
|
|
err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password))
|
|
return err == nil
|
|
}
|
|
|
|
// CheckDuplicateUsername 验证用户名是否重复
|
|
func (a *Account) CheckDuplicateUsername() bool {
|
|
var count int64
|
|
if DB.Model(&Account{}).Where("username=?", a.Username).Count(&count); count > 0 {
|
|
return false
|
|
} else {
|
|
return true
|
|
}
|
|
}
|
|
|
|
func GetAccountByID(id uint) (*Account, error) {
|
|
var account Account
|
|
if err := DB.First(&account, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &account, nil
|
|
}
|