0302-добавил куки и сломал десктоп авторизацию.

сложно поддерживать однояйцевых близнецов - desktop и TMA, подготовил к рефакторингу структуры
This commit is contained in:
2026-02-03 09:32:02 +03:00
parent 88620f3fb6
commit ea1e5bbf6a
14 changed files with 547 additions and 86 deletions

View File

@@ -1,34 +1,33 @@
package handlers
import (
"fmt"
"net/http"
"rmser/internal/domain/account"
"rmser/internal/services/auth"
"rmser/pkg/logger"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"github.com/google/uuid"
)
// AuthHandler обрабатывает HTTP запросы авторизации
type AuthHandler struct {
service *auth.Service
botUsername string
authService *auth.Service
accountService account.Repository
botUsername string
}
// NewAuthHandler создает новый экземпляр AuthHandler
func NewAuthHandler(s *auth.Service, botUsername string) *AuthHandler {
return &AuthHandler{service: s, botUsername: botUsername}
func NewAuthHandler(s *auth.Service, accountRepo account.Repository, botUsername string) *AuthHandler {
return &AuthHandler{authService: s, accountService: accountRepo, botUsername: botUsername}
}
// InitDesktopAuth инициализирует desktop авторизацию
// POST /api/auth/init-desktop
func (h *AuthHandler) InitDesktopAuth(c *gin.Context) {
// Вызываем сервис для генерации session_id
sessionID, err := h.service.InitDesktopAuth()
sessionID, err := h.authService.InitDesktopAuth()
if err != nil {
logger.Log.Error("Ошибка инициализации desktop авторизации", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Ошибка инициализации авторизации",
})
@@ -36,12 +35,7 @@ func (h *AuthHandler) InitDesktopAuth(c *gin.Context) {
}
// Формируем QR URL для Telegram бота
qrURL := fmt.Sprintf("https://t.me/%s?start=auth_%s", h.botUsername, sessionID)
logger.Log.Info("Desktop авторизация инициализирована",
zap.String("session_id", sessionID),
zap.String("qr_url", qrURL),
)
qrURL := "https://t.me/" + h.botUsername + "?start=auth_" + sessionID
// Возвращаем ответ с session_id и qr_url
c.JSON(http.StatusOK, gin.H{
@@ -49,3 +43,56 @@ func (h *AuthHandler) InitDesktopAuth(c *gin.Context) {
"qr_url": qrURL,
})
}
// CreateSession создает HTTP сессию и устанавливает HttpOnly Cookie
func (h *AuthHandler) CreateSession(c *gin.Context) {
userID, exists := c.Get("userID")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "user not found in context"})
return
}
userAgent := c.Request.UserAgent()
ip := c.ClientIP()
session, err := h.authService.CreateWebSession(userID.(uuid.UUID), userAgent, ip)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// Устанавливаем HttpOnly Cookie на 7 дней
c.SetCookie("rmser_session", session.RefreshToken, 7*24*60*60, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
// GetMe возвращает информацию о текущем пользователе
func (h *AuthHandler) GetMe(c *gin.Context) {
userID, exists := c.Get("userID")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "user not found"})
return
}
user, err := h.accountService.GetUserByID(userID.(uuid.UUID))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, user)
}
// Logout удаляет сессию и очищает cookie
func (h *AuthHandler) Logout(c *gin.Context) {
token, err := c.Cookie("rmser_session")
if err == nil && token != "" {
h.authService.DeleteSession(token)
}
// Очищаем куку
c.SetCookie("rmser_session", "", -1, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}