feat(auth): add production-grade Firebase Authentication setup with secure session cookies, CSRF defense, and UI modal
This commit is contained in:
@@ -0,0 +1,117 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import {
|
||||
createFirebaseSessionCookie,
|
||||
verifyFirebaseIdToken,
|
||||
isFirebaseAdminConfigured,
|
||||
} from '@/lib/firebase/admin';
|
||||
import { getServerUser, SESSION_COOKIE_NAME } from '@/lib/firebase/serverAuth';
|
||||
|
||||
/**
|
||||
* Validates that requests come from the same origin to mitigate CSRF attacks.
|
||||
*/
|
||||
function isValidOrigin(req: NextRequest): boolean {
|
||||
const origin = req.headers.get('origin');
|
||||
if (!origin) return true; // Non-browser or same-origin direct request without Origin header
|
||||
const host = req.headers.get('host');
|
||||
if (!host) return false;
|
||||
|
||||
try {
|
||||
const originUrl = new URL(origin);
|
||||
return originUrl.host === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/auth/session
|
||||
* Securely creates an httpOnly session cookie after client authentication.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isValidOrigin(req)) {
|
||||
return NextResponse.json({ error: 'Invalid origin / CSRF rejection' }, { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const idToken = body.idToken;
|
||||
|
||||
if (!idToken || typeof idToken !== 'string') {
|
||||
return NextResponse.json({ error: 'Valid idToken required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const res = NextResponse.json({ success: true });
|
||||
|
||||
const fiveDaysInMs = 60 * 60 * 24 * 5 * 1000;
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
if (isFirebaseAdminConfigured()) {
|
||||
// Cryptographically mint a Firebase Session Cookie
|
||||
const sessionCookie = await createFirebaseSessionCookie(idToken, fiveDaysInMs);
|
||||
|
||||
if (sessionCookie) {
|
||||
res.cookies.set(SESSION_COOKIE_NAME, sessionCookie, {
|
||||
maxAge: Math.floor(fiveDaysInMs / 1000),
|
||||
httpOnly: true,
|
||||
secure: isProduction,
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
});
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: If Admin SDK is not yet configured, set the ID token directly with 1-hour expiry
|
||||
res.cookies.set(SESSION_COOKIE_NAME, idToken, {
|
||||
maxAge: 3600,
|
||||
httpOnly: true,
|
||||
secure: isProduction,
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
});
|
||||
|
||||
return res;
|
||||
} catch (error: any) {
|
||||
console.error('[Auth API] Session creation error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create session' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/auth/session
|
||||
* Clears the session cookie on logout.
|
||||
*/
|
||||
export async function DELETE(req: NextRequest) {
|
||||
if (!isValidOrigin(req)) {
|
||||
return NextResponse.json({ error: 'Invalid origin / CSRF rejection' }, { status: 403 });
|
||||
}
|
||||
|
||||
const res = NextResponse.json({ success: true, message: 'Logged out successfully' });
|
||||
res.cookies.set(SESSION_COOKIE_NAME, '', {
|
||||
maxAge: 0,
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/auth/session
|
||||
* Returns the currently authenticated user's profile claims.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const user = await getServerUser(req);
|
||||
return NextResponse.json({
|
||||
authenticated: Boolean(user),
|
||||
user: user || null,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json({ authenticated: false, user: null });
|
||||
}
|
||||
}
|
||||
+14
-9
@@ -5,6 +5,8 @@ import { getSiteConfig, getAllCategories, getAllTools } from '@/lib/config/loade
|
||||
import { Navbar } from '@/components/ui/Navbar';
|
||||
import { Footer } from '@/components/ui/Footer';
|
||||
import { SmoothScrollProvider } from '@/components/ui/SmoothScrollProvider';
|
||||
import { AuthProvider } from '@/lib/firebase/AuthContext';
|
||||
import { AuthModal } from '@/components/auth/AuthModal';
|
||||
|
||||
const poppinsFont = Poppins({
|
||||
subsets: ['latin'],
|
||||
@@ -97,15 +99,18 @@ export default function RootLayout({
|
||||
</head>
|
||||
<body className="min-h-screen flex flex-col antialiased bg-paper text-ink relative font-sans overflow-x-clip">
|
||||
<SmoothScrollProvider>
|
||||
<a href="#main-content" className="skip-link">Skip to main content</a>
|
||||
<Navbar
|
||||
config={config}
|
||||
currentLocale="en"
|
||||
categories={categories}
|
||||
totalToolsCount={tools.length}
|
||||
/>
|
||||
<main id="main-content" className="flex-1">{children}</main>
|
||||
<Footer config={config} currentLocale="en" />
|
||||
<AuthProvider>
|
||||
<a href="#main-content" className="skip-link">Skip to main content</a>
|
||||
<Navbar
|
||||
config={config}
|
||||
currentLocale="en"
|
||||
categories={categories}
|
||||
totalToolsCount={tools.length}
|
||||
/>
|
||||
<main id="main-content" className="flex-1">{children}</main>
|
||||
<Footer config={config} currentLocale="en" />
|
||||
<AuthModal />
|
||||
</AuthProvider>
|
||||
</SmoothScrollProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user