user.go 1.8 KB

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