add_user.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package user
  2. //go:generate mkdir -p mocks
  3. //go:generate rm -rf ./mocks/*_minimock.go
  4. //go:generate minimock -i AuthService,UserRepository -o ./mocks/ -s "_minimock.go"
  5. import (
  6. "context"
  7. "strings"
  8. "github.com/go-playground/validator/v10"
  9. "github.com/gofiber/fiber/v2"
  10. "github.com/golang-jwt/jwt/v4"
  11. "git.dmitriygnatenko.ru/dima/homethings/internal/dto"
  12. "git.dmitriygnatenko.ru/dima/homethings/internal/factory"
  13. "git.dmitriygnatenko.ru/dima/homethings/internal/models"
  14. )
  15. type (
  16. AuthService interface {
  17. GeneratePasswordHash(password string) (string, error)
  18. GetClaims(fctx *fiber.Ctx) jwt.MapClaims
  19. }
  20. UserRepository interface {
  21. Get(ctx context.Context, username string) (*models.User, error)
  22. Add(ctx context.Context, username string, password string) (int, error)
  23. Update(ctx context.Context, req models.UpdateUserRequest) error
  24. }
  25. )
  26. // @Router /api/v1/users [post]
  27. // @Param data body dto.AddUserRequest true "Request body"
  28. // @Success 200 {object} dto.EmptyResponse
  29. // @Failure 400 {object} dto.ErrorResponse
  30. // @Failure 500 {object} dto.ErrorResponse
  31. // @Summary Add user
  32. // @Tags Users
  33. // @security APIKey
  34. // @Accept json
  35. // @Produce json
  36. func AddUserHandler(
  37. authService AuthService,
  38. userRepository UserRepository,
  39. ) fiber.Handler {
  40. return func(fctx *fiber.Ctx) error {
  41. ctx := fctx.Context()
  42. req := dto.AddUserRequest{}
  43. if err := fctx.BodyParser(&req); err != nil {
  44. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  45. }
  46. var validate = validator.New()
  47. if err := validate.Struct(req); err != nil {
  48. return fctx.Status(fiber.StatusBadRequest).JSON(factory.CreateValidateErrorResponse(err))
  49. }
  50. hash, err := authService.GeneratePasswordHash(strings.TrimSpace(req.Password))
  51. if err != nil {
  52. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  53. }
  54. _, err = userRepository.Add(ctx, strings.TrimSpace(req.Username), hash)
  55. if err != nil {
  56. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  57. }
  58. return fctx.JSON(factory.CreateEmptyResponse())
  59. }
  60. }