add_user.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package user
  2. import (
  3. "strings"
  4. "git.dmitriygnatenko.ru/dima/homethings/internal/dto"
  5. "git.dmitriygnatenko.ru/dima/homethings/internal/factory"
  6. "git.dmitriygnatenko.ru/dima/homethings/internal/interfaces"
  7. "github.com/go-playground/validator/v10"
  8. "github.com/gofiber/fiber/v2"
  9. )
  10. // @Router /api/v1/users [post]
  11. // @Param data body dto.AddUserRequest true "Request body"
  12. // @Success 200 {object} dto.EmptyResponse
  13. // @Failure 400 {object} dto.ErrorResponse
  14. // @Failure 500 {object} dto.ErrorResponse
  15. // @Summary Add user
  16. // @Tags Users
  17. // @security APIKey
  18. // @Accept json
  19. // @Produce json
  20. func AddUserHandler(sp interfaces.ServiceProvider) fiber.Handler {
  21. return func(fctx *fiber.Ctx) error {
  22. ctx := fctx.Context()
  23. req := dto.AddUserRequest{}
  24. if err := fctx.BodyParser(&req); err != nil {
  25. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  26. }
  27. var validate = validator.New()
  28. if err := validate.Struct(req); err != nil {
  29. return fctx.Status(fiber.StatusBadRequest).JSON(factory.CreateValidateErrorResponse(err))
  30. }
  31. hash, err := sp.GetAuthService().GeneratePasswordHash(strings.TrimSpace(req.Password))
  32. if err != nil {
  33. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  34. }
  35. _, err = sp.GetUserRepository().Add(ctx, strings.TrimSpace(req.Username), hash)
  36. if err != nil {
  37. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  38. }
  39. return fctx.JSON(factory.CreateEmptyResponse())
  40. }
  41. }