Files
rmser/internal/transport/http/handlers/auth.go
SERTY ea1e5bbf6a 0302-добавил куки и сломал десктоп авторизацию.
сложно поддерживать однояйцевых близнецов - desktop и TMA, подготовил к рефакторингу структуры
2026-02-03 09:32:02 +03:00

99 lines
2.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handlers
import (
"net/http"
"rmser/internal/domain/account"
"rmser/internal/services/auth"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// AuthHandler обрабатывает HTTP запросы авторизации
type AuthHandler struct {
authService *auth.Service
accountService account.Repository
botUsername string
}
// NewAuthHandler создает новый экземпляр AuthHandler
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.authService.InitDesktopAuth()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Ошибка инициализации авторизации",
})
return
}
// Формируем QR URL для Telegram бота
qrURL := "https://t.me/" + h.botUsername + "?start=auth_" + sessionID
// Возвращаем ответ с session_id и qr_url
c.JSON(http.StatusOK, gin.H{
"session_id": sessionID,
"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"})
}