testfb/models/user.go
2024-10-09 08:26:53 +08:00

47 lines
1.1 KiB
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 (
"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"`
}
type ReqApi struct {
Code string `json:"code"`
Message string `json:"message"`
NationalId string `json:"nationalId"`
Phone string `json:"phone"`
Token string `json:"token"`
}
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))
}
}