feat: account.

This commit is contained in:
2026-02-03 15:43:42 +08:00
parent 1c38601fe0
commit 85ec3cba4a
8 changed files with 276 additions and 3 deletions

40
models/user.go Normal file
View 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
}