WIP - fix browser refresh not holding user authentication

This commit is contained in:
Francisco Gaona
2026-02-04 08:55:08 +01:00
parent 0e2f3dddbc
commit 49a571215d
4 changed files with 49 additions and 17 deletions

View File

@@ -56,15 +56,15 @@ export default defineEventHandler(async (event) => {
setSessionCookie(event, access_token)
// Set tenant ID cookie (readable by client for context)
if (tenantId) {
setTenantIdCookie(event, tenantId)
}
// Use tenantId from response, or fall back to subdomain
const tenantToStore = tenantId || subdomain
setTenantIdCookie(event, tenantToStore)
// Return user info (but NOT the token - it's in HTTP-only cookie)
return {
success: true,
user,
tenantId,
tenantId: tenantToStore,
}
} catch (error: any) {
// Re-throw H3 errors

View File

@@ -1,5 +1,5 @@
import type { H3Event } from 'h3'
import { getCookie, setCookie, deleteCookie } from 'h3'
import { getCookie, setCookie, deleteCookie, getHeader } from 'h3'
const SESSION_COOKIE_NAME = 'routebox_session'
const SESSION_MAX_AGE = 60 * 60 * 24 * 7 // 7 days
@@ -11,6 +11,25 @@ export interface SessionData {
email: string
}
/**
* Determine if the request is over a secure connection
* Checks both direct HTTPS and proxy headers
*/
function isSecureRequest(event: H3Event): boolean {
// Check x-forwarded-proto header (set by reverse proxies)
const forwardedProto = getHeader(event, 'x-forwarded-proto')
if (forwardedProto === 'https') {
return true
}
// Check if NODE_ENV is production (assume HTTPS in production)
if (process.env.NODE_ENV === 'production') {
return true
}
return false
}
/**
* Get the session token from HTTP-only cookie
*/
@@ -22,11 +41,11 @@ export function getSessionToken(event: H3Event): string | null {
* Set the session token in an HTTP-only cookie
*/
export function setSessionCookie(event: H3Event, token: string): void {
const isProduction = process.env.NODE_ENV === 'production'
const secure = isSecureRequest(event)
setCookie(event, SESSION_COOKIE_NAME, token, {
httpOnly: true,
secure: isProduction,
secure,
sameSite: 'lax',
maxAge: SESSION_MAX_AGE,
path: '/',
@@ -54,11 +73,11 @@ export function getTenantIdFromCookie(event: H3Event): string | null {
* Set tenant ID cookie (readable by client for context)
*/
export function setTenantIdCookie(event: H3Event, tenantId: string): void {
const isProduction = process.env.NODE_ENV === 'production'
const secure = isSecureRequest(event)
setCookie(event, 'routebox_tenant', tenantId, {
httpOnly: false, // Allow client to read tenant context
secure: isProduction,
secure,
sameSite: 'lax',
maxAge: SESSION_MAX_AGE,
path: '/',