1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package admin
- import (
- "git.dmitriygnatenko.ru/dima/go-common/logger"
- "github.com/go-playground/validator/v10"
- "github.com/gofiber/fiber/v2"
- helper "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers/i18n"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/auth"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/i18n"
- )
- func ChangePassword(
- authService AuthService,
- userRepository UserRepository,
- ) fiber.Handler {
- return func(fctx *fiber.Ctx) error {
- ctx := fctx.Context()
- lang := i18n.Language(fctx)
- var validate = validator.New()
- validateErrors := make(map[string]string)
- trans, err := helper.GetDefaultTranslator(validate)
- if err != nil {
- logger.Error(ctx, err.Error())
- return err
- }
- form := models.ChangePasswordForm{}
- if fctx.Method() == fiber.MethodPost {
- if err = fctx.BodyParser(&form); err != nil {
- logger.Info(ctx, err.Error())
- return err
- }
- if err = validate.Struct(form); err != nil {
- validateErrors = helper.FormatValidateErrors(err, trans)
- }
- if len(validateErrors) == 0 {
- claims := authService.GetClaims(fctx)
- user, err := userRepository.Get(ctx, claims[auth.ClaimNameKey].(string))
- if err != nil {
- logger.Error(ctx, err.Error())
- return err
- }
- if authService.IsCorrectPassword(form.OldPassword, user.Password) {
- newPassword, err := authService.GeneratePasswordHash(form.NewPassword)
- if err != nil {
- logger.Error(ctx, err.Error())
- return err
- }
- if err = userRepository.UpdatePassword(ctx, user.ID, newPassword); err != nil {
- logger.Error(ctx, err.Error())
- return err
- }
- return fctx.Redirect("/admin")
- }
- validateErrors["ChangePasswordForm.OldPassword"] = i18n.T(lang, "admin_incorrect_old_password")
- }
- }
- return fctx.Render("admin/user_change_password", fiber.Map{
- "form": form,
- "errors": validateErrors,
- "section": "change_password",
- "title": i18n.T(lang, "admin_change_password_title"),
- }, "admin/_layout")
- }
- }
|