2026-08-09 22:47:43 +02:00
|
|
|
package auth
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"net/http"
|
2026-08-18 00:31:58 +02:00
|
|
|
"strings"
|
2026-08-09 22:47:43 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/alexedwards/scs/pgxstore"
|
|
|
|
|
"github.com/alexedwards/scs/v2"
|
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
|
)
|
|
|
|
|
|
2026-08-18 00:31:58 +02:00
|
|
|
// 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 {
|
2026-08-09 22:47:43 +02:00
|
|
|
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
|
2026-08-18 00:31:58 +02:00
|
|
|
sm.Cookie.Domain = strings.TrimPrefix(strings.TrimSpace(cookieDomain), ".")
|
2026-08-09 22:47:43 +02:00
|
|
|
sm.Cookie.HttpOnly = true
|
|
|
|
|
sm.Cookie.Secure = secure
|
|
|
|
|
sm.Cookie.SameSite = http.SameSiteLaxMode
|
|
|
|
|
sm.Cookie.Path = "/"
|
|
|
|
|
return sm
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const (
|
2026-08-14 00:06:43 +02:00
|
|
|
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
|
2026-08-09 22:47:43 +02:00
|
|
|
)
|