add_user.go 2.2 KB

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