This commit is contained in:
maxwell 2024-09-27 09:33:25 +08:00
parent b7b872f70b
commit 6ffe946c24
2 changed files with 76 additions and 0 deletions

View File

@ -0,0 +1,38 @@
package models
import (
"errors"
"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 nil
} else {
return errors.New("error password")
// bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
}
}

View File

@ -0,0 +1,38 @@
package models
import (
"errors"
"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 nil
} else {
return errors.New("error password")
// bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
}
}