user.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package admin
  2. import (
  3. "git.dmitriygnatenko.ru/dima/go-common/logger"
  4. "github.com/go-playground/validator/v10"
  5. "github.com/gofiber/fiber/v2"
  6. helper "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/helpers/i18n"
  7. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/mapper"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
  9. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/auth"
  10. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/services/i18n"
  11. )
  12. func ChangePassword(
  13. authService AuthService,
  14. userRepository UserRepository,
  15. ) fiber.Handler {
  16. return func(fctx *fiber.Ctx) error {
  17. ctx := fctx.Context()
  18. lang := mapper.LanguageFromContext(fctx)
  19. var validate = validator.New()
  20. validateErrors := make(map[string]string)
  21. trans, err := helper.GetDefaultTranslator(validate)
  22. if err != nil {
  23. logger.Error(ctx, err.Error())
  24. return err
  25. }
  26. form := models.ChangePasswordForm{}
  27. if fctx.Method() == fiber.MethodPost {
  28. if err = fctx.BodyParser(&form); err != nil {
  29. logger.Info(ctx, err.Error())
  30. return err
  31. }
  32. if err = validate.Struct(form); err != nil {
  33. validateErrors = helper.FormatValidateErrors(err, trans)
  34. }
  35. if len(validateErrors) == 0 {
  36. claims := authService.GetClaims(fctx)
  37. user, err := userRepository.Get(ctx, claims[auth.ClaimNameKey].(string))
  38. if err != nil {
  39. logger.Error(ctx, err.Error())
  40. return err
  41. }
  42. if authService.IsCorrectPassword(form.OldPassword, user.Password) {
  43. newPassword, err := authService.GeneratePasswordHash(form.NewPassword)
  44. if err != nil {
  45. logger.Error(ctx, err.Error())
  46. return err
  47. }
  48. if err = userRepository.UpdatePassword(ctx, user.ID, newPassword); err != nil {
  49. logger.Error(ctx, err.Error())
  50. return err
  51. }
  52. return fctx.Redirect("/admin")
  53. }
  54. validateErrors["ChangePasswordForm.OldPassword"] = i18n.T(lang, "admin_incorrect_old_password")
  55. }
  56. }
  57. return fctx.Render("admin/user_change_password", fiber.Map{
  58. "form": form,
  59. "errors": validateErrors,
  60. "section": "change_password",
  61. "title": i18n.T(lang, "admin_change_password_title"),
  62. }, "admin/_layout")
  63. }
  64. }