๐๐ค Building a Secure AI-Powered Coding Challenge Platform
In the rapidly evolving world of software development, staying sharp with coding skills is essential. I built a secure, AI-powered platform that generates personalized coding challenges using modern web technologies. This project demonstrates how to combine artificial intelligence with robust security practices to create an educational tool that's both powerful and safe.
๐ FastAPI + โก React + ๐ Clerk + ๐ค OpenAI = The ultimate secure coding challenge generator with intelligent question generation and enterprise-grade authentication!
Live Demo GitHub Repository Demo Video
๐ฏ Project Vision
The platform addresses a common challenge in developer education: generating diverse, high-quality coding questions at scale while maintaining user security and preventing abuse. By leveraging AI for content generation and implementing robust authentication, the system provides a personalized learning experience with enterprise-grade security.
Core Problems Solved
- Content Scalability: AI generates unlimited unique coding challenges
- Security First: JWT-based authentication with webhook verification
- Abuse Prevention: Daily quotas and rate limiting
- User Experience: Seamless authentication flow with challenge history
- Educational Value: Structured questions with detailed explanations
๐ฌ Live Demo
See the platform in action! This demo showcases the complete user journey from authentication to challenge generation:
๐ฏ Demo Highlights: - Secure Authentication: Clerk integration with seamless login - AI Challenge Generation: Real-time question creation with OpenAI - Interactive UI: Modern React interface with smooth animations - Quota Management: Daily limits and usage tracking - Challenge History: Personal archive of completed challenges
โก Tech Stack Architecture
๐ Security-First Architecture
Security isn't an afterthoughtโit's built into every layer of the application.
Authentication Flow
sequenceDiagram
participant U as User
participant F as Frontend
participant C as Clerk
participant B as Backend
participant AI as OpenAI
U->>F: Access Application
F->>C: Authenticate User
C->>F: Return JWT Token
F->>B: API Request + JWT
B->>C: Verify Token
C->>B: Token Valid
B->>AI: Generate Challenge
AI->>B: Return Challenge
B->>F: Secure Response
F->>U: Display Challenge
Security Layers
- JWT Authentication: Clerk-managed tokens with automatic refresh
- Webhook Verification: Svix-powered signature validation
- Rate Limiting: Daily quotas prevent API abuse
- CORS Protection: Configured for secure cross-origin requests
- Environment Security: Secure credential management
๐ค AI-Powered Challenge Generation
The heart of the platform lies in its intelligent challenge generation system.
Challenge Structure
interface CodingChallenge {
question: string;
options: string[];
correct_answer: number;
explanation: string;
difficulty: 'easy' | 'medium' | 'hard';
topic: string;
}
AI Prompt Engineering
The system uses carefully crafted prompts to ensure consistent, high-quality output:
def generate_challenge_prompt(difficulty: str, topic: str) -> str:
return f"""
Generate a {difficulty} coding challenge about {topic}.
Requirements:
- Multiple choice with 4 options
- One correct answer
- Detailed explanation
- Practical, interview-style question
Return valid JSON matching the schema.
"""
Intelligent Features
- Difficulty Scaling: AI adjusts complexity based on user selection
- Topic Diversity: Covers algorithms, data structures, system design
- Explanation Quality: Detailed reasoning for learning reinforcement
- Validation: Pydantic models ensure data integrity
๐ฏ User Experience Design
Challenge Generation Flow
๐ Challenge Generation Flow
Watch the process in action
Select Difficulty
Choose your challenge level
AI Generation
OpenAI creates your question
Answer Challenge
Test your knowledge
View Results
Learn from explanations
Current Step:
Key UX Features
- Instant Feedback: Real-time challenge generation
- Progress Tracking: Visual quota indicators
- History Management: Personal challenge archive
- Responsive Design: Seamless mobile experience
- Error Handling: Graceful degradation with fallbacks
๐ Technical Implementation
Backend API Design
@app.post("/api/generate-challenge")
async def generate_challenge(
request: ChallengeRequest,
user: User = Depends(get_current_user)
):
# Check daily quota
if not await check_user_quota(user.id):
raise HTTPException(status_code=429, detail="Daily quota exceeded")
# Generate AI challenge
challenge = await ai_generator.create_challenge(
difficulty=request.difficulty,
topic=request.topic
)
# Save to database
await save_challenge(user.id, challenge)
# Update quota
await update_user_quota(user.id)
return challenge
Frontend State Management
const useChallenge = () => {
return useQuery({
queryKey: ['challenge', difficulty],
queryFn: async () => {
const response = await fetch('/api/generate-challenge', {
method: 'POST',
headers: {
'Authorization': `Bearer ${await getToken()}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ difficulty, topic })
});
return response.json();
},
staleTime: 0 // Always fresh challenges
});
};
Database Schema
-- Users managed by Clerk
CREATE TABLE challenges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
question TEXT NOT NULL,
options JSON NOT NULL,
correct_answer INTEGER NOT NULL,
explanation TEXT NOT NULL,
difficulty TEXT NOT NULL,
topic TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE user_quotas (
user_id TEXT PRIMARY KEY,
daily_count INTEGER DEFAULT 0,
last_reset DATE DEFAULT CURRENT_DATE
);
๐ Performance Optimizations
Frontend Optimizations
- Code Splitting: Route-based lazy loading
- React Query: Intelligent caching and background updates
- Vite + SWC: Lightning-fast development builds
- Bundle Analysis: Optimized chunk sizes
Backend Optimizations
- UV Package Manager: 10-100x faster than pip
- SQLAlchemy 2.0: Async database operations
- Connection Pooling: Efficient database connections
- Response Caching: Reduced API latency
AI Integration Optimizations
- Prompt Caching: Reuse optimized prompts
- Fallback Strategies: Graceful degradation
- Rate Limiting: Prevent API quota exhaustion
- Response Validation: Ensure data quality
๐ฎ Advanced Features
Quota Management System
async def reset_daily_quotas():
"""Reset quotas for all users daily"""
await database.execute("""
UPDATE user_quotas
SET daily_count = 0, last_reset = CURRENT_DATE
WHERE last_reset < CURRENT_DATE
""")
Webhook Security
@app.post("/webhooks/clerk")
async def handle_clerk_webhook(request: Request):
# Verify webhook signature
payload = await request.body()
headers = request.headers
try:
event = svix.Webhook(clerk_webhook_secret).verify(
payload, headers
)
except Exception:
raise HTTPException(status_code=400, detail="Invalid signature")
# Process user events
if event["type"] == "user.created":
await create_user_quota(event["data"]["id"])
return {"status": "success"}
๐ Real-World Impact
Educational Benefits
- Skill Assessment: Evaluate programming knowledge
- Interview Preparation: Practice with realistic questions
- Continuous Learning: Daily challenge routine
- Progress Tracking: Monitor improvement over time
Technical Benefits
- Scalable Architecture: Handle thousands of users
- Security Best Practices: Enterprise-grade protection
- Modern Stack: Latest web technologies
- Developer Experience: Fast development workflow
๐ง Development Workflow
Local Development Setup
# Backend setup
cd backend
uv sync
uv run server.py
# Frontend setup
cd frontend
npm install
npm run dev
# Ngrok for webhooks
ngrok http 8000 --domain=your-domain.ngrok-free.app
Environment Configuration
# Required Environment Variables
OPENAI_API_KEY=your_openai_key
CLERK_SECRET_KEY=your_clerk_secret
NGROK_AUTHTOKEN=your_ngrok_token
NGROK_DOMAIN=your-domain.ngrok-free.app
DATABASE_URL=sqlite:///./challenges.db
๐ก Key Learnings
Building this platform taught me valuable lessons about modern web development:
- Security First: Authentication should be built-in, not bolted-on
- AI Integration: Structured outputs are more reliable than free-form text
- User Experience: Real-time feedback improves engagement
- Performance: Modern tools like UV and Vite dramatically improve DX
- Architecture: Clean separation of concerns enables scalability
๐ Conclusion
This secure AI-powered coding challenge platform demonstrates how to build modern, scalable applications that prioritize both user experience and security. By combining cutting-edge AI capabilities with robust authentication and thoughtful architecture, we can create educational tools that are both powerful and safe.
The project showcases the potential of AI in education while maintaining the security standards required for production applications. As AI continues to evolve, platforms like this will play a crucial role in developer education and skill assessment.
Ready to test your coding skills? Try the platform and see how AI can personalize your learning journey while keeping your data secure!
๐ท๏ธ Tags
#AI
#Security
#FastAPI
#React
#Authentication
#OpenAI
#Webhooks
#Education
#FullStack
#ModernWeb