Files
Ivan Rezchikov 628dd6384b
Build and Deploy / test-backend (push) Successful in 1m11s
Build and Deploy / lint-frontend (push) Successful in 21s
Build and Deploy / build-backend (push) Successful in 58s
Build and Deploy / deploy (push) Canceled after 0s
Build and Deploy / build-frontend (push) Canceled after 5m38s
version 1
2026-09-18 00:45:51 +03:00

77 lines
1.8 KiB
Go

package handler
import (
"errors"
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/dusiburg/fancy-api/internal/service"
)
type AuthHandler struct {
service *service.AuthService
}
func NewAuthHandler(service *service.AuthService) *AuthHandler {
return &AuthHandler{service: service}
}
func (h *AuthHandler) CreateSession(c *gin.Context) {
accessToken := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
if accessToken == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "access token is required"})
return
}
sessionToken, err := h.service.CreateSession(c, accessToken)
if err != nil {
log.Printf("create session: %v", err)
switch {
case errors.Is(err, service.ErrKotosoftUnauthorized):
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid access token"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "session creation failed"})
}
return
}
c.JSON(http.StatusOK, gin.H{"session_token": sessionToken})
}
func (h *AuthHandler) Me(c *gin.Context) {
userID, ok := c.Get("user_id")
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
user, err := h.service.GetUser(c, userID.(uuid.UUID))
if err != nil {
log.Printf("get user %s: %v", userID, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to fetch user"})
return
}
c.JSON(http.StatusOK, user)
}
func (h *AuthHandler) DeleteSession(c *gin.Context) {
token := strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "session token is required"})
return
}
if err := h.service.RevokeSession(c, token); err != nil {
log.Printf("revoke session: %v", err)
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid session token"})
return
}
c.Status(http.StatusNoContent)
}