testfb/.history/models/user_20240925164547.go
2024-09-25 16:52:21 +08:00

37 lines
867 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package models
import (
"time"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
type User struct {
ID uint `gorm:"primarykey" json:"id"`
Username string `gorm:"unique" json:"username"`
Password string `json:"-"`
Email string `json:"email"`
Phone string `json:"phone"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
func (u *User) BeforeCreate(tx *gorm.DB) error {
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
if err != nil {
return err
}
u.Password = string(hashedPassword)
return nil
}
func (u *User) ComparePassword(password string) error {
//直接比较密码不用bcrypt
if u.Password != password {
return ErrInvalidPassword
}
return nil
// return bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
}