123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package admin
- import (
- "github.com/go-playground/validator/v10"
- "github.com/gofiber/fiber/v2"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/auth"
- )
- // nolint
- const errIncorrectOldPassword = "Неверный старый пароль"
- func ChangePassword(
- authService AuthService,
- userRepository UserRepository,
- ) 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 := authService.GetClaims(fctx)
- user, err := userRepository.Get(ctx, claims[auth.ClaimNameKey].(string))
- if err != nil {
- return err
- }
- if authService.IsCorrectPassword(form.OldPassword, user.Password) {
- newPassword, err := authService.GeneratePasswordHash(form.NewPassword)
- if err != nil {
- return err
- }
- if err = userRepository.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")
- }
- }
|