user.go 2.1 KB

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