diff --git a/assembly/assembly.go b/assembly/assembly.go index f6af2a3..0211233 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -33,7 +33,7 @@ type Assembly struct { func New(boot *bootstrap.Bootstrap) (*Assembly, error) { server := grpc.NewServer() httpCli := httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(boot.App.Logger()))) - db := dbrx.New(dbx.WithMigration(boot.MigrationsDir)) + db := dbrx.New(dbx.WithMigrationRunner(boot.MigrationsDir, boot.App.Logger())) bgjobCli := bgjobx.NewClient(db, boot.App.Logger()) return &Assembly{ boot: boot, diff --git a/conf/config_dev.yml b/conf/config_dev.yml new file mode 100644 index 0000000..0d35d39 --- /dev/null +++ b/conf/config_dev.yml @@ -0,0 +1,17 @@ +configServiceAddress: + ip: 10.2.4.244 + port: 9001 +grpcOuterAddress: + #ip: 127.0.0.1 + port: 9007 +grpcInnerAddress: + ip: 0.0.0.0 + port: 9007 +moduleName: msp-admin-service +infraServerPort: 9557 + +logfile: + path: /var/log/msp-admin-service/runtime.log + maxSizeMb: 512 + maxBackups: 4 + compress: true diff --git a/conf/remote.go b/conf/remote.go index 332dbd9..7190961 100644 --- a/conf/remote.go +++ b/conf/remote.go @@ -11,7 +11,7 @@ import ( // nolint: gochecknoinits func init() { // - schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Type) { + schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) { t.Type = "string" t.Enum = []interface{}{"debug", "info", "error", "fatal"} }) diff --git a/controller/user.go b/controller/user.go index 55ff052..9c88b36 100644 --- a/controller/user.go +++ b/controller/user.go @@ -2,6 +2,7 @@ package controller import ( "context" + "github.com/txix-open/isp-kit/grpc/apierrors" "github.com/pkg/errors" "github.com/txix-open/isp-kit/grpc" @@ -18,6 +19,7 @@ type userService interface { DeleteUsers(ctx context.Context, ids []int64, adminId int64) (int, error) Block(ctx context.Context, adminId int64, userId int) error GetById(ctx context.Context, userId int) (*domain.User, error) + ChangePassword(ctx context.Context, adminId int64, oldPassword string, newPassword string) error } type User struct { @@ -211,6 +213,30 @@ func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain return u.userService.GetById(ctx, identities.UserId) } -func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest) error { - return u.userService.ChangePassword(ctx, req) +// ChangePassword +// @Tags user +// @Summary Метод изменения пароля пользователя +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.ChangePasswordRequest true "Тело запроса" +// @Success 200 +// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" +// @Failure 500 {object} domain.GrpcError +// @Router /user/change_password [POST] +func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error { + adminId, err := getAdminId(authData) + if err != nil { + return err + } + + err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword) + switch { + case errors.Is(err, domain.ErrInvalidPassword): + return apierrors.NewBusinessError(1001, "invalid password", err) + case err != nil: + return apierrors.NewInternalServiceError(err) + default: + return nil + } } diff --git a/domain/errors.go b/domain/errors.go index e648178..abeffae 100644 --- a/domain/errors.go +++ b/domain/errors.go @@ -18,6 +18,7 @@ var ( ErrTooManyLoginRequests = errors.New("too many login requests") ErrUserIsBlocked = errors.New("user is blocked") ErrNoActionRequired = errors.New("no action required") + ErrInvalidPassword = errors.New("invalid password") ) type UnknownAuditEventError struct { diff --git a/repository/user.go b/repository/user.go index 0eb6698..7194adf 100644 --- a/repository/user.go +++ b/repository/user.go @@ -231,3 +231,23 @@ func (u User) Block(ctx context.Context, userId int) (*entity.User, error) { } return &user, nil } + +func (u User) ChangePassword(ctx context.Context, userId int64, newPassword string) error { + ctx = sql_metrics.OperationLabelToContext(ctx, "User.ChangePassword") + + q, args, err := query.New(). + Update("users"). + Where(squirrel.Eq{"id": userId}). + Set("password", newPassword). + ToSql() + if err != nil { + return errors.WithMessage(err, "user.repo.ChangePassword: build query") + } + + _, err = u.db.Exec(ctx, q, args...) + if err != nil { + return errors.WithMessage(err, "user.repo.ChangePassword: exec query") + } + + return nil +} diff --git a/routes/routes.go b/routes/routes.go index 9a0b1d3..c96ce9a 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -93,6 +93,11 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.User.GetById, }, + { + Path: "admin/user/change_password", + Inner: true, + Handler: c.User.ChangePassword, + }, { Path: "admin/role/all", Inner: true, diff --git a/service/user.go b/service/user.go index 24aa16c..e9382a0 100644 --- a/service/user.go +++ b/service/user.go @@ -33,6 +33,7 @@ type UserRepo interface { DeleteUser(ctx context.Context, ids []int64) (int, error) Insert(ctx context.Context, user entity.User) (int, error) ChangeBlockStatus(ctx context.Context, userId int) (bool, error) + ChangePassword(ctx context.Context, userId int64, newPassword string) error } type TokenRepo interface { @@ -457,3 +458,26 @@ func diffToString(a map[string]any, b map[string]any) string { result := builder.String() return result[:len(result)-1] } + +func (u User) ChangePassword(ctx context.Context, adminId int64, oldPassword string, newPassword string) error { + admin, err := u.userRepo.GetUserById(ctx, adminId) + if err != nil { + return errors.WithMessage(err, "user.service.ChangePassword: get user by id") + } + + if err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword)); err != nil { + return domain.ErrInvalidPassword + } + + encryptedPassword, errOld := u.cryptPassword(newPassword) + if errOld != nil { + return errors.WithMessage(errOld, "user.service.ChangePassword: crypt old password") + } + + err = u.userRepo.ChangePassword(ctx, adminId, encryptedPassword) + if err != nil { + return errors.WithMessage(err, "user.service.ChangePassword: change password ") + } + + return nil +} diff --git a/tests/audit_test.go b/tests/audit_test.go index 5250822..c4c6c90 100644 --- a/tests/audit_test.go +++ b/tests/audit_test.go @@ -35,7 +35,7 @@ type AuditSuite struct { func (t *AuditSuite) SetupTest() { testInstance, _ := test.New(t.T()) t.test = testInstance - t.db = dbt.New(testInstance, dbx.WithMigration("../migrations")) + t.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) remote := conf.Remote{ Audit: conf.Audit{ diff --git a/tests/auth_test.go b/tests/auth_test.go index 173c04f..8986d8a 100644 --- a/tests/auth_test.go +++ b/tests/auth_test.go @@ -46,7 +46,7 @@ type AuthTestSuite struct { func (s *AuthTestSuite) SetupTest() { testInstance, _ := test.New(s.T()) s.test = testInstance - s.db = dbt.New(testInstance, dbx.WithMigration("../migrations")) + s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) s.httpCli = httpcli.New() mocksrv, host := s.initMockSudir() diff --git a/tests/customization_test.go b/tests/customization_test.go index 71a7f9c..b10746a 100644 --- a/tests/customization_test.go +++ b/tests/customization_test.go @@ -29,7 +29,7 @@ type CustomizationTestSuite struct { func (s *CustomizationTestSuite) SetupTest() { testInstance, _ := test.New(s.T()) s.test = testInstance - s.db = dbt.New(testInstance, dbx.WithMigration("../migrations")) + s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) remote := conf.Remote{ UiDesign: conf.UIDesign{ diff --git a/tests/inactive_test.go b/tests/inactive_test.go index 9988113..62ff583 100644 --- a/tests/inactive_test.go +++ b/tests/inactive_test.go @@ -20,7 +20,7 @@ func TestInactiveWorker(t *testing.T) { t.Parallel() test, require := test.New(t) - db := dbt.New(test, dbx.WithMigration("../migrations")) + db := dbt.New(test, dbx.WithMigrationRunner("../migrations", test.Logger())) userId := InsertUser(db, entity.User{Email: "a@test"}) InsertUser(db, entity.User{Email: "b@test"}) diff --git a/tests/secure_test.go b/tests/secure_test.go index 908590a..56a3c5e 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -34,7 +34,7 @@ type SecureSuite struct { func (s *SecureSuite) SetupTest() { s.test, s.require = test.New(s.T()) - s.db = dbt.New(s.test, dbx.WithMigration("../migrations")) + s.db = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger())) httpCli := httpcli.New() remote := conf.Remote{ ExpireSec: 3600, diff --git a/tests/user_test.go b/tests/user_test.go index 9f309b3..237df04 100644 --- a/tests/user_test.go +++ b/tests/user_test.go @@ -2,6 +2,8 @@ package tests_test import ( "context" + "github.com/txix-open/isp-kit/grpc/apierrors" + "golang.org/x/crypto/bcrypt" "strconv" "testing" "time" @@ -45,7 +47,7 @@ type UserTestSuite struct { func (s *UserTestSuite) SetupTest() { testInstance, _ := test.New(s.T()) s.test = testInstance - s.db = dbt.New(testInstance, dbx.WithMigration("../migrations")) + s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) s.httpCli = httpcli.New() remote := conf.Remote{ @@ -338,3 +340,34 @@ func (s *UserTestSuite) TestBlockUser() { s.Require().NoError(err) s.EqualValues(entity.TokenStatusRevoked, t.Status) } + +func (s *UserTestSuite) TestChangePasswordUser() { + // insert user with old password + adminId := InsertUser(s.db, entity.User{Email: "a_del@a.ru", Password: "password"}) + + // check for err when invalid data + invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"} + err := s.grpcCli.Invoke("admin/user/change_password"). + AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). + JsonRequestBody(invalidReq). + Do(context.Background()) + s.Require().Error(err) + err = apierrors.FromError(err) + s.Require().Contains(err.Error(), "1001") + + // change password + changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"} + err = s.grpcCli.Invoke("admin/user/change_password"). + AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). + JsonRequestBody(changePswReq). + Do(context.Background()) + + s.Require().NoError(err) + + var newPassword string + s.db.Must().SelectRow(&newPassword, "select password from users where id = $1", adminId) + + notEqualErr := bcrypt.CompareHashAndPassword([]byte(newPassword), []byte(changePswReq.NewPassword)) + s.Require().NoError(notEqualErr) + +}