Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Reset password validation #160

Merged
merged 6 commits into from
Nov 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions development-kit/pkg/enums/errors/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ import "errors"
var ErrorWrongEmailOrPassword = errors.New("{ACCOUNT} invalid username or password")
var ErrorAccountEmailNotConfirmed = errors.New("{ACCOUNT} account email not confirmed")
var ErrorEmailAlreadyInUse = errors.New("{ACCOUNT} email already in use")
var ErrorNewPasswordNotEqualOldPassword = errors.New("{ACCOUNT} new password is can't equals current password")
var ErrorNewPasswordOrPasswordHashNotBeEmpty = errors.New("{ACCOUNT} password or password hash can't be empty")
var ErrorInvalidResetPasswordCode = errors.New("{ACCOUNT} invalid reset password data")
var ErrorDoNotHavePermissionToThisAction = errors.New("{ACCOUNT} user do not have permission to this action")
var ErrorMissingOrInvalidPassword = errors.New("{ACCOUNT} missing or invalid password")
var ErrorInvalidPassword = errors.New("{ACCOUNT} password is not valid")
var ErrorInvalidAccountID = errors.New("{ACCOUNT} invalid account id")
var ErrorUserAlreadyLogged = errors.New("{ACCOUNT} user already logged")
var ErrorEmptyAuthorizationToken = errors.New("{ACCOUNT} empty authorization token")
Expand Down
29 changes: 24 additions & 5 deletions development-kit/pkg/usecases/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"fmt"
"io"
"math/rand"
"regexp"
"time"

"github.com/Nerzal/gocloak/v7"
Expand Down Expand Up @@ -57,6 +58,8 @@ type IUseCases interface {
NewAccountUpdateFromReadCloser(body io.ReadCloser) (*authEntities.Account, error)
}

const DefaultRegexPasswordValidation = ""

type UseCases struct {
}

Expand Down Expand Up @@ -202,7 +205,11 @@ func (u *UseCases) NewAccountFromReadCloser(body io.ReadCloser) (*authEntities.A
}

account := createAccount.ToAccount()
return account, account.Validate()
return account, validation.ValidateStruct(account,
validation.Field(&account.Email, validation.Required, validation.Length(1, 255), is.Email),
validation.Field(&account.Password, u.getPasswordValidation()...),
validation.Field(&account.Username, validation.Length(1, 255), validation.Required),
)
}

func (u *UseCases) NewAccountUpdateFromReadCloser(body io.ReadCloser) (*authEntities.Account, error) {
Expand Down Expand Up @@ -241,12 +248,24 @@ func (u *UseCases) NewPasswordFromReadCloser(body io.ReadCloser) (password strin
if body == nil {
return "", errors.ErrorErrorEmptyBody
}
err = json.NewDecoder(body).Decode(&password)
_ = body.Close()
if err != nil {
return "", err
}

buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(body)
password = buf.String()
return password, validation.Validate(password, u.getPasswordValidation()...)
}

return password, validation.Validate(password, validation.Required, validation.Length(1, 255))
func (u *UseCases) getPasswordValidation() []validation.Rule {
return []validation.Rule{
validation.Required,
validation.Length(8, 255),
validation.Match(regexp.MustCompile(`[A-Z]`)).Error("must be a character upper case"),
validation.Match(regexp.MustCompile(`[a-z]`)).Error("must be a character lower case"),
validation.Match(regexp.MustCompile(`[0-9]`)).Error("must be a character digit"),
validation.Match(regexp.MustCompile(`[!@#$&*-._]`)).Error("must be a character special"),
}
}

func (u *UseCases) NewRefreshTokenFromReadCloser(body io.ReadCloser) (token string, err error) {
Expand Down
130 changes: 123 additions & 7 deletions development-kit/pkg/usecases/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,16 +342,60 @@ func TestNewValidateUniqueFromReadCloser(t *testing.T) {
}

func TestNewPasswordFromReadCloser(t *testing.T) {
t.Run("should return no error when valid password", func(t *testing.T) {
bytes, _ := json.Marshal("t3st3c")
t.Run("should return required value when valid password", func(t *testing.T) {
bytes, _ := json.Marshal("")
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewPasswordFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "cannot be blank", err.Error())
})
t.Run("should return not valid length when valid password", func(t *testing.T) {
bytes, _ := json.Marshal("@tEst12")
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewPasswordFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "the length must be between 8 and 255", err.Error())
})
t.Run("should return not valid upper case when valid password", func(t *testing.T) {
bytes, _ := json.Marshal("teesstee")
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewPasswordFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "must be a character upper case", err.Error())
})
t.Run("should return not valid number when valid password", func(t *testing.T) {
bytes, _ := json.Marshal("teesstEE")
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewPasswordFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "must be a character digit", err.Error())
})
t.Run("should return not valid special when valid password", func(t *testing.T) {
bytes, _ := json.Marshal("t33sstEE")
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewPasswordFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "must be a character special", err.Error())
})
t.Run("should validate with success", func(t *testing.T) {
bytes, _ := json.Marshal("@t33sstEE")
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
password, err := useCases.NewPasswordFromReadCloser(readCloser)
assert.NoError(t, err)
assert.Equal(t, "\"t3st3c\"", password)
assert.Equal(t, "@t33sstEE", password)
})

t.Run("should return error when parsing invalid data", func(t *testing.T) {
useCases := NewAuthUseCases()
_, err := useCases.NewPasswordFromReadCloser(nil)
Expand Down Expand Up @@ -427,19 +471,91 @@ func TestNewRefreshTokenFromReadCloser(t *testing.T) {
}

func TestNewAccountFromReadCloser(t *testing.T) {
t.Run("should success parse read closer to account", func(t *testing.T) {
t.Run("should return required value when valid password", func(t *testing.T) {
bytes, _ := json.Marshal(&authEntities.Account{
Email: "test@test.com",
Username: "test",
Password: "test",
Password: "",
AccountID: uuid.New(),
})
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewAccountFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "password: cannot be blank.", err.Error())
})
t.Run("should return not valid length when valid password", func(t *testing.T) {
bytes, _ := json.Marshal(&authEntities.Account{
Email: "test@test.com",
Username: "test",
Password: "@tEst12",
AccountID: uuid.New(),
})
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewAccountFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "password: the length must be between 8 and 255.", err.Error())
})
t.Run("should return not valid upper case when valid password", func(t *testing.T) {
bytes, _ := json.Marshal(&authEntities.Account{
Email: "test@test.com",
Username: "test",
Password: "teesstee",
AccountID: uuid.New(),
})
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewAccountFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "password: must be a character upper case.", err.Error())
})
t.Run("should return not valid number when valid password", func(t *testing.T) {
bytes, _ := json.Marshal(&authEntities.Account{
Email: "test@test.com",
Username: "test",
Password: "teesstEE",
AccountID: uuid.New(),
})
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewAccountFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "password: must be a character digit.", err.Error())
})
t.Run("should return not valid special when valid password", func(t *testing.T) {
bytes, _ := json.Marshal(&authEntities.Account{
Email: "test@test.com",
Username: "test",
Password: "t33sstEE",
AccountID: uuid.New(),
})
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
_, err := useCases.NewAccountFromReadCloser(readCloser)
assert.Error(t, err)
assert.Equal(t, "password: must be a character special.", err.Error())
})
t.Run("should validate with success", func(t *testing.T) {
bytes, _ := json.Marshal(&authEntities.Account{
Email: "test@test.com",
Username: "test",
Password: "@t33sstEE",
AccountID: uuid.New(),
})
readCloser := ioutil.NopCloser(strings.NewReader(string(bytes)))

useCases := NewAuthUseCases()
account, err := useCases.NewAccountFromReadCloser(readCloser)
assert.NoError(t, err)
assert.NotEmpty(t, account)
assert.Equal(t, "@t33sstEE", account.Password)
assert.Equal(t, "test@test.com", account.Email)
assert.Equal(t, "test", account.Username)
})

t.Run("should return error when parsing invalid data", func(t *testing.T) {
Expand Down
18 changes: 17 additions & 1 deletion horusec-auth/internal/controller/account/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ package account

import (
"fmt"
"github.com/ZupIT/horusec/development-kit/pkg/utils/crypto"
"github.com/ZupIT/horusec/development-kit/pkg/utils/logger"
"time"

SQL "github.com/ZupIT/horusec/development-kit/pkg/databases/relational"
Expand Down Expand Up @@ -220,7 +222,10 @@ func (a *Account) ChangePassword(accountID uuid.UUID, password string) error {
if err != nil {
return err
}

if err := a.checkIfPasswordHashIsEqualNewPassword(account.Password, password); err != nil {
logger.LogError("{ACCOUNT} Error on validate password: ", err)
return errors.ErrorInvalidPassword
}
account.Password = password
account.SetPasswordHash()
_ = a.cacheRepository.Del(accountID.String())
Expand Down Expand Up @@ -348,3 +353,14 @@ func (a *Account) GetAccountID(token string) (uuid.UUID, error) {
func (a *Account) UpdateAccount(account *authEntities.Account) error {
return a.accountRepository.Update(account)
}

func (a *Account) checkIfPasswordHashIsEqualNewPassword(passwordHash, newPassword string) error {
if passwordHash == "" || newPassword == "" {
return errors.ErrorNewPasswordOrPasswordHashNotBeEmpty
}
isValid := crypto.CheckPasswordHash(newPassword, passwordHash)
if isValid {
return errors.ErrorNewPasswordNotEqualOldPassword
}
return nil
}
56 changes: 54 additions & 2 deletions horusec-auth/internal/controller/account/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,10 @@ func TestResetPassword(t *testing.T) {
mockWrite := &relational.MockWrite{}
cacheRepositoryMock := &cache.Mock{}

account := &authEntities.Account{}
account := &authEntities.Account{
Password: "Other@Pass123",
}
account.SetPasswordHash()
resp := &response.Response{}

mockRead.On("Find").Return(resp.SetData(account))
Expand All @@ -397,9 +400,58 @@ func TestResetPassword(t *testing.T) {
controller := NewAccountController(brokerMock, mockRead, mockWrite, cacheRepositoryMock, appConfig)
assert.NotNil(t, controller)

err := controller.ChangePassword(uuid.New(), "123456")
err := controller.ChangePassword(uuid.New(), "Ch@ng3m3")
assert.NoError(t, err)
})
t.Run("should return error because password can't be equal current password", func(t *testing.T) {
brokerMock := &broker.Mock{}
mockRead := &relational.MockRead{}
mockWrite := &relational.MockWrite{}
cacheRepositoryMock := &cache.Mock{}

account := &authEntities.Account{
Password: "Ch@ng3m3",
}
account.SetPasswordHash()
resp := &response.Response{}

mockRead.On("Find").Return(resp.SetData(account))
mockRead.On("SetFilter").Return(&gorm.DB{})
mockWrite.On("Update").Return(resp)
cacheRepositoryMock.On("Del").Return(nil)

appConfig := app.NewConfig()
controller := NewAccountController(brokerMock, mockRead, mockWrite, cacheRepositoryMock, appConfig)
assert.NotNil(t, controller)

err := controller.ChangePassword(uuid.New(), "Ch@ng3m3")
assert.Error(t, err)
})

t.Run("should return error because password can't be empty", func(t *testing.T) {
brokerMock := &broker.Mock{}
mockRead := &relational.MockRead{}
mockWrite := &relational.MockWrite{}
cacheRepositoryMock := &cache.Mock{}

account := &authEntities.Account{
Password: "Ch@ng3m3",
}
account.SetPasswordHash()
resp := &response.Response{}

mockRead.On("Find").Return(resp.SetData(account))
mockRead.On("SetFilter").Return(&gorm.DB{})
mockWrite.On("Update").Return(resp)
cacheRepositoryMock.On("Del").Return(nil)

appConfig := app.NewConfig()
controller := NewAccountController(brokerMock, mockRead, mockWrite, cacheRepositoryMock, appConfig)
assert.NotNil(t, controller)

err := controller.ChangePassword(uuid.New(), "")
assert.Error(t, err)
})

t.Run("should return error when finding account", func(t *testing.T) {
brokerMock := &broker.Mock{}
Expand Down
36 changes: 17 additions & 19 deletions horusec-auth/internal/handler/account/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,34 +232,32 @@ func (h *Handler) checkVerifyResetPasswordCodeErrors(w http.ResponseWriter, err
// @Router /api/account/change-password [post]
// @Security ApiKeyAuth
func (h *Handler) ChangePassword(w http.ResponseWriter, r *http.Request) {
accountID, password := h.getChangePasswordData(w, r)
if accountID == uuid.Nil || password == "" {
return
}

err := h.controller.ChangePassword(accountID, password)
if err != nil {
httpUtil.StatusInternalServerError(w, err)
return
}

httpUtil.StatusNoContent(w)
}

func (h *Handler) getChangePasswordData(w http.ResponseWriter, r *http.Request) (uuid.UUID, string) {
accountID, err := h.controller.GetAccountID(r.Header.Get("Authorization"))
if err != nil {
if err != nil || accountID == uuid.Nil {
httpUtil.StatusUnauthorized(w, errors.ErrorDoNotHavePermissionToThisAction)
return uuid.Nil, ""
return
}

password, err := h.useCases.NewPasswordFromReadCloser(r.Body)
if err != nil {
httpUtil.StatusBadRequest(w, errors.ErrorMissingOrInvalidPassword)
return uuid.Nil, ""
return
}
h.executeChangePassword(w, accountID, password)
}

return accountID, password
func (h *Handler) executeChangePassword(w http.ResponseWriter, accountID uuid.UUID, password string) {
err := h.controller.ChangePassword(accountID, password)
switch err {
case errors.ErrorInvalidPassword:
httpUtil.StatusConflict(w, err)
case errors.ErrNotFoundRecords:
httpUtil.StatusNotFound(w, err)
case nil:
httpUtil.StatusNoContent(w)
default:
httpUtil.StatusInternalServerError(w, err)
}
}

// @Tags Account
Expand Down
Loading