From 7d69b35b9d7c848f39c7fe9e6c21be7dc552eeb1 Mon Sep 17 00:00:00 2001 From: celogeek Date: Thu, 26 May 2022 17:08:21 +0200 Subject: [PATCH] encrypt password with more secure algo --- internal/photos/api/account.go | 10 +++++----- internal/photos/api/session.go | 9 ++++++--- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/internal/photos/api/account.go b/internal/photos/api/account.go index a73fe2e..4190129 100644 --- a/internal/photos/api/account.go +++ b/internal/photos/api/account.go @@ -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) diff --git a/internal/photos/api/session.go b/internal/photos/api/session.go index 91020ab..634e944 100644 --- a/internal/photos/api/session.go +++ b/internal/photos/api/session.go @@ -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 {