update_user.go 2.0 KB

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