🚀 Complete Production Setup

 Features:
- Analytics Dashboard with real-time metrics
- Redis caching for performance optimization
- Import/Export functionality for projects
- Complete admin system with security
- Production-ready Docker setup

🔧 Technical:
- Removed Ghost CMS dependencies
- Added Redis container with caching
- Implemented API response caching
- Enhanced admin interface with analytics
- Optimized for dk0.dev domain

🛡️ Security:
- Admin authentication with Basic Auth
- Protected analytics endpoints
- Secure environment configuration

📊 Analytics:
- Performance metrics dashboard
- Project statistics visualization
- Real-time data with caching
- Umami integration for GDPR compliance

🎯 Production Ready:
- Multi-container Docker setup
- Health checks for all services
- Automatic restart policies
- Resource limits configured
- Ready for Nginx Proxy Manager
This commit is contained in:
Dennis Konkol
2025-09-05 21:35:54 +00:00
parent c736f860aa
commit 9835bb810d
19 changed files with 1386 additions and 45 deletions

View File

@@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from 'next/server';
import { projectService } from '@/lib/prisma';
import { analyticsCache } from '@/lib/redis';
export async function GET(request: NextRequest) {
try {
// Check admin authentication
const authHeader = request.headers.get('authorization');
const basicAuth = process.env.ADMIN_BASIC_AUTH;
if (!basicAuth) {
return new NextResponse('Admin access not configured', { status: 500 });
}
if (!authHeader || !authHeader.startsWith('Basic ')) {
return new NextResponse('Authentication required', { status: 401 });
}
const credentials = authHeader.split(' ')[1];
const [username, password] = Buffer.from(credentials, 'base64').toString().split(':');
const [expectedUsername, expectedPassword] = basicAuth.split(':');
if (username !== expectedUsername || password !== expectedPassword) {
return new NextResponse('Invalid credentials', { status: 401 });
}
// Check cache first
const cachedStats = await analyticsCache.getOverallStats();
if (cachedStats) {
return NextResponse.json(cachedStats);
}
// Get analytics data
const projectsResult = await projectService.getAllProjects();
const projects = projectsResult.projects || projectsResult;
const performanceStats = await projectService.getPerformanceStats();
// Calculate analytics metrics
const analytics = {
overview: {
totalProjects: projects.length,
publishedProjects: projects.filter(p => p.published).length,
featuredProjects: projects.filter(p => p.featured).length,
totalViews: projects.reduce((sum, p) => sum + ((p.analytics as any)?.views || 0), 0),
totalLikes: projects.reduce((sum, p) => sum + ((p.analytics as any)?.likes || 0), 0),
totalShares: projects.reduce((sum, p) => sum + ((p.analytics as any)?.shares || 0), 0),
avgLighthouse: projects.length > 0
? Math.round(projects.reduce((sum, p) => sum + ((p.performance as any)?.lighthouse || 0), 0) / projects.length)
: 0
},
projects: projects.map(project => ({
id: project.id,
title: project.title,
category: project.category,
difficulty: project.difficulty,
views: (project.analytics as any)?.views || 0,
likes: (project.analytics as any)?.likes || 0,
shares: (project.analytics as any)?.shares || 0,
lighthouse: (project.performance as any)?.lighthouse || 0,
published: project.published,
featured: project.featured,
createdAt: project.createdAt,
updatedAt: project.updatedAt
})),
categories: performanceStats.byCategory,
difficulties: performanceStats.byDifficulty,
performance: {
avgLighthouse: performanceStats.avgLighthouse,
totalViews: performanceStats.totalViews,
totalLikes: performanceStats.totalLikes,
totalShares: performanceStats.totalShares
}
};
// Cache the results
await analyticsCache.setOverallStats(analytics);
return NextResponse.json(analytics);
} catch (error) {
console.error('Analytics dashboard error:', error);
return NextResponse.json(
{ error: 'Failed to fetch analytics data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,87 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
export async function GET(request: NextRequest) {
try {
// Check admin authentication
const authHeader = request.headers.get('authorization');
const basicAuth = process.env.ADMIN_BASIC_AUTH;
if (!basicAuth) {
return new NextResponse('Admin access not configured', { status: 500 });
}
if (!authHeader || !authHeader.startsWith('Basic ')) {
return new NextResponse('Authentication required', { status: 401 });
}
const credentials = authHeader.split(' ')[1];
const [username, password] = Buffer.from(credentials, 'base64').toString().split(':');
const [expectedUsername, expectedPassword] = basicAuth.split(':');
if (username !== expectedUsername || password !== expectedPassword) {
return new NextResponse('Invalid credentials', { status: 401 });
}
// Get performance data from database
const pageViews = await prisma.pageView.findMany({
orderBy: { timestamp: 'desc' },
take: 1000 // Last 1000 page views
});
const userInteractions = await prisma.userInteraction.findMany({
orderBy: { timestamp: 'desc' },
take: 1000 // Last 1000 interactions
});
// Calculate performance metrics
const performance = {
pageViews: {
total: pageViews.length,
last24h: pageViews.filter(pv => {
const dayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
return new Date(pv.timestamp) > dayAgo;
}).length,
last7d: pageViews.filter(pv => {
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
return new Date(pv.timestamp) > weekAgo;
}).length,
last30d: pageViews.filter(pv => {
const monthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
return new Date(pv.timestamp) > monthAgo;
}).length
},
interactions: {
total: userInteractions.length,
last24h: userInteractions.filter(ui => {
const dayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
return new Date(ui.timestamp) > dayAgo;
}).length,
last7d: userInteractions.filter(ui => {
const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
return new Date(ui.timestamp) > weekAgo;
}).length,
last30d: userInteractions.filter(ui => {
const monthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
return new Date(ui.timestamp) > monthAgo;
}).length
},
topPages: pageViews.reduce((acc, pv) => {
acc[pv.page] = (acc[pv.page] || 0) + 1;
return acc;
}, {} as Record<string, number>),
topInteractions: userInteractions.reduce((acc, ui) => {
acc[ui.type] = (acc[ui.type] || 0) + 1;
return acc;
}, {} as Record<string, number>)
};
return NextResponse.json(performance);
} catch (error) {
console.error('Performance analytics error:', error);
return NextResponse.json(
{ error: 'Failed to fetch performance data' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from 'next/server';
import { projectService } from '@/lib/prisma';
export async function GET(request: NextRequest) {
try {
// Get all projects with full data
const projectsResult = await projectService.getAllProjects();
const projects = projectsResult.projects || projectsResult;
// Format for export
const exportData = {
version: '1.0',
exportDate: new Date().toISOString(),
projects: projects.map(project => ({
id: project.id,
title: project.title,
description: project.description,
content: project.content,
tags: project.tags,
category: project.category,
featured: project.featured,
github: project.github,
live: project.live,
published: project.published,
imageUrl: project.imageUrl,
difficulty: project.difficulty,
timeToComplete: project.timeToComplete,
technologies: project.technologies,
challenges: project.challenges,
lessonsLearned: project.lessonsLearned,
futureImprovements: project.futureImprovements,
demoVideo: project.demoVideo,
screenshots: project.screenshots,
colorScheme: project.colorScheme,
accessibility: project.accessibility,
performance: project.performance,
analytics: project.analytics,
createdAt: project.createdAt,
updatedAt: project.updatedAt
}))
};
// Return as downloadable JSON file
return new NextResponse(JSON.stringify(exportData, null, 2), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Content-Disposition': `attachment; filename="portfolio-projects-${new Date().toISOString().split('T')[0]}.json"`
}
});
} catch (error) {
console.error('Export error:', error);
return NextResponse.json(
{ error: 'Failed to export projects' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,89 @@
import { NextRequest, NextResponse } from 'next/server';
import { projectService } from '@/lib/prisma';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
// Validate import data structure
if (!body.projects || !Array.isArray(body.projects)) {
return NextResponse.json(
{ error: 'Invalid import data format' },
{ status: 400 }
);
}
const results = {
imported: 0,
skipped: 0,
errors: [] as string[]
};
// Process each project
for (const projectData of body.projects) {
try {
// Check if project already exists (by title)
const existingProjectsResult = await projectService.getAllProjects();
const existingProjects = existingProjectsResult.projects || existingProjectsResult;
const exists = existingProjects.some(p => p.title === projectData.title);
if (exists) {
results.skipped++;
results.errors.push(`Project "${projectData.title}" already exists`);
continue;
}
// Create new project
const newProject = await projectService.createProject({
title: projectData.title,
description: projectData.description,
content: projectData.content,
tags: projectData.tags || [],
category: projectData.category,
featured: projectData.featured || false,
github: projectData.github,
live: projectData.live,
published: projectData.published !== false, // Default to true
imageUrl: projectData.imageUrl,
difficulty: projectData.difficulty || 'Intermediate',
timeToComplete: projectData.timeToComplete,
technologies: projectData.technologies || [],
challenges: projectData.challenges || [],
lessonsLearned: projectData.lessonsLearned || [],
futureImprovements: projectData.futureImprovements || [],
demoVideo: projectData.demoVideo,
screenshots: projectData.screenshots || [],
colorScheme: projectData.colorScheme || 'Dark',
accessibility: projectData.accessibility !== false, // Default to true
performance: projectData.performance || {
lighthouse: 90,
bundleSize: '50KB',
loadTime: '1.5s'
},
analytics: projectData.analytics || {
views: 0,
likes: 0,
shares: 0
}
});
results.imported++;
} catch (error) {
results.skipped++;
results.errors.push(`Failed to import "${projectData.title}": ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
return NextResponse.json({
success: true,
message: `Import completed: ${results.imported} imported, ${results.skipped} skipped`,
results
});
} catch (error) {
console.error('Import error:', error);
return NextResponse.json(
{ error: 'Failed to import projects' },
{ status: 500 }
);
}
}

View File

@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { apiCache } from '@/lib/cache';
export async function GET(request: NextRequest) {
try {
@@ -12,6 +13,15 @@ export async function GET(request: NextRequest) {
const difficulty = searchParams.get('difficulty');
const search = searchParams.get('search');
// Create cache key based on parameters
const cacheKey = `projects:${page}:${limit}:${category || 'all'}:${featured || 'all'}:${published || 'all'}:${difficulty || 'all'}:${search || 'all'}`;
// Check cache first
const cached = await apiCache.getProjects();
if (cached && !search) { // Don't cache search results
return NextResponse.json(cached);
}
const skip = (page - 1) * limit;
const where: any = {};
@@ -40,12 +50,19 @@ export async function GET(request: NextRequest) {
prisma.project.count({ where })
]);
return NextResponse.json({
const result = {
projects,
total,
pages: Math.ceil(total / limit),
currentPage: page
});
};
// Cache the result (only for non-search queries)
if (!search) {
await apiCache.setProjects(result);
}
return NextResponse.json(result);
} catch (error) {
console.error('Error fetching projects:', error);
return NextResponse.json(
@@ -67,6 +84,9 @@ export async function POST(request: NextRequest) {
}
});
// Invalidate cache
await apiCache.invalidateAll();
return NextResponse.json(project);
} catch (error) {
console.error('Error creating project:', error);