package auth import ( "net/http" "strings" "time" "github.com/alexedwards/scs/pgxstore" "github.com/alexedwards/scs/v2" "github.com/jackc/pgx/v5/pgxpool" ) // NewSessionManager builds the scs session manager. cookieDomain is the session // cookie Domain attribute: empty keeps a host-only cookie (localhost / same-host // deploys). When the web app and API live on sibling hosts of one parent domain // (descrybe.io + api.descrybe.io), set SESSION_COOKIE_DOMAIN=descrybe.io so the // browser also sends the session cookie to the web host — SvelteKit SSR gates // (/admin +layout.server.ts fetchMeStaff) forward it to /api/auth/me and would // otherwise always see 401. func NewSessionManager(pool *pgxpool.Pool, cookieName, cookieDomain string, secure bool, idleHours int) *scs.SessionManager { sm := scs.New() sm.Store = pgxstore.New(pool) sm.Lifetime = 7 * 24 * time.Hour if idleHours <= 0 { idleHours = 24 } sm.IdleTimeout = time.Duration(idleHours) * time.Hour sm.Cookie.Name = cookieName sm.Cookie.Domain = strings.TrimPrefix(strings.TrimSpace(cookieDomain), ".") sm.Cookie.HttpOnly = true sm.Cookie.Secure = secure sm.Cookie.SameSite = http.SameSiteLaxMode sm.Cookie.Path = "/" return sm } const ( SessionUserIDKey = "user_id" SessionCompanyIDKey = "company_id" SessionImpersonatorIDKey = "impersonator_id" // non-prod user switch: original admin/demo SessionStaffHomeCompanyKey = "staff_home_company_id" // platform admin tenant switch: home company to revert to SessionVersionKey = "session_version" // must match users.session_version )