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
+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;
}