Files
gridpilot.gg/apps/website/lib/gateways/SessionGateway.ts
2026-01-03 02:42:47 +01:00

64 lines
1.8 KiB
TypeScript

/**
* SessionGateway - Server-side session management
*
* Fetches session data from the API using server cookies.
* Designed for 'use server' contexts.
*/
import { cookies } from 'next/headers';
import type { AuthSessionDTO } from '../types/generated/AuthSessionDTO';
/**
* SessionGateway class for server-side session management
*
* Uses Next.js server cookies and fetches session from API
* Returns null on any error or non-2xx response (no throws)
*/
export class SessionGateway {
/**
* Get current authentication session
*
* @returns Promise<AuthSessionDTO | null> - Session object or null if not authenticated/error
*/
async getSession(): Promise<AuthSessionDTO | null> {
try {
// Get cookies from the current request
const cookieStore = await cookies();
const cookieString = cookieStore.toString();
// If no cookies, return null immediately
if (!cookieString) {
return null;
}
// Determine API base URL
// In Docker/test: use API_BASE_URL env var or direct API URL
// In production: use relative path which will be rewritten
const baseUrl = process.env.API_BASE_URL || 'http://localhost:3101';
const apiUrl = `${baseUrl}/auth/session`;
// Fetch session from API with cookies forwarded
// Use credentials: 'include' to ensure cookies are sent
const response = await fetch(apiUrl, {
headers: {
cookie: cookieString,
},
cache: 'no-store',
credentials: 'include',
});
// Return null for non-2xx responses
if (!response.ok) {
return null;
}
// Parse and return session data
const session = await response.json();
return session as AuthSessionDTO;
} catch (error) {
// Return null on any error (network, parsing, etc.)
return null;
}
}
}