package auth import ( "errors" "log" "github.com/gofiber/fiber/v2" "github.com/sujit-baniya/fiber-boilerplate/app" "github.com/sujit-baniya/fiber-boilerplate/pkg/models" ) const portalSessionKey = "portal_user_id" // PortalUser obtiene el usuario portal de la sesión actual. func PortalUser(c *fiber.Ctx) (*models.PortalUser, error) { store := app.Http.Session.Get(c) raw := store.Get(portalSessionKey) log.Printf("[PORTAL SESSION] GET %s → cookie=%q raw=%v", c.Path(), c.Cookies("session_id"), raw) if raw == nil { return nil, errors.New("no portal session") } var id uint switch v := raw.(type) { case uint: id = v case int64: id = uint(v) case float64: id = uint(v) default: log.Printf("[PORTAL SESSION] type assertion failed: %T", raw) return nil, errors.New("invalid portal session") } u, err := models.GetPortalUserByID(id) if err != nil { return nil, err } if !u.Activo { return nil, errors.New("portal user inactive") } // Precargar accesos del portal user para que GetClienteIDsForPortalUser funcione return u, nil } // SetPortalSession guarda el portal_user_id en la sesión. func SetPortalSession(c *fiber.Ctx, userID uint) error { store := app.Http.Session.Get(c) // Regenerar ID de sesión para evitar session fixation if err := store.Regenerate(); err != nil { log.Printf("[PORTAL SESSION] Regenerate error: %v", err) return err } store.Set(portalSessionKey, userID) if err := store.Save(); err != nil { log.Printf("[PORTAL SESSION] Save error: %v", err) return err } log.Printf("[PORTAL SESSION] SET userID=%d cookie=%q", userID, c.Cookies("session_id")) return nil } // DestroyPortalSession elimina la sesión del portal. func DestroyPortalSession(c *fiber.Ctx) error { store := app.Http.Session.Get(c) store.Delete(portalSessionKey) return store.Save() } // IsPortalLoggedIn verifica si hay sesión de portal activa. func IsPortalLoggedIn(c *fiber.Ctx) bool { store := app.Http.Session.Get(c) return store.Get(portalSessionKey) != nil }