simplify account

This commit is contained in:
celogeek 2022-05-26 17:29:05 +02:00
parent 7d69b35b9d
commit a5241c404a
Signed by: celogeek
GPG Key ID: E6B7BDCFC446233A
2 changed files with 11 additions and 25 deletions

View File

@ -18,33 +18,19 @@ var (
// Model
type Account struct {
ID uint32 `gorm:"primary_key" json:"-"`
Login string `gorm:"unique;size:64;not null" json:"login"`
Password string `gorm:"-" json:"-"`
EncryptedPassword string `gorm:"size:60;not null" json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"-"`
}
func (a *Account) BeforeCreate(tx *gorm.DB) error {
if a.EncryptedPassword == "" {
a.EncryptPassword()
}
return nil
}
func (a *Account) EncryptPassword() {
b, _ := bcrypt.GenerateFromPassword([]byte(a.Password), 12)
a.EncryptedPassword = string(b)
ID uint32 `gorm:"primary_key" json:"-"`
Login string `gorm:"unique;size:64;not null" json:"login"`
Password []byte `gorm:"type:varchar(60);not null" json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"-"`
}
func NewAccount(login string, password string) *Account {
a := &Account{
p, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return &Account{
Login: login,
Password: password,
Password: p,
}
a.EncryptPassword()
return a
}
// Service

View File

@ -39,14 +39,14 @@ func (s *Session) BeforeCreate(tx *gorm.DB) error {
}
func NewSession(tx *gorm.DB, login string, password string) (*Session, error) {
account := &Account{Login: login}
account := &Account{}
if err := tx.Where(
"login = ?",
account.Login,
login,
).First(account).Error; err != nil {
return nil, err
}
if err := bcrypt.CompareHashAndPassword([]byte(account.EncryptedPassword), []byte(password)); err != nil {
if err := bcrypt.CompareHashAndPassword(account.Password, []byte(password)); err != nil {
return nil, err
}