update_user.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package user
  2. import (
  3. "database/sql"
  4. "strings"
  5. "git.dmitriygnatenko.ru/dima/homethings/internal/dto"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/factory"
  7. "git.dmitriygnatenko.ru/dima/homethings/internal/interfaces"
  8. "git.dmitriygnatenko.ru/dima/homethings/internal/mappers"
  9. "github.com/gofiber/fiber/v2"
  10. )
  11. // @Router /api/v1/users [put]
  12. // @Param data body dto.UpdateUserRequest true "Request body"
  13. // @Success 200 {object} dto.EmptyResponse
  14. // @Failure 400 {object} dto.ErrorResponse
  15. // @Failure 500 {object} dto.ErrorResponse
  16. // @Summary Update user
  17. // @Tags Users
  18. // @security APIKey
  19. // @Accept json
  20. // @Produce json
  21. func UpdateUserHandler(sp interfaces.ServiceProvider) fiber.Handler {
  22. return func(fctx *fiber.Ctx) error {
  23. var err error
  24. var username, password string
  25. ctx := fctx.Context()
  26. req := dto.UpdateUserRequest{}
  27. if err = fctx.BodyParser(&req); err != nil {
  28. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  29. }
  30. if req.Username != nil {
  31. username = strings.TrimSpace(*req.Username)
  32. }
  33. if req.Password != nil {
  34. password, err = sp.GetAuthService().GeneratePasswordHash(strings.TrimSpace(*req.Password))
  35. if err != nil {
  36. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  37. }
  38. }
  39. if username == "" && password == "" {
  40. return fiber.NewError(fiber.StatusBadRequest, "")
  41. }
  42. claims := sp.GetAuthService().GetClaims(fctx)
  43. user, err := sp.GetUserRepository().Get(ctx, claims["name"].(string))
  44. if err != nil {
  45. if err == sql.ErrNoRows {
  46. return fiber.NewError(fiber.StatusBadRequest, "")
  47. }
  48. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  49. }
  50. req.Password = &password
  51. req.Username = &username
  52. err = sp.GetUserRepository().Update(ctx, mappers.ConvertToUpdateUserRequestModel(user.ID, req))
  53. if err != nil {
  54. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  55. }
  56. return fctx.JSON(factory.CreateEmptyResponse())
  57. }
  58. }