check_auth.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package auth
  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. "database/sql"
  8. "errors"
  9. "github.com/gofiber/fiber/v2"
  10. "github.com/golang-jwt/jwt/v4"
  11. "git.dmitriygnatenko.ru/dima/homethings/internal/mappers"
  12. "git.dmitriygnatenko.ru/dima/homethings/internal/models"
  13. )
  14. type (
  15. AuthService interface {
  16. GetClaims(fctx *fiber.Ctx) jwt.MapClaims
  17. IsCorrectPassword(password string, hash string) bool
  18. GenerateToken(user models.User) (string, error)
  19. }
  20. UserRepository interface {
  21. Get(ctx context.Context, username string) (*models.User, error)
  22. }
  23. )
  24. // @Router /api/v1/auth/check [get]
  25. // @Success 200 {object} dto.UserResponse
  26. // @Failure 403 {object} dto.ErrorResponse
  27. // @Failure 500 {object} dto.ErrorResponse
  28. // @Summary Check auth
  29. // @Tags Auth
  30. // @Accept json
  31. // @Produce json
  32. func CheckAuthHandler(
  33. authService AuthService,
  34. userRepository UserRepository,
  35. ) fiber.Handler {
  36. return func(fctx *fiber.Ctx) error {
  37. ctx := fctx.Context()
  38. claims := authService.GetClaims(fctx)
  39. user, err := userRepository.Get(ctx, claims["name"].(string))
  40. if err != nil {
  41. if errors.Is(err, sql.ErrNoRows) {
  42. return fiber.NewError(fiber.StatusForbidden, "")
  43. }
  44. return fiber.NewError(fiber.StatusInternalServerError, err.Error())
  45. }
  46. return fctx.JSON(mappers.ToUserResponse(*user))
  47. }
  48. }