1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package admin
- import (
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/interfaces"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
- "github.com/go-playground/validator/v10"
- "github.com/gofiber/fiber/v2"
- )
- // nolint
- const errIncorrectOldPassword = "Неверный старый пароль"
- func ChangePassword(sp interfaces.ServiceProvider) fiber.Handler {
- return func(fctx *fiber.Ctx) error {
- ctx := fctx.Context()
- var validate = validator.New()
- validateErrors := make(map[string]string)
- trans, err := helpers.GetDefaultTranslator(validate)
- if err != nil {
- return err
- }
- form := models.ChangePasswordForm{}
- if fctx.Method() == fiber.MethodPost {
- if err = fctx.BodyParser(&form); err != nil {
- return err
- }
- if err = validate.Struct(form); err != nil {
- validateErrors = helpers.FormatValidateErrors(err, trans)
- }
- if len(validateErrors) == 0 {
- claims := sp.GetAuthService().GetClaims(fctx)
- user, err := sp.GetUserRepository().Get(ctx, claims["name"].(string))
- if err != nil {
- return err
- }
- if sp.GetAuthService().IsCorrectPassword(form.OldPassword, user.Password) {
- newPassword, err := sp.GetAuthService().GeneratePasswordHash(form.NewPassword)
- if err != nil {
- return err
- }
- if err = sp.GetUserRepository().UpdatePassword(ctx, user.ID, newPassword); err != nil {
- return err
- }
- return fctx.Redirect("/admin")
- }
- validateErrors["ChangePasswordForm.OldPassword"] = errIncorrectOldPassword
- }
- }
- return fctx.Render("admin/user_change_password", fiber.Map{
- "form": form,
- "errors": validateErrors,
- "section": "change_password",
- "title": "Изменение пароля",
- }, "admin/_layout")
- }
- }
|