altervisi0n

Untitled

Dec 14th, 2025
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 9.75 KB | None | 0 0
  1. package handlers
  2.  
  3. import (
  4.     "net/http"
  5.     "strconv"
  6.  
  7.     "Visitked/models"
  8.     "Visitked/services"
  9.     "Visitked/utils"
  10.  
  11.     "github.com/gin-gonic/gin"
  12. )
  13.  
  14. type CardHandler struct {
  15.     cardService         *services.CardService
  16.     subscriptionService *services.SubscriptionService
  17.     analyticsService    *services.AnalyticsService
  18. }
  19.  
  20. func NewCardHandler(
  21.     cardService *services.CardService,
  22.     subscriptionService *services.SubscriptionService,
  23.     analyticsService *services.AnalyticsService,
  24. ) *CardHandler {
  25.     return &CardHandler{
  26.         cardService:         cardService,
  27.         subscriptionService: subscriptionService,
  28.         analyticsService:    analyticsService,
  29.     }
  30. }
  31.  
  32. // CreateCard создает новую цифровую визитную карточку
  33. func (h *CardHandler) CreateCard(c *gin.Context) {
  34.     userID, exists := c.Get("userID")
  35.     if !exists {
  36.         c.JSON(http.StatusUnauthorized, gin.H{
  37.             "error": "User not authenticated",
  38.             "code":  "AUTHENTICATION_REQUIRED",
  39.         })
  40.         return
  41.     }
  42.  
  43.     var cardData models.CardInput
  44.     if err := c.ShouldBindJSON(&cardData); err != nil {
  45.         utils.LogSecurityEvent("invalid_card_data", userID.(string), c.ClientIP(), map[string]interface{}{
  46.             "error": err.Error(),
  47.         })
  48.         c.JSON(http.StatusBadRequest, gin.H{
  49.             "error":   "Invalid card data",
  50.             "details": err.Error(),
  51.             "code":    "INVALID_INPUT",
  52.         })
  53.         return
  54.     }
  55.  
  56.     // Проверка лимитов подписки
  57.     canCreate, err := h.subscriptionService.CanCreateCard(userID.(string))
  58.     if err != nil {
  59.         utils.LogError("Failed to check subscription limits", err, map[string]interface{}{
  60.             "user_id": userID,
  61.         })
  62.         c.JSON(http.StatusInternalServerError, gin.H{
  63.             "error": "Failed to check subscription limits",
  64.             "code":  "SUBSCRIPTION_CHECK_FAILED",
  65.         })
  66.         return
  67.     }
  68.  
  69.     if !canCreate {
  70.         utils.LogSecurityEvent("subscription_limit_exceeded", userID.(string), c.ClientIP(), nil)
  71.         c.JSON(http.StatusForbidden, gin.H{
  72.             "error": "Card creation limit reached for your subscription plan",
  73.             "code":  "SUBSCRIPTION_LIMIT_REACHED",
  74.         })
  75.         return
  76.     }
  77.  
  78.     // Валидация входных данных
  79.     if err := h.validateCardData(cardData); err != nil {
  80.         c.JSON(http.StatusBadRequest, gin.H{
  81.             "error":   "Validation failed",
  82.             "details": err.Error(),
  83.             "code":    "VALIDATION_FAILED",
  84.         })
  85.         return
  86.     }
  87.  
  88.     // Создание карточки
  89.     card, err := h.cardService.CreateCard(userID.(string), cardData)
  90.     if err != nil {
  91.         utils.LogError("Failed to create card", err, map[string]interface{}{
  92.             "user_id":   userID,
  93.             "card_data": cardData,
  94.         })
  95.         c.JSON(http.StatusInternalServerError, gin.H{
  96.             "error":   "Failed to create card",
  97.             "details": err.Error(),
  98.             "code":    "CARD_CREATION_FAILED",
  99.         })
  100.         return
  101.     }
  102.  
  103.     // Логирование успешного создания
  104.     utils.LogInfo("Card created successfully", map[string]interface{}{
  105.         "user_id": userID,
  106.         "card_id": card.ID,
  107.     })
  108.  
  109.     c.JSON(http.StatusCreated, gin.H{
  110.         "message": "Card created successfully",
  111.         "card":    card,
  112.     })
  113. }
  114.  
  115. // GetCards возвращает список карточек пользователя
  116. func (h *CardHandler) GetCards(c *gin.Context) {
  117.     userID, exists := c.Get("userID")
  118.     if !exists {
  119.         c.JSON(http.StatusUnauthorized, gin.H{
  120.             "error": "User not authenticated",
  121.             "code":  "AUTHENTICATION_REQUIRED",
  122.         })
  123.         return
  124.     }
  125.  
  126.     // Параметры пагинации
  127.     limitStr := c.DefaultQuery("limit", "10")
  128.     offsetStr := c.DefaultQuery("offset", "0")
  129.  
  130.     limit, err := strconv.Atoi(limitStr)
  131.     if err != nil || limit < 1 || limit > 100 {
  132.         limit = 10
  133.     }
  134.  
  135.     offset, err := strconv.Atoi(offsetStr)
  136.     if err != nil || offset < 0 {
  137.         offset = 0
  138.     }
  139.  
  140.     cards, total, err := h.cardService.GetUserCards(userID.(string), limit, offset)
  141.     if err != nil {
  142.         utils.LogError("Failed to get user cards", err, map[string]interface{}{
  143.             "user_id": userID,
  144.         })
  145.         c.JSON(http.StatusInternalServerError, gin.H{
  146.             "error": "Failed to retrieve cards",
  147.             "code":  "CARDS_RETRIEVAL_FAILED",
  148.         })
  149.         return
  150.     }
  151.  
  152.     c.JSON(http.StatusOK, gin.H{
  153.         "cards":  cards,
  154.         "total":  total,
  155.         "limit":  limit,
  156.         "offset": offset,
  157.     })
  158. }
  159.  
  160. // GetPublicCard возвращает публичную карточку по URL
  161. func (h *CardHandler) GetPublicCard(c *gin.Context) {
  162.     publicURL := c.Param("url")
  163.     if publicURL == "" {
  164.         c.JSON(http.StatusBadRequest, gin.H{
  165.             "error": "Public URL is required",
  166.             "code":  "MISSING_PUBLIC_URL",
  167.         })
  168.         return
  169.     }
  170.  
  171.     card, err := h.cardService.GetCardByPublicURL(publicURL)
  172.     if err != nil {
  173.         c.JSON(http.StatusNotFound, gin.H{
  174.             "error": "Card not found or inactive",
  175.             "code":  "CARD_NOT_FOUND",
  176.         })
  177.         return
  178.     }
  179.  
  180.     // Запись просмотра для аналитики
  181.     viewData := models.AnalyticsView{
  182.         CardID:    card.ID,
  183.         ViewerIP:  c.ClientIP(),
  184.         UserAgent: c.GetHeader("User-Agent"),
  185.         Referrer:  c.GetHeader("Referer"),
  186.     }
  187.  
  188.     // Асинхронная запись аналитики (не блокируем ответ)
  189.     go func() {
  190.         if err := h.analyticsService.RecordView(viewData); err != nil {
  191.             utils.LogError("Failed to record card view", err, map[string]interface{}{
  192.                 "card_id": card.ID,
  193.                 "ip":      viewData.ViewerIP,
  194.             })
  195.         }
  196.     }()
  197.  
  198.     // Увеличение счетчика просмотров
  199.     go func() {
  200.         if err := h.cardService.IncrementViewCount(card.ID); err != nil {
  201.             utils.LogError("Failed to increment view count", err, map[string]interface{}{
  202.                 "card_id": card.ID,
  203.             })
  204.         }
  205.     }()
  206.  
  207.     c.JSON(http.StatusOK, gin.H{
  208.         "card": card,
  209.     })
  210. }
  211.  
  212. // UpdateCard обновляет существующую карточку
  213. func (h *CardHandler) UpdateCard(c *gin.Context) {
  214.     userID, exists := c.Get("userID")
  215.     if !exists {
  216.         c.JSON(http.StatusUnauthorized, gin.H{
  217.             "error": "User not authenticated",
  218.             "code":  "AUTHENTICATION_REQUIRED",
  219.         })
  220.         return
  221.     }
  222.  
  223.     cardID := c.Param("id")
  224.     if cardID == "" {
  225.         c.JSON(http.StatusBadRequest, gin.H{
  226.             "error": "Card ID is required",
  227.             "code":  "MISSING_CARD_ID",
  228.         })
  229.         return
  230.     }
  231.  
  232.     var updateData models.CardUpdate
  233.     if err := c.ShouldBindJSON(&updateData); err != nil {
  234.         c.JSON(http.StatusBadRequest, gin.H{
  235.             "error":   "Invalid update data",
  236.             "details": err.Error(),
  237.             "code":    "INVALID_INPUT",
  238.         })
  239.         return
  240.     }
  241.  
  242.     // Проверка прав доступа к карточке
  243.     hasAccess, err := h.cardService.UserHasAccessToCard(userID.(string), cardID)
  244.     if err != nil {
  245.         c.JSON(http.StatusInternalServerError, gin.H{
  246.             "error": "Failed to verify card access",
  247.             "code":  "ACCESS_VERIFICATION_FAILED",
  248.         })
  249.         return
  250.     }
  251.  
  252.     if !hasAccess {
  253.         utils.LogSecurityEvent("unauthorized_card_access", userID.(string), c.ClientIP(), map[string]interface{}{
  254.             "card_id": cardID,
  255.             "action":  "update",
  256.         })
  257.         c.JSON(http.StatusForbidden, gin.H{
  258.             "error": "Access denied",
  259.             "code":  "ACCESS_DENIED",
  260.         })
  261.         return
  262.     }
  263.  
  264.     // Обновление карточки
  265.     card, err := h.cardService.UpdateCard(cardID, updateData)
  266.     if err != nil {
  267.         utils.LogError("Failed to update card", err, map[string]interface{}{
  268.             "user_id":     userID,
  269.             "card_id":     cardID,
  270.             "update_data": updateData,
  271.         })
  272.         c.JSON(http.StatusInternalServerError, gin.H{
  273.             "error":   "Failed to update card",
  274.             "details": err.Error(),
  275.             "code":    "CARD_UPDATE_FAILED",
  276.         })
  277.         return
  278.     }
  279.  
  280.     utils.LogInfo("Card updated successfully", map[string]interface{}{
  281.         "user_id": userID,
  282.         "card_id": cardID,
  283.     })
  284.  
  285.     c.JSON(http.StatusOK, gin.H{
  286.         "message": "Card updated successfully",
  287.         "card":    card,
  288.     })
  289. }
  290.  
  291. // DeleteCard удаляет карточку
  292. func (h *CardHandler) DeleteCard(c *gin.Context) {
  293.     userID, exists := c.Get("userID")
  294.     if !exists {
  295.         c.JSON(http.StatusUnauthorized, gin.H{
  296.             "error": "User not authenticated",
  297.             "code":  "AUTHENTICATION_REQUIRED",
  298.         })
  299.         return
  300.     }
  301.  
  302.     cardID := c.Param("id")
  303.     if cardID == "" {
  304.         c.JSON(http.StatusBadRequest, gin.H{
  305.             "error": "Card ID is required",
  306.             "code":  "MISSING_CARD_ID",
  307.         })
  308.         return
  309.     }
  310.  
  311.     // Проверка прав доступа
  312.     hasAccess, err := h.cardService.UserHasAccessToCard(userID.(string), cardID)
  313.     if err != nil {
  314.         c.JSON(http.StatusInternalServerError, gin.H{
  315.             "error": "Failed to verify card access",
  316.             "code":  "ACCESS_VERIFICATION_FAILED",
  317.         })
  318.         return
  319.     }
  320.  
  321.     if !hasAccess {
  322.         utils.LogSecurityEvent("unauthorized_card_access", userID.(string), c.ClientIP(), map[string]interface{}{
  323.             "card_id": cardID,
  324.             "action":  "delete",
  325.         })
  326.         c.JSON(http.StatusForbidden, gin.H{
  327.             "error": "Access denied",
  328.             "code":  "ACCESS_DENIED",
  329.         })
  330.         return
  331.     }
  332.  
  333.     // Удаление карточки
  334.     if err := h.cardService.DeleteCard(cardID); err != nil {
  335.         utils.LogError("Failed to delete card", err, map[string]interface{}{
  336.             "user_id": userID,
  337.             "card_id": cardID,
  338.         })
  339.         c.JSON(http.StatusInternalServerError, gin.H{
  340.             "error": "Failed to delete card",
  341.             "code":  "CARD_DELETION_FAILED",
  342.         })
  343.         return
  344.     }
  345.  
  346.     utils.LogInfo("Card deleted successfully", map[string]interface{}{
  347.         "user_id": userID,
  348.         "card_id": cardID,
  349.     })
  350.  
  351.     c.JSON(http.StatusOK, gin.H{
  352.         "message": "Card deleted successfully",
  353.     })
  354. }
  355.  
  356. // validateCardData валидирует данные карточки
  357. func (h *CardHandler) validateCardData(data models.CardInput) error {
  358.     if data.Name == "" {
  359.         return fmt.Errorf("name is required")
  360.     }
  361.  
  362.     if data.Email == "" {
  363.         return fmt.Errorf("email is required")
  364.     }
  365.  
  366.     if !utils.IsValidEmail(data.Email) {
  367.         return fmt.Errorf("invalid email format")
  368.     }
  369.  
  370.     if data.Phone != "" && !utils.IsValidPhone(data.Phone) {
  371.         return fmt.Errorf("invalid phone format")
  372.     }
  373.  
  374.     if data.Website != "" && !utils.IsValidURL(data.Website) {
  375.         return fmt.Errorf("invalid website URL")
  376.     }
  377.  
  378.     return nil
  379. }
Advertisement
Add Comment
Please, Sign In to add comment