encrypt password with more secure algo
This commit is contained in:
parent
396c0fbc08
commit
7d69b35b9d
@ -6,6 +6,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@ -20,7 +21,7 @@ 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:44;not null" json:"-"`
|
||||
EncryptedPassword string `gorm:"size:60;not null" json:"-"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"-"`
|
||||
}
|
||||
@ -33,9 +34,8 @@ func (a *Account) BeforeCreate(tx *gorm.DB) error {
|
||||
}
|
||||
|
||||
func (a *Account) EncryptPassword() {
|
||||
ch := NewChecksum()
|
||||
ch.Write([]byte(a.Password))
|
||||
a.EncryptedPassword = ch.String()
|
||||
b, _ := bcrypt.GenerateFromPassword([]byte(a.Password), 12)
|
||||
a.EncryptedPassword = string(b)
|
||||
}
|
||||
|
||||
func NewAccount(login string, password string) *Account {
|
||||
@ -95,7 +95,7 @@ func (s *Service) Login(c *gin.Context) {
|
||||
|
||||
session, err := NewSession(s.DB, account.Login, account.Password)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
|
||||
c.AbortWithError(http.StatusNotFound, ErrAccountAuth)
|
||||
} else {
|
||||
c.AbortWithError(http.StatusInternalServerError, err)
|
||||
|
@ -8,6 +8,7 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@ -38,14 +39,16 @@ func (s *Session) BeforeCreate(tx *gorm.DB) error {
|
||||
}
|
||||
|
||||
func NewSession(tx *gorm.DB, login string, password string) (*Session, error) {
|
||||
account := NewAccount(login, password)
|
||||
account := &Account{Login: login}
|
||||
if err := tx.Where(
|
||||
"login = ? and encrypted_password = ?",
|
||||
"login = ?",
|
||||
account.Login,
|
||||
account.EncryptedPassword,
|
||||
).First(account).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(account.EncryptedPassword), []byte(password)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
session := &Session{Account: account}
|
||||
if err := tx.Create(session).Error; err != nil {
|
||||
|
Loading…
x
Reference in New Issue
Block a user