Files
gobeyhan/app/account/handlers/social_account_handler.go
Beyhan Oğur f34e54c5a5 first commit
2026-04-26 21:43:40 +03:00

112 lines
2.7 KiB
Go

package handlers
import (
"gobeyhan/app/account/services"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
type SocialAccountHandler struct {
service *services.SocialAccountService
}
func NewSocialAccountHandler(service *services.SocialAccountService) *SocialAccountHandler {
return &SocialAccountHandler{service: service}
}
// GetUserSocialAccounts godoc
// @Summary Get user's social accounts
// @Description Get all social accounts for the authenticated user
// @Tags social-accounts
// @Accept json
// @Produce json
// @Security BearerAuth
// @Success 200 {array} models.SocialAccount
// @Router /api/v1/user/social-accounts [get]
func (h *SocialAccountHandler) GetUserSocialAccounts(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
return
}
// Convert user_id to uint64
var uid uint64
switch v := userID.(type) {
case string:
uid, _ = strconv.ParseUint(v, 10, 64)
case uint64:
uid = v
case int:
uid = uint64(v)
case float64:
uid = uint64(v)
}
accounts, err := h.service.GetSocialAccountsByUser(uid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": accounts})
}
// DeleteSocialAccount godoc
// @Summary Delete a social account
// @Description Delete a social account for the authenticated user
// @Tags social-accounts
// @Accept json
// @Produce json
// @Security BearerAuth
// @Param id path int true "Social Account ID"
// @Success 200 {object} map[string]string
// @Router /api/v1/user/social-accounts/{id} [delete]
func (h *SocialAccountHandler) DeleteSocialAccount(c *gin.Context) {
idStr := c.Param("id")
id, err := strconv.ParseUint(idStr, 10, 64)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid social account ID"})
return
}
// Verify ownership
account, err := h.service.GetSocialAccountByID(id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if account == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Social account not found"})
return
}
userID, _ := c.Get("user_id")
var uid uint64
switch v := userID.(type) {
case string:
uid, _ = strconv.ParseUint(v, 10, 64)
case uint64:
uid = v
case int:
uid = uint64(v)
case float64:
uid = uint64(v)
}
if account.UserID != uid {
c.JSON(http.StatusForbidden, gin.H{"error": "You can only delete your own social accounts"})
return
}
if err := h.service.DeleteSocialAccount(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Social account deleted successfully"})
}