user.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package admin
  2. import (
  3. "github.com/go-playground/validator/v10"
  4. "github.com/gofiber/fiber/v2"
  5. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers"
  6. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
  7. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/auth"
  8. )
  9. // nolint
  10. const errIncorrectOldPassword = "Неверный старый пароль"
  11. func ChangePassword(
  12. authService AuthService,
  13. userRepository UserRepository,
  14. ) fiber.Handler {
  15. return func(fctx *fiber.Ctx) error {
  16. ctx := fctx.Context()
  17. var validate = validator.New()
  18. validateErrors := make(map[string]string)
  19. trans, err := helpers.GetDefaultTranslator(validate)
  20. if err != nil {
  21. return err
  22. }
  23. form := models.ChangePasswordForm{}
  24. if fctx.Method() == fiber.MethodPost {
  25. if err = fctx.BodyParser(&form); err != nil {
  26. return err
  27. }
  28. if err = validate.Struct(form); err != nil {
  29. validateErrors = helpers.FormatValidateErrors(err, trans)
  30. }
  31. if len(validateErrors) == 0 {
  32. claims := authService.GetClaims(fctx)
  33. user, err := userRepository.Get(ctx, claims[auth.ClaimNameKey].(string))
  34. if err != nil {
  35. return err
  36. }
  37. if authService.IsCorrectPassword(form.OldPassword, user.Password) {
  38. newPassword, err := authService.GeneratePasswordHash(form.NewPassword)
  39. if err != nil {
  40. return err
  41. }
  42. if err = userRepository.UpdatePassword(ctx, user.ID, newPassword); err != nil {
  43. return err
  44. }
  45. return fctx.Redirect("/admin")
  46. }
  47. validateErrors["ChangePasswordForm.OldPassword"] = errIncorrectOldPassword
  48. }
  49. }
  50. return fctx.Render("admin/user_change_password", fiber.Map{
  51. "form": form,
  52. "errors": validateErrors,
  53. "section": "change_password",
  54. "title": "Изменение пароля",
  55. }, "admin/_layout")
  56. }
  57. }