Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package handlers
- import (
- "net/http"
- "strconv"
- "Visitked/models"
- "Visitked/services"
- "Visitked/utils"
- "github.com/gin-gonic/gin"
- )
- type CardHandler struct {
- cardService *services.CardService
- subscriptionService *services.SubscriptionService
- analyticsService *services.AnalyticsService
- }
- func NewCardHandler(
- cardService *services.CardService,
- subscriptionService *services.SubscriptionService,
- analyticsService *services.AnalyticsService,
- ) *CardHandler {
- return &CardHandler{
- cardService: cardService,
- subscriptionService: subscriptionService,
- analyticsService: analyticsService,
- }
- }
- // CreateCard создает новую цифровую визитную карточку
- func (h *CardHandler) CreateCard(c *gin.Context) {
- userID, exists := c.Get("userID")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{
- "error": "User not authenticated",
- "code": "AUTHENTICATION_REQUIRED",
- })
- return
- }
- var cardData models.CardInput
- if err := c.ShouldBindJSON(&cardData); err != nil {
- utils.LogSecurityEvent("invalid_card_data", userID.(string), c.ClientIP(), map[string]interface{}{
- "error": err.Error(),
- })
- c.JSON(http.StatusBadRequest, gin.H{
- "error": "Invalid card data",
- "details": err.Error(),
- "code": "INVALID_INPUT",
- })
- return
- }
- // Проверка лимитов подписки
- canCreate, err := h.subscriptionService.CanCreateCard(userID.(string))
- if err != nil {
- utils.LogError("Failed to check subscription limits", err, map[string]interface{}{
- "user_id": userID,
- })
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": "Failed to check subscription limits",
- "code": "SUBSCRIPTION_CHECK_FAILED",
- })
- return
- }
- if !canCreate {
- utils.LogSecurityEvent("subscription_limit_exceeded", userID.(string), c.ClientIP(), nil)
- c.JSON(http.StatusForbidden, gin.H{
- "error": "Card creation limit reached for your subscription plan",
- "code": "SUBSCRIPTION_LIMIT_REACHED",
- })
- return
- }
- // Валидация входных данных
- if err := h.validateCardData(cardData); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "error": "Validation failed",
- "details": err.Error(),
- "code": "VALIDATION_FAILED",
- })
- return
- }
- // Создание карточки
- card, err := h.cardService.CreateCard(userID.(string), cardData)
- if err != nil {
- utils.LogError("Failed to create card", err, map[string]interface{}{
- "user_id": userID,
- "card_data": cardData,
- })
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": "Failed to create card",
- "details": err.Error(),
- "code": "CARD_CREATION_FAILED",
- })
- return
- }
- // Логирование успешного создания
- utils.LogInfo("Card created successfully", map[string]interface{}{
- "user_id": userID,
- "card_id": card.ID,
- })
- c.JSON(http.StatusCreated, gin.H{
- "message": "Card created successfully",
- "card": card,
- })
- }
- // GetCards возвращает список карточек пользователя
- func (h *CardHandler) GetCards(c *gin.Context) {
- userID, exists := c.Get("userID")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{
- "error": "User not authenticated",
- "code": "AUTHENTICATION_REQUIRED",
- })
- return
- }
- // Параметры пагинации
- limitStr := c.DefaultQuery("limit", "10")
- offsetStr := c.DefaultQuery("offset", "0")
- limit, err := strconv.Atoi(limitStr)
- if err != nil || limit < 1 || limit > 100 {
- limit = 10
- }
- offset, err := strconv.Atoi(offsetStr)
- if err != nil || offset < 0 {
- offset = 0
- }
- cards, total, err := h.cardService.GetUserCards(userID.(string), limit, offset)
- if err != nil {
- utils.LogError("Failed to get user cards", err, map[string]interface{}{
- "user_id": userID,
- })
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": "Failed to retrieve cards",
- "code": "CARDS_RETRIEVAL_FAILED",
- })
- return
- }
- c.JSON(http.StatusOK, gin.H{
- "cards": cards,
- "total": total,
- "limit": limit,
- "offset": offset,
- })
- }
- // GetPublicCard возвращает публичную карточку по URL
- func (h *CardHandler) GetPublicCard(c *gin.Context) {
- publicURL := c.Param("url")
- if publicURL == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "error": "Public URL is required",
- "code": "MISSING_PUBLIC_URL",
- })
- return
- }
- card, err := h.cardService.GetCardByPublicURL(publicURL)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "error": "Card not found or inactive",
- "code": "CARD_NOT_FOUND",
- })
- return
- }
- // Запись просмотра для аналитики
- viewData := models.AnalyticsView{
- CardID: card.ID,
- ViewerIP: c.ClientIP(),
- UserAgent: c.GetHeader("User-Agent"),
- Referrer: c.GetHeader("Referer"),
- }
- // Асинхронная запись аналитики (не блокируем ответ)
- go func() {
- if err := h.analyticsService.RecordView(viewData); err != nil {
- utils.LogError("Failed to record card view", err, map[string]interface{}{
- "card_id": card.ID,
- "ip": viewData.ViewerIP,
- })
- }
- }()
- // Увеличение счетчика просмотров
- go func() {
- if err := h.cardService.IncrementViewCount(card.ID); err != nil {
- utils.LogError("Failed to increment view count", err, map[string]interface{}{
- "card_id": card.ID,
- })
- }
- }()
- c.JSON(http.StatusOK, gin.H{
- "card": card,
- })
- }
- // UpdateCard обновляет существующую карточку
- func (h *CardHandler) UpdateCard(c *gin.Context) {
- userID, exists := c.Get("userID")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{
- "error": "User not authenticated",
- "code": "AUTHENTICATION_REQUIRED",
- })
- return
- }
- cardID := c.Param("id")
- if cardID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "error": "Card ID is required",
- "code": "MISSING_CARD_ID",
- })
- return
- }
- var updateData models.CardUpdate
- if err := c.ShouldBindJSON(&updateData); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "error": "Invalid update data",
- "details": err.Error(),
- "code": "INVALID_INPUT",
- })
- return
- }
- // Проверка прав доступа к карточке
- hasAccess, err := h.cardService.UserHasAccessToCard(userID.(string), cardID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": "Failed to verify card access",
- "code": "ACCESS_VERIFICATION_FAILED",
- })
- return
- }
- if !hasAccess {
- utils.LogSecurityEvent("unauthorized_card_access", userID.(string), c.ClientIP(), map[string]interface{}{
- "card_id": cardID,
- "action": "update",
- })
- c.JSON(http.StatusForbidden, gin.H{
- "error": "Access denied",
- "code": "ACCESS_DENIED",
- })
- return
- }
- // Обновление карточки
- card, err := h.cardService.UpdateCard(cardID, updateData)
- if err != nil {
- utils.LogError("Failed to update card", err, map[string]interface{}{
- "user_id": userID,
- "card_id": cardID,
- "update_data": updateData,
- })
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": "Failed to update card",
- "details": err.Error(),
- "code": "CARD_UPDATE_FAILED",
- })
- return
- }
- utils.LogInfo("Card updated successfully", map[string]interface{}{
- "user_id": userID,
- "card_id": cardID,
- })
- c.JSON(http.StatusOK, gin.H{
- "message": "Card updated successfully",
- "card": card,
- })
- }
- // DeleteCard удаляет карточку
- func (h *CardHandler) DeleteCard(c *gin.Context) {
- userID, exists := c.Get("userID")
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{
- "error": "User not authenticated",
- "code": "AUTHENTICATION_REQUIRED",
- })
- return
- }
- cardID := c.Param("id")
- if cardID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "error": "Card ID is required",
- "code": "MISSING_CARD_ID",
- })
- return
- }
- // Проверка прав доступа
- hasAccess, err := h.cardService.UserHasAccessToCard(userID.(string), cardID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": "Failed to verify card access",
- "code": "ACCESS_VERIFICATION_FAILED",
- })
- return
- }
- if !hasAccess {
- utils.LogSecurityEvent("unauthorized_card_access", userID.(string), c.ClientIP(), map[string]interface{}{
- "card_id": cardID,
- "action": "delete",
- })
- c.JSON(http.StatusForbidden, gin.H{
- "error": "Access denied",
- "code": "ACCESS_DENIED",
- })
- return
- }
- // Удаление карточки
- if err := h.cardService.DeleteCard(cardID); err != nil {
- utils.LogError("Failed to delete card", err, map[string]interface{}{
- "user_id": userID,
- "card_id": cardID,
- })
- c.JSON(http.StatusInternalServerError, gin.H{
- "error": "Failed to delete card",
- "code": "CARD_DELETION_FAILED",
- })
- return
- }
- utils.LogInfo("Card deleted successfully", map[string]interface{}{
- "user_id": userID,
- "card_id": cardID,
- })
- c.JSON(http.StatusOK, gin.H{
- "message": "Card deleted successfully",
- })
- }
- // validateCardData валидирует данные карточки
- func (h *CardHandler) validateCardData(data models.CardInput) error {
- if data.Name == "" {
- return fmt.Errorf("name is required")
- }
- if data.Email == "" {
- return fmt.Errorf("email is required")
- }
- if !utils.IsValidEmail(data.Email) {
- return fmt.Errorf("invalid email format")
- }
- if data.Phone != "" && !utils.IsValidPhone(data.Phone) {
- return fmt.Errorf("invalid phone format")
- }
- if data.Website != "" && !utils.IsValidURL(data.Website) {
- return fmt.Errorf("invalid website URL")
- }
- return nil
- }
Advertisement
Add Comment
Please, Sign In to add comment