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

@ -20,31 +20,17 @@ var (
type Account struct { type Account struct {
ID uint32 `gorm:"primary_key" json:"-"` ID uint32 `gorm:"primary_key" json:"-"`
Login string `gorm:"unique;size:64;not null" json:"login"` Login string `gorm:"unique;size:64;not null" json:"login"`
Password string `gorm:"-" json:"-"` Password []byte `gorm:"type:varchar(60);not null" json:"-"`
EncryptedPassword string `gorm:"size:60;not null" json:"-"`
CreatedAt time.Time `json:"created_at"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"-"` 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)
}
func NewAccount(login string, password string) *Account { func NewAccount(login string, password string) *Account {
a := &Account{ p, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
return &Account{
Login: login, Login: login,
Password: password, Password: p,
} }
a.EncryptPassword()
return a
} }
// Service // 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) { func NewSession(tx *gorm.DB, login string, password string) (*Session, error) {
account := &Account{Login: login} account := &Account{}
if err := tx.Where( if err := tx.Where(
"login = ?", "login = ?",
account.Login, login,
).First(account).Error; err != nil { ).First(account).Error; err != nil {
return nil, err 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 return nil, err
} }