update_user.go 2.2 KB

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