simplify account
This commit is contained in:
parent
7d69b35b9d
commit
a5241c404a
@ -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
|
||||
|
@ -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
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user