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) }