Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/api/admin/email-templates/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
import { unstable_cache } from "next/cache";
import { requireAdminAuth } from "../../lib/auth";
import { getAllTemplates } from "@/lib/email-templates";

// Cached function to get templates (templates are static, cache for longer)
Expand All @@ -16,6 +17,10 @@ const getCachedTemplates = unstable_cache(

export async function GET() {
try {
// Require admin authentication
const authResult = await requireAdminAuth();
if (authResult instanceof NextResponse) return authResult;

const templates = await getCachedTemplates();

const response = NextResponse.json({ templates });
Expand Down
5 changes: 5 additions & 0 deletions app/api/admin/revalidate/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdminAuth } from "../../lib/auth";
import { revalidateTag } from "next/cache";

/**
Expand All @@ -7,6 +8,10 @@ import { revalidateTag } from "next/cache";
*/
export async function POST(request: NextRequest) {
try {
// Require admin authentication
const authResult = await requireAdminAuth();
if (authResult instanceof NextResponse) return authResult;

const searchParams = request.nextUrl.searchParams;
const tag = searchParams.get("tag");

Expand Down
5 changes: 5 additions & 0 deletions app/api/admin/send-email/route.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdminAuth } from "../../lib/auth";
import { supabaseAdmin } from "../../lib/supabase-server";
import { errorResponse } from "../../lib/errors";
import { sendCustomEmail } from "@/lib/email";

export async function POST(request: NextRequest) {
try {
// Require admin authentication
const authResult = await requireAdminAuth();
if (authResult instanceof NextResponse) return authResult;

const body = await request.json();
const { userIds, subject, content } = body;

Expand Down
6 changes: 4 additions & 2 deletions app/api/admin/users/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
import { unstable_cache } from "next/cache";
import { requireAdminAuth } from "../../lib/auth";
import { supabaseAdmin } from "../../lib/supabase-server";

// Cached function to fetch users
Expand All @@ -25,8 +26,9 @@ const getCachedUsers = unstable_cache(

export async function GET() {
try {
// In production, add proper admin authentication here
// For now, we'll allow access from the admin dashboard
// Require admin authentication
const authResult = await requireAdminAuth();
if (authResult instanceof NextResponse) return authResult;

const users = await getCachedUsers();

Expand Down
28 changes: 28 additions & 0 deletions app/api/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,31 @@ export async function requireAuth(): Promise<{ userId: string } | NextResponse>

return { userId };
}

/**
* Require admin authentication for an API route
* Returns userId if authenticated and user is admin, or error response if not
* Admin check: Verify against ADMIN_USER_IDS environment variable
*/
export async function requireAdminAuth(): Promise<{ userId: string } | NextResponse> {
const { userId } = await auth();

if (!userId) {
return NextResponse.json(
{ error: 'Unauthorized', message: 'Authentication required' },
{ status: 401 }
);
}

// Check if user is in the admin list
const adminUserIds = (process.env.ADMIN_USER_IDS || '').split(',').map(id => id.trim()).filter(Boolean);

if (!adminUserIds.includes(userId)) {
return NextResponse.json(
{ error: 'Forbidden', message: 'Admin access required' },
{ status: 403 }
);
}

return { userId };
}
167 changes: 167 additions & 0 deletions app/api/lib/rate-limit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import { NextRequest, NextResponse } from 'next/server';

/**
* In-memory rate limiter for development/self-hosted
* For production Vercel deployment, use Upstash Redis
*/
interface RateLimitStore {
[key: string]: {
count: number;
resetTime: number;
};
}

class RateLimiter {
private store: RateLimitStore = {};
private windowMs: number;
private maxRequests: number;

constructor(windowMs: number = 60000, maxRequests: number = 100) {
this.windowMs = windowMs;
this.maxRequests = maxRequests;

// Cleanup expired entries every minute
setInterval(() => {
const now = Date.now();
Object.keys(this.store).forEach((key) => {
if (this.store[key].resetTime < now) {
delete this.store[key];
}
});
}, 60000);
}

isLimited(key: string): boolean {
const now = Date.now();
const entry = this.store[key];

if (!entry || entry.resetTime < now) {
// New window
this.store[key] = {
count: 1,
resetTime: now + this.windowMs,
};
return false;
}

if (entry.count < this.maxRequests) {
entry.count++;
return false;
}

return true;
}

getRetryAfter(key: string): number {
const entry = this.store[key];
if (!entry) return 0;
return Math.ceil((entry.resetTime - Date.now()) / 1000);
}
}

// Global rate limiters
const apiLimiter = new RateLimiter(60000, 100); // 100 requests per minute
const authLimiter = new RateLimiter(900000, 7); // 7 requests per 15 minutes (auth endpoints)
const uploadLimiter = new RateLimiter(3600000, 15); // 15 requests per hour (upload endpoints)

/**
* Extract client IP from request
*/
function getClientIp(request: NextRequest): string {
const forwarded = request.headers.get('x-forwarded-for');
const clientIp = forwarded ? forwarded.split(',')[0] : '127.0.0.1';
return clientIp.trim();
}

/**
* Rate limit middleware for API routes
*/
export function withRateLimit(
handler: (request: NextRequest) => Promise<NextResponse>,
options?: {
windowMs?: number;
maxRequests?: number;
limiterType?: 'api' | 'auth' | 'upload';
}
): (request: NextRequest) => Promise<NextResponse> {
return async (request: NextRequest) => {
const clientIp = getClientIp(request);
const limiterType = options?.limiterType || 'api';

let limiter: RateLimiter;
switch (limiterType) {
case 'auth':
limiter = authLimiter;
break;
case 'upload':
limiter = uploadLimiter;
break;
default:
limiter = apiLimiter;
}

if (limiter.isLimited(clientIp)) {
const retryAfter = limiter.getRetryAfter(clientIp);
return NextResponse.json(
{
error: 'Too many requests',
message: `Rate limit exceeded. Please try again in ${retryAfter} seconds.`,
retryAfter,
},
{
status: 429,
headers: {
'Retry-After': retryAfter.toString(),
'X-RateLimit-Limit': limiter['maxRequests']?.toString() || '100',
'X-RateLimit-Remaining': '0',
'X-RateLimit-Reset': new Date(
Date.now() + retryAfter * 1000
).toISOString(),
},
}
);
}

return handler(request);
};
}

/**
* Per-user rate limiting (for authenticated endpoints)
*/
export function withUserRateLimit(
handler: (request: NextRequest, userId: string) => Promise<NextResponse>,
options?: {
windowMs?: number;
maxRequests?: number;
}
) {
const limiter = new RateLimiter(
options?.windowMs || 60000,
options?.maxRequests || 100
);

return async (
request: NextRequest,
userId: string
): Promise<NextResponse> => {
if (limiter.isLimited(userId)) {
const retryAfter = limiter.getRetryAfter(userId);
return NextResponse.json(
{
error: 'Too many requests',
message: `Rate limit exceeded. Please try again in ${retryAfter} seconds.`,
retryAfter,
},
{
status: 429,
headers: {
'Retry-After': retryAfter.toString(),
},
}
);
}

return handler(request, userId);
};
}
Loading