Files
gridpilot.gg/apps/website/lib/gateways/SessionGateway.ts
2026-01-04 00:39:17 +01:00

65 lines
1.9 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
// The API is always at http://api:3000 in the Docker network
const baseUrl = process.env.API_BASE_URL || 'http://localhost:3101';
const apiUrl = `${baseUrl}/auth/session`;
// Fetch session from API with cookies forwarded
// In server-side fetch, we need to pass cookies explicitly
// credentials: 'include' doesn't work in server-side fetch
const response = await fetch(apiUrl, {
headers: {
cookie: cookieString,
},
cache: 'no-store',
});
// 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;
}
}
}