simplify account
This commit is contained in:
parent
7d69b35b9d
commit
a5241c404a
@ -18,33 +18,19 @@ var (
|
|||||||
|
|
||||||
// Model
|
// Model
|
||||||
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
|
||||||
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user