feat: account.
This commit is contained in:
40
models/user.go
Normal file
40
models/user.go
Normal file
@ -0,0 +1,40 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Username string `gorm:"uniqueIndex;not null" json:"username"`
|
||||
Email string `gorm:"uniqueIndex;" json:"email"`
|
||||
Phone string `gorm:"uniqueIndex;" json:"phone"`
|
||||
Password string `gorm:"not null" json:"-"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
|
||||
// HashPassword 密码加密
|
||||
func (u *User) HashPassword(password string) error {
|
||||
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.Password = string(bytes)
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckPassword 验证密码
|
||||
func (u *User) CheckPassword(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// BeforeCreate 创建前钩子
|
||||
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
if u.Password != "" {
|
||||
return u.HashPassword(u.Password)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user