From 6ffe946c24fd7b52c47cd54b1bcfd134d964d42e Mon Sep 17 00:00:00 2001 From: maxwell Date: Fri, 27 Sep 2024 09:33:25 +0800 Subject: [PATCH] update --- .history/models/user_20240927093317.go | 38 ++++++++++++++++++++++++++ .history/models/user_20240927093319.go | 38 ++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 .history/models/user_20240927093317.go create mode 100644 .history/models/user_20240927093319.go diff --git a/.history/models/user_20240927093317.go b/.history/models/user_20240927093317.go new file mode 100644 index 0000000..2fcb5b7 --- /dev/null +++ b/.history/models/user_20240927093317.go @@ -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)) + } +} diff --git a/.history/models/user_20240927093319.go b/.history/models/user_20240927093319.go new file mode 100644 index 0000000..2fcb5b7 --- /dev/null +++ b/.history/models/user_20240927093319.go @@ -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)) + } +}