feat(auth): add production-grade Firebase Authentication setup with secure session cookies, CSRF defense, and UI modal

This commit is contained in:
2026-11-13 11:21:34 +05:30
parent a9c092ba03
commit 0fe0457136
14 changed files with 4154 additions and 20 deletions
+117
View File
@@ -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
View File
@@ -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>
+379
View File
@@ -0,0 +1,379 @@
'use client';
import React, { useState, useEffect } from 'react';
import {
X,
Mail,
Lock,
User as UserIcon,
Eye,
EyeOff,
AlertCircle,
CheckCircle2,
Sparkles,
ArrowRight,
Loader2,
} from 'lucide-react';
import { useAuth } from '@/lib/firebase/AuthContext';
function GoogleIcon({ className = 'w-4 h-4' }: { className?: string }) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
<path
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
fill="#4285F4"
/>
<path
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
fill="#34A853"
/>
<path
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z"
fill="#FBBC05"
/>
<path
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z"
fill="#EA4335"
/>
</svg>
);
}
function parseAuthError(error: any): string {
const code = error?.code || '';
switch (code) {
case 'auth/user-not-found':
case 'auth/wrong-password':
case 'auth/invalid-credential':
return 'Invalid email address or password.';
case 'auth/email-already-in-use':
return 'An account already exists with this email address.';
case 'auth/invalid-email':
return 'Please enter a valid email address.';
case 'auth/weak-password':
return 'Password should be at least 6 characters.';
case 'auth/popup-closed-by-user':
return 'Sign in cancelled before completion.';
case 'auth/too-many-requests':
return 'Too many attempts. Please wait a few moments and try again.';
case 'auth/network-request-failed':
return 'Network error. Please check your internet connection.';
default:
return error?.message || 'Authentication failed. Please try again.';
}
}
export function AuthModal() {
const {
authModalOpen,
authModalMode,
closeAuthModal,
openAuthModal,
signInWithGoogle,
signInWithEmail,
signUpWithEmail,
sendPasswordReset,
isConfigured,
} = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
// Reset form when modal opens or mode changes
useEffect(() => {
setError(null);
setSuccess(null);
setEmail('');
setPassword('');
setName('');
}, [authModalOpen, authModalMode]);
// Handle ESC key to close modal
useEffect(() => {
if (!authModalOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') closeAuthModal();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [authModalOpen, closeAuthModal]);
if (!authModalOpen) return null;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
setSuccess(null);
setLoading(true);
try {
if (authModalMode === 'signin') {
if (!email.trim() || !password) {
setError('Please provide both email and password.');
setLoading(false);
return;
}
await signInWithEmail(email, password);
} else if (authModalMode === 'signup') {
if (!email.trim() || !password) {
setError('Please provide email and password.');
setLoading(false);
return;
}
if (password.length < 6) {
setError('Password must be at least 6 characters.');
setLoading(false);
return;
}
await signUpWithEmail(email, password, name);
} else if (authModalMode === 'reset') {
if (!email.trim()) {
setError('Please enter your account email.');
setLoading(false);
return;
}
await sendPasswordReset(email);
setSuccess('Password reset link sent! Check your inbox.');
}
} catch (err: any) {
setError(parseAuthError(err));
} finally {
setLoading(false);
}
};
const handleGoogleSignIn = async () => {
setError(null);
setSuccess(null);
setLoading(true);
try {
await signInWithGoogle();
} catch (err: any) {
setError(parseAuthError(err));
} finally {
setLoading(false);
}
};
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-slate-950/60 backdrop-blur-sm animate-in fade-in duration-200"
onClick={(e) => {
if (e.target === e.currentTarget) closeAuthModal();
}}
role="dialog"
aria-modal="true"
aria-labelledby="auth-modal-title"
>
<div className="relative w-full max-w-md bg-paper-hi border border-rule rounded-2xl p-6 sm:p-8 shadow-2xl overflow-hidden motion-safe:transition-all">
{/* Top Close Button */}
<button
onClick={closeAuthModal}
className="absolute right-4 top-4 p-1.5 rounded-full text-slate-400 hover:text-slate-900 hover:bg-slate-100 transition-colors cursor-pointer"
aria-label="Close dialog"
>
<X className="w-4 h-4" />
</button>
{/* Unconfigured Configuration Warning Banner */}
{!isConfigured && (
<div className="mb-5 p-3 rounded-xl bg-amber-500/10 border border-amber-500/20 text-amber-800 text-xs flex items-start gap-2.5">
<AlertCircle className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
<div>
<span className="font-semibold block text-amber-900">Firebase Setup Ready</span>
Add your credentials to <code className="font-mono text-[11px] bg-amber-200/50 px-1 py-0.5 rounded">.env.local</code> to activate live authentication.
</div>
</div>
)}
{/* Header */}
<div className="text-center mb-6">
<div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-accent/10 border border-accent/20 text-accent text-xs font-semibold mb-3">
<Sparkles className="w-3.5 h-3.5" />
<span>CRE Innovations Studio</span>
</div>
<h2 id="auth-modal-title" className="text-2xl font-display font-bold text-ink tracking-tight">
{authModalMode === 'signin' && 'Welcome back'}
{authModalMode === 'signup' && 'Create your account'}
{authModalMode === 'reset' && 'Reset your password'}
</h2>
<p className="mt-1 text-xs sm:text-sm text-slate-500 font-sans">
{authModalMode === 'signin' && 'Sign in to access your cloud studio workspace'}
{authModalMode === 'signup' && 'Start editing with lossless 4K neural vision tools'}
{authModalMode === 'reset' && "Enter your email and we'll send you a password recovery link"}
</p>
</div>
{/* Error & Success Messages */}
{error && (
<div className="mb-4 p-3 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-700 text-xs flex items-start gap-2">
<AlertCircle className="w-4 h-4 shrink-0 mt-0.5" />
<span>{error}</span>
</div>
)}
{success && (
<div className="mb-4 p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 text-emerald-700 text-xs flex items-start gap-2">
<CheckCircle2 className="w-4 h-4 shrink-0 mt-0.5" />
<span>{success}</span>
</div>
)}
{/* OAuth: Google One-Click Sign In (for signin & signup) */}
{authModalMode !== 'reset' && (
<div className="space-y-4 mb-5">
<button
type="button"
onClick={handleGoogleSignIn}
disabled={loading}
className="w-full h-11 inline-flex items-center justify-center gap-2.5 px-4 rounded-xl bg-white border border-slate-200 hover:border-slate-300 hover:bg-slate-50/80 text-slate-700 font-sans font-semibold text-xs sm:text-sm shadow-xs transition-all active:scale-[0.99] cursor-pointer disabled:opacity-60"
>
<GoogleIcon className="w-4 h-4" />
<span>Continue with Google</span>
</button>
<div className="relative flex items-center justify-center">
<div className="border-t border-slate-200 w-full" />
<span className="bg-paper-hi px-3 text-[11px] font-mono text-slate-400 uppercase tracking-wider">
or with email
</span>
</div>
</div>
)}
{/* Email & Password Form */}
<form onSubmit={handleSubmit} className="space-y-3.5">
{authModalMode === 'signup' && (
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1">Full name</label>
<div className="relative">
<UserIcon className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="text"
placeholder="Jane Doe"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
</div>
</div>
)}
<div>
<label className="block text-xs font-semibold text-slate-700 mb-1">Email address</label>
<div className="relative">
<Mail className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
className="w-full pl-9 pr-3.5 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
</div>
</div>
{authModalMode !== 'reset' && (
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-xs font-semibold text-slate-700">Password</label>
{authModalMode === 'signin' && (
<button
type="button"
onClick={() => openAuthModal('reset')}
className="text-[11px] text-accent hover:underline cursor-pointer"
>
Forgot password?
</button>
)}
</div>
<div className="relative">
<Lock className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
<input
type={showPassword ? 'text' : 'password'}
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full pl-9 pr-10 py-2.5 rounded-xl border border-slate-200 bg-white text-xs sm:text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none focus:border-accent focus:ring-1 focus:ring-accent/20"
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1"
aria-label={showPassword ? 'Hide password' : 'Show password'}
>
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full h-11 inline-flex items-center justify-center gap-2 rounded-xl bg-slate-900 hover:bg-accent text-white font-sans font-semibold text-xs sm:text-sm transition-all shadow-xs hover:shadow-md cursor-pointer active:scale-[0.99] disabled:opacity-50 mt-1"
>
{loading ? (
<Loader2 className="w-4 h-4 animate-spin text-white" />
) : (
<>
<span>
{authModalMode === 'signin' && 'Sign In'}
{authModalMode === 'signup' && 'Create Account'}
{authModalMode === 'reset' && 'Send Reset Link'}
</span>
<ArrowRight className="w-4 h-4" />
</>
)}
</button>
</form>
{/* Footer Mode Switcher */}
<div className="mt-6 text-center text-xs text-slate-500 font-sans">
{authModalMode === 'signin' && (
<p>
Don&apos;t have an account?{' '}
<button
type="button"
onClick={() => openAuthModal('signup')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Sign up
</button>
</p>
)}
{authModalMode === 'signup' && (
<p>
Already have an account?{' '}
<button
type="button"
onClick={() => openAuthModal('signin')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Sign in
</button>
</p>
)}
{authModalMode === 'reset' && (
<p>
Remember your password?{' '}
<button
type="button"
onClick={() => openAuthModal('signin')}
className="font-semibold text-accent hover:underline cursor-pointer"
>
Back to Sign in
</button>
</p>
)}
</div>
</div>
</div>
);
}
+159
View File
@@ -0,0 +1,159 @@
'use client';
import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';
import {
User as UserIcon,
LogOut,
Sparkles,
ChevronDown,
CheckCircle2,
AlertCircle,
ExternalLink,
} from 'lucide-react';
import { useAuth } from '@/lib/firebase/AuthContext';
export function UserMenu() {
const { user, loading, openAuthModal, logout } = useAuth();
const [dropdownOpen, setDropdownOpen] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
// Close dropdown on click outside
useEffect(() => {
if (!dropdownOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setDropdownOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [dropdownOpen]);
// Close on Escape key
useEffect(() => {
if (!dropdownOpen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') setDropdownOpen(false);
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [dropdownOpen]);
if (loading) {
return (
<div className="w-8 h-8 rounded-full bg-slate-200/80 animate-pulse shrink-0" />
);
}
if (!user) {
return (
<button
type="button"
onClick={() => openAuthModal('signin')}
className="inline-flex items-center gap-1.5 px-3.5 py-1.5 rounded-full text-xs sm:text-sm font-sans font-semibold text-slate-700 hover:text-slate-950 bg-paper-2/90 hover:bg-paper-hi border border-rule transition-colors cursor-pointer active:scale-[0.98]"
aria-label="Sign in to your account"
>
<UserIcon className="w-3.5 h-3.5 text-accent" />
<span>Sign In</span>
</button>
);
}
const initial = (user.displayName || user.email || 'U').charAt(0).toUpperCase();
return (
<div className="relative shrink-0" ref={dropdownRef}>
<button
type="button"
onClick={() => setDropdownOpen(!dropdownOpen)}
className="inline-flex items-center gap-2 p-1 pr-2 rounded-full border border-rule bg-paper-hi hover:bg-slate-50 transition-colors shadow-2xs cursor-pointer focus:outline-none focus:ring-2 focus:ring-accent/20"
aria-expanded={dropdownOpen}
aria-haspopup="true"
aria-label="User account menu"
>
{user.photoURL ? (
<img
src={user.photoURL}
alt={user.displayName || 'User profile'}
className="w-7 h-7 rounded-full object-cover border border-slate-200"
/>
) : (
<div className="w-7 h-7 rounded-full bg-accent/15 text-accent font-sans font-bold text-xs flex items-center justify-center border border-accent/20">
{initial}
</div>
)}
<span className="hidden sm:inline text-xs font-sans font-medium text-slate-800 max-w-[100px] truncate">
{user.displayName || user.email?.split('@')[0]}
</span>
<ChevronDown className={`w-3.5 h-3.5 text-slate-400 transition-transform ${dropdownOpen ? 'rotate-180' : ''}`} />
</button>
{dropdownOpen && (
<div
className="absolute right-0 mt-2 w-64 rounded-2xl bg-paper-hi border border-rule shadow-2xl p-2 z-50 animate-in fade-in-0 zoom-in-95 duration-150"
role="menu"
>
{/* User Profile Summary */}
<div className="p-3 border-b border-rule">
<div className="font-semibold text-xs text-slate-900 truncate">
{user.displayName || 'Studio Member'}
</div>
<div className="text-[11px] font-mono text-slate-500 truncate mt-0.5">
{user.email}
</div>
{user.emailVerified ? (
<span className="inline-flex items-center gap-1 text-[10px] text-emerald-600 mt-1.5 font-medium">
<CheckCircle2 className="w-3 h-3" />
<span>Verified Account</span>
</span>
) : (
<span className="inline-flex items-center gap-1 text-[10px] text-amber-600 mt-1.5 font-medium">
<AlertCircle className="w-3 h-3" />
<span>Unverified Email</span>
</span>
)}
</div>
{/* Quick Links */}
<div className="py-1">
<Link
href="/tools"
onClick={() => setDropdownOpen(false)}
className="flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-slate-700 hover:bg-slate-100 hover:text-slate-950 transition-colors"
role="menuitem"
>
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>Studio Workspaces</span>
</Link>
<Link
href="/apps"
onClick={() => setDropdownOpen(false)}
className="flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-slate-700 hover:bg-slate-100 hover:text-slate-950 transition-colors"
role="menuitem"
>
<ExternalLink className="w-3.5 h-3.5 text-slate-400" />
<span>Mobile App Suite</span>
</Link>
</div>
{/* Sign Out */}
<div className="pt-1 border-t border-rule">
<button
type="button"
onClick={async () => {
setDropdownOpen(false);
await logout();
}}
className="w-full flex items-center gap-2.5 px-3 py-2 rounded-xl text-xs font-sans text-rose-600 hover:bg-rose-50 transition-colors cursor-pointer font-medium"
role="menuitem"
>
<LogOut className="w-3.5 h-3.5" />
<span>Sign Out</span>
</button>
</div>
</div>
)}
</div>
);
}
+7 -1
View File
@@ -20,6 +20,7 @@ import {
import { SiteConfig, CategoryItem, resolveLocalised } from '@/types';
import { BrandLogo } from './BrandLogo';
import { RainbowButton } from '@/components/magicui/rainbow-button';
import { UserMenu } from '@/components/auth/UserMenu';
interface NavbarProps {
config: SiteConfig;
@@ -147,8 +148,9 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
})}
</nav>
{/* Right CTA Actions from JSON */}
{/* Right CTA Actions from JSON + User Authentication */}
<div className="hidden md:flex items-center gap-3 relative z-20 flex-shrink-0">
<UserMenu />
<RainbowButton href={ctaHref}>
<span>{ctaLabel}</span>
<ArrowRight className="w-3.5 h-3.5 ml-1 inline" aria-hidden="true" />
@@ -208,6 +210,10 @@ export function Navbar({ config, currentLocale, categories = [], totalToolsCount
</nav>
<div className="pt-6 border-t border-rule space-y-3">
<div className="flex items-center justify-between pb-3 border-b border-rule/70">
<span className="text-xs font-semibold text-slate-700">Studio Account</span>
<UserMenu />
</div>
<RainbowButton
href={ctaHref}
onClick={() => setMobileMenuOpen(false)}
+202
View File
@@ -0,0 +1,202 @@
'use client';
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import {
User,
onIdTokenChanged,
signInWithPopup,
signInWithEmailAndPassword,
createUserWithEmailAndPassword,
sendPasswordResetEmail,
signOut as firebaseSignOut,
updateProfile,
} from 'firebase/auth';
import { getClientAuth, getGoogleProvider, isFirebaseClientConfigured } from './config';
export type AuthModalMode = 'signin' | 'signup' | 'reset';
interface AuthContextType {
user: User | null;
loading: boolean;
isConfigured: boolean;
signInWithGoogle: () => Promise<void>;
signInWithEmail: (email: string, pass: string) => Promise<void>;
signUpWithEmail: (email: string, pass: string, displayName?: string) => Promise<void>;
sendPasswordReset: (email: string) => Promise<void>;
logout: () => Promise<void>;
authModalOpen: boolean;
authModalMode: AuthModalMode;
openAuthModal: (mode?: AuthModalMode) => void;
closeAuthModal: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [authModalOpen, setAuthModalOpen] = useState<boolean>(false);
const [authModalMode, setAuthModalMode] = useState<AuthModalMode>('signin');
const isConfigured = isFirebaseClientConfigured();
// Synchronize Firebase Auth state with Server Session Cookie
useEffect(() => {
if (!isConfigured) {
setLoading(false);
return;
}
const auth = getClientAuth();
if (!auth) {
setLoading(false);
return;
}
const unsubscribe = onIdTokenChanged(auth, async (currentUser) => {
setUser(currentUser);
setLoading(false);
if (currentUser) {
try {
const idToken = await currentUser.getIdToken();
await fetch('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ idToken }),
});
} catch (error) {
console.warn('[Auth] Failed to sync session cookie:', error);
}
} else {
try {
await fetch('/api/auth/session', { method: 'DELETE' });
} catch {
// Ignore logout error
}
}
});
return () => unsubscribe();
}, [isConfigured]);
const openAuthModal = useCallback((mode: AuthModalMode = 'signin') => {
setAuthModalMode(mode);
setAuthModalOpen(true);
}, []);
const closeAuthModal = useCallback(() => {
setAuthModalOpen(false);
}, []);
const signInWithGoogle = useCallback(async () => {
if (!isConfigured) {
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
}
const auth = getClientAuth();
const provider = getGoogleProvider();
if (!auth || !provider) {
throw new Error('Firebase Auth client could not be initialized.');
}
const result = await signInWithPopup(auth, provider);
const idToken = await result.user.getIdToken();
await fetch('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ idToken }),
});
setAuthModalOpen(false);
}, [isConfigured]);
const signInWithEmail = useCallback(async (email: string, pass: string) => {
if (!isConfigured) {
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
}
const auth = getClientAuth();
if (!auth) {
throw new Error('Firebase Auth client could not be initialized.');
}
const result = await signInWithEmailAndPassword(auth, email.trim(), pass);
const idToken = await result.user.getIdToken();
await fetch('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ idToken }),
});
setAuthModalOpen(false);
}, [isConfigured]);
const signUpWithEmail = useCallback(async (email: string, pass: string, displayName?: string) => {
if (!isConfigured) {
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
}
const auth = getClientAuth();
if (!auth) {
throw new Error('Firebase Auth client could not be initialized.');
}
const result = await createUserWithEmailAndPassword(auth, email.trim(), pass);
if (displayName && displayName.trim()) {
await updateProfile(result.user, { displayName: displayName.trim() });
}
const idToken = await result.user.getIdToken();
await fetch('/api/auth/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ idToken }),
});
setAuthModalOpen(false);
}, [isConfigured]);
const sendPasswordReset = useCallback(async (email: string) => {
if (!isConfigured) {
throw new Error('Firebase is not yet configured. Please set your credentials in .env.local.');
}
const auth = getClientAuth();
if (!auth) {
throw new Error('Firebase Auth client could not be initialized.');
}
await sendPasswordResetEmail(auth, email.trim());
}, [isConfigured]);
const logout = useCallback(async () => {
const auth = getClientAuth();
if (auth) {
await firebaseSignOut(auth);
}
await fetch('/api/auth/session', { method: 'DELETE' });
setUser(null);
}, []);
return (
<AuthContext.Provider
value={{
user,
loading,
isConfigured,
signInWithGoogle,
signInWithEmail,
signUpWithEmail,
sendPasswordReset,
logout,
authModalOpen,
authModalMode,
openAuthModal,
closeAuthModal,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
}
+125
View File
@@ -0,0 +1,125 @@
import { getApps, initializeApp, cert, App } from 'firebase-admin/app';
import { getAuth, Auth, DecodedIdToken } from 'firebase-admin/auth';
/**
* Firebase Admin SDK Initialization (Server-side only)
* Provides cryptographically secure verification of ID tokens and session cookies.
*/
function formatPrivateKey(key: string | undefined): string | undefined {
if (!key) return undefined;
return key.replace(/\\n/g, '\n');
}
const projectId =
process.env.FIREBASE_PROJECT_ID ||
process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID ||
'';
const clientEmail = process.env.FIREBASE_CLIENT_EMAIL || '';
const privateKey = formatPrivateKey(process.env.FIREBASE_PRIVATE_KEY);
export function isFirebaseAdminConfigured(): boolean {
return Boolean(projectId && clientEmail && privateKey);
}
function initAdmin(): App | null {
const currentApps = getApps();
if (currentApps.length > 0) {
return currentApps[0]!;
}
if (isFirebaseAdminConfigured()) {
try {
return initializeApp({
credential: cert({
projectId,
clientEmail,
privateKey,
}),
});
} catch (error) {
console.warn('[Firebase Admin] Initialization with cert failed:', error);
}
} else if (projectId) {
// Project ID only (e.g. Google Cloud Run or GCP environment with ADC)
try {
return initializeApp({
projectId,
});
} catch (error) {
console.warn('[Firebase Admin] Initialization with projectId failed:', error);
}
}
return null;
}
export function getAdminAuth(): Auth | null {
const currentApp = getApps().length > 0 ? getApps()[0]! : initAdmin();
if (!currentApp) return null;
return getAuth(currentApp);
}
/**
* Verifies a client-provided Firebase ID Token.
* Rejects revoked or expired tokens.
*/
export async function verifyFirebaseIdToken(
idToken: string,
checkRevoked = true
): Promise<DecodedIdToken | null> {
const auth = getAdminAuth();
if (!auth) {
return null;
}
try {
const decoded = await auth.verifyIdToken(idToken, checkRevoked);
return decoded;
} catch (error) {
console.warn('[Firebase Admin] ID token verification failed:', error);
return null;
}
}
/**
* Verifies a server-side session cookie.
*/
export async function verifyFirebaseSessionCookie(
sessionCookie: string,
checkRevoked = true
): Promise<DecodedIdToken | null> {
const auth = getAdminAuth();
if (!auth) {
return null;
}
try {
const decoded = await auth.verifySessionCookie(sessionCookie, checkRevoked);
return decoded;
} catch (error) {
console.warn('[Firebase Admin] Session cookie verification failed:', error);
return null;
}
}
/**
* Creates a server session cookie valid for the specified duration (e.g., 5 days).
*/
export async function createFirebaseSessionCookie(
idToken: string,
expiresInMs = 60 * 60 * 24 * 5 * 1000 // 5 days
): Promise<string | null> {
const auth = getAdminAuth();
if (!auth) return null;
try {
const sessionCookie = await auth.createSessionCookie(idToken, {
expiresIn: expiresInMs,
});
return sessionCookie;
} catch (error) {
console.warn('[Firebase Admin] Failed to create session cookie:', error);
return null;
}
}
+79
View File
@@ -0,0 +1,79 @@
import { initializeApp, getApps, getApp, FirebaseApp } from 'firebase/app';
import { getAuth, Auth, GoogleAuthProvider } from 'firebase/auth';
/**
* Firebase Client SDK Configuration
* Loaded dynamically from environment variables.
* Safe fallback prevents build-time crashes when credentials are not yet configured.
*/
export const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY || '',
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN || '',
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID || '',
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET || '',
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID || '',
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID || '',
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID || '',
};
/**
* Validates whether the essential client configuration keys are set.
*/
export function isFirebaseClientConfigured(): boolean {
return Boolean(
firebaseConfig.apiKey &&
firebaseConfig.authDomain &&
firebaseConfig.projectId &&
firebaseConfig.appId
);
}
let app: FirebaseApp | null = null;
let auth: Auth | null = null;
let googleProvider: GoogleAuthProvider | null = null;
if (typeof window !== 'undefined') {
if (isFirebaseClientConfigured()) {
try {
app = getApps().length > 0 ? getApp() : initializeApp(firebaseConfig);
auth = getAuth(app);
googleProvider = new GoogleAuthProvider();
googleProvider.setCustomParameters({ prompt: 'select_account' });
} catch (error) {
console.warn('[Firebase] Client initialization failed:', error);
}
}
}
export function getClientApp(): FirebaseApp | null {
if (!app && typeof window !== 'undefined' && isFirebaseClientConfigured()) {
try {
app = getApps().length > 0 ? getApp() : initializeApp(firebaseConfig);
} catch (err) {
console.warn('[Firebase] Failed to get client app:', err);
}
}
return app;
}
export function getClientAuth(): Auth | null {
if (!auth && typeof window !== 'undefined' && isFirebaseClientConfigured()) {
const clientApp = getClientApp();
if (clientApp) {
try {
auth = getAuth(clientApp);
} catch (err) {
console.warn('[Firebase] Failed to get client auth:', err);
}
}
}
return auth;
}
export function getGoogleProvider(): GoogleAuthProvider | null {
if (!googleProvider && typeof window !== 'undefined') {
googleProvider = new GoogleAuthProvider();
googleProvider.setCustomParameters({ prompt: 'select_account' });
}
return googleProvider;
}
+80
View File
@@ -0,0 +1,80 @@
import { cookies, headers } from 'next/headers';
import { NextRequest } from 'next/server';
import { verifyFirebaseSessionCookie, verifyFirebaseIdToken } from './admin';
export interface AuthenticatedUser {
uid: string;
email: string | null;
displayName: string | null;
photoURL: string | null;
emailVerified: boolean;
claims: Record<string, any>;
}
export const SESSION_COOKIE_NAME = '__session';
/**
* Extracts and verifies the authenticated user from cookies or Authorization header.
* Server-only verification: Cannot be spoofed by client headers alone.
*/
export async function getServerUser(req?: NextRequest): Promise<AuthenticatedUser | null> {
// 1. Try session cookie first (httpOnly)
let sessionToken: string | undefined;
if (req) {
sessionToken = req.cookies.get(SESSION_COOKIE_NAME)?.value;
} else {
try {
const cookieStore = cookies();
sessionToken = cookieStore.get(SESSION_COOKIE_NAME)?.value;
} catch {
// Outside request context
}
}
if (sessionToken) {
const decoded = await verifyFirebaseSessionCookie(sessionToken);
if (decoded) {
return {
uid: decoded.uid,
email: decoded.email || null,
displayName: (decoded.name as string) || null,
photoURL: (decoded.picture as string) || null,
emailVerified: Boolean(decoded.email_verified),
claims: decoded,
};
}
}
// 2. Fallback to Authorization: Bearer <idToken> header (e.g. for API clients)
let authHeader: string | null = null;
if (req) {
authHeader = req.headers.get('authorization');
} else {
try {
const headerStore = headers();
authHeader = headerStore.get('authorization');
} catch {
// Outside request context
}
}
if (authHeader && authHeader.startsWith('Bearer ')) {
const idToken = authHeader.substring(7).trim();
if (idToken) {
const decoded = await verifyFirebaseIdToken(idToken);
if (decoded) {
return {
uid: decoded.uid,
email: decoded.email || null,
displayName: (decoded.name as string) || null,
photoURL: (decoded.picture as string) || null,
emailVerified: Boolean(decoded.email_verified),
claims: decoded,
};
}
}
}
return null;
}