refactor
This commit is contained in:
@@ -14,6 +14,7 @@
|
|||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"dotenv": "^16.4.5",
|
"dotenv": "^16.4.5",
|
||||||
"cors": "^2.8.5",
|
"cors": "^2.8.5",
|
||||||
"node-fetch": "^3.3.2"
|
"node-fetch": "^3.3.2",
|
||||||
|
"express-rate-limit": "^7.1.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
60
backend/src/config.js
Normal file
60
backend/src/config.js
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
/**
|
||||||
|
* Environment configuration and validation
|
||||||
|
*/
|
||||||
|
|
||||||
|
const requiredEnvVars = [
|
||||||
|
'JWT_SECRET',
|
||||||
|
'DB_HOST',
|
||||||
|
'DB_USER',
|
||||||
|
'DB_PASSWORD',
|
||||||
|
'DB_NAME',
|
||||||
|
'TMDB_API_KEY'
|
||||||
|
];
|
||||||
|
|
||||||
|
export function validateConfig() {
|
||||||
|
const missing = [];
|
||||||
|
|
||||||
|
for (const varName of requiredEnvVars) {
|
||||||
|
if (!process.env[varName]) {
|
||||||
|
missing.push(varName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missing.length > 0) {
|
||||||
|
console.error('❌ Missing required environment variables:');
|
||||||
|
missing.forEach(varName => {
|
||||||
|
console.error(` - ${varName}`);
|
||||||
|
});
|
||||||
|
console.error('\nPlease set these in your .env file or environment.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate JWT_SECRET is strong enough
|
||||||
|
if (process.env.JWT_SECRET.length < 32) {
|
||||||
|
console.error('❌ JWT_SECRET must be at least 32 characters long for security.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('✅ Environment configuration validated');
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
jwt: {
|
||||||
|
secret: process.env.JWT_SECRET,
|
||||||
|
expiresIn: '7d'
|
||||||
|
},
|
||||||
|
db: {
|
||||||
|
host: process.env.DB_HOST,
|
||||||
|
user: process.env.DB_USER,
|
||||||
|
password: process.env.DB_PASSWORD,
|
||||||
|
database: process.env.DB_NAME,
|
||||||
|
port: parseInt(process.env.DB_PORT || '3306', 10)
|
||||||
|
},
|
||||||
|
tmdb: {
|
||||||
|
apiKey: process.env.TMDB_API_KEY,
|
||||||
|
baseUrl: 'https://api.themoviedb.org/3'
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: parseInt(process.env.PORT || '3000', 10)
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -4,7 +4,10 @@ import dotenv from 'dotenv';
|
|||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
|
import rateLimit from 'express-rate-limit';
|
||||||
import { initDB } from './db/index.js';
|
import { initDB } from './db/index.js';
|
||||||
|
import { validateConfig, config } from './config.js';
|
||||||
|
import { errorHandler } from './middleware/errorHandler.js';
|
||||||
import authRoutes from './routes/auth.js';
|
import authRoutes from './routes/auth.js';
|
||||||
import challengeRoutes from './routes/challenges.js';
|
import challengeRoutes from './routes/challenges.js';
|
||||||
import predictionRoutes from './routes/predictions.js';
|
import predictionRoutes from './routes/predictions.js';
|
||||||
@@ -14,22 +17,50 @@ import leaderboardRoutes from './routes/leaderboard.js';
|
|||||||
|
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
|
// Validate environment configuration
|
||||||
|
validateConfig();
|
||||||
|
|
||||||
const __filename = fileURLToPath(import.meta.url);
|
const __filename = fileURLToPath(import.meta.url);
|
||||||
const __dirname = path.dirname(__filename);
|
const __dirname = path.dirname(__filename);
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
|
// Rate limiting
|
||||||
|
const authLimiter = rateLimit({
|
||||||
|
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||||
|
max: 5, // 5 requests per window
|
||||||
|
message: { error: 'Too many authentication attempts, please try again later.' },
|
||||||
|
standardHeaders: true,
|
||||||
|
legacyHeaders: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const apiLimiter = rateLimit({
|
||||||
|
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||||
|
max: 100, // 100 requests per window
|
||||||
|
message: { error: 'Too many requests, please try again later.' },
|
||||||
|
standardHeaders: true,
|
||||||
|
legacyHeaders: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const tmdbLimiter = rateLimit({
|
||||||
|
windowMs: 60 * 1000, // 1 minute
|
||||||
|
max: 20, // 20 requests per minute
|
||||||
|
message: { error: 'Too many search requests, please slow down.' },
|
||||||
|
standardHeaders: true,
|
||||||
|
legacyHeaders: false,
|
||||||
|
});
|
||||||
|
|
||||||
// Middleware
|
// Middleware
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
// API Routes
|
// API Routes
|
||||||
app.use('/api/auth', authRoutes);
|
app.use('/api/auth', authLimiter, authRoutes);
|
||||||
app.use('/api/challenges', challengeRoutes);
|
app.use('/api/challenges', apiLimiter, challengeRoutes);
|
||||||
app.use('/api/predictions', predictionRoutes);
|
app.use('/api/predictions', apiLimiter, predictionRoutes);
|
||||||
app.use('/api/friends', friendRoutes);
|
app.use('/api/friends', apiLimiter, friendRoutes);
|
||||||
app.use('/api/tmdb', tmdbRoutes);
|
app.use('/api/tmdb', tmdbLimiter, tmdbRoutes);
|
||||||
app.use('/api/leaderboard', leaderboardRoutes);
|
app.use('/api/leaderboard', apiLimiter, leaderboardRoutes);
|
||||||
|
|
||||||
// Health check
|
// Health check
|
||||||
app.get('/api/health', (req, res) => {
|
app.get('/api/health', (req, res) => {
|
||||||
@@ -57,7 +88,10 @@ if (frontendExists) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const PORT = process.env.PORT || 4000;
|
// Error handling middleware (must be last)
|
||||||
|
app.use(errorHandler);
|
||||||
|
|
||||||
|
const PORT = config.server.port;
|
||||||
|
|
||||||
// Initialize database and start server
|
// Initialize database and start server
|
||||||
initDB()
|
initDB()
|
||||||
|
|||||||
58
backend/src/middleware/errorHandler.js
Normal file
58
backend/src/middleware/errorHandler.js
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
/**
|
||||||
|
* Centralized error handling middleware
|
||||||
|
*/
|
||||||
|
|
||||||
|
export class AppError extends Error {
|
||||||
|
constructor(message, statusCode = 500) {
|
||||||
|
super(message);
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
this.isOperational = true;
|
||||||
|
Error.captureStackTrace(this, this.constructor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function errorHandler(err, req, res, next) {
|
||||||
|
let { statusCode = 500, message } = err;
|
||||||
|
|
||||||
|
// Log error for debugging
|
||||||
|
if (process.env.NODE_ENV !== 'production') {
|
||||||
|
console.error('Error:', {
|
||||||
|
message: err.message,
|
||||||
|
stack: err.stack,
|
||||||
|
statusCode,
|
||||||
|
path: req.path,
|
||||||
|
method: req.method
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.error('Error:', err.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle specific error types
|
||||||
|
if (err.code === 'ER_DUP_ENTRY') {
|
||||||
|
statusCode = 409;
|
||||||
|
message = 'A record with this information already exists';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.name === 'JsonWebTokenError') {
|
||||||
|
statusCode = 401;
|
||||||
|
message = 'Invalid token';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.name === 'TokenExpiredError') {
|
||||||
|
statusCode = 401;
|
||||||
|
message = 'Token expired';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send error response
|
||||||
|
res.status(statusCode).json({
|
||||||
|
error: message,
|
||||||
|
...(process.env.NODE_ENV !== 'production' && { stack: err.stack })
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Async handler wrapper to catch errors in async routes
|
||||||
|
export function asyncHandler(fn) {
|
||||||
|
return (req, res, next) => {
|
||||||
|
Promise.resolve(fn(req, res, next)).catch(next);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -10,7 +10,8 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
"react-dom": "^18.2.0",
|
"react-dom": "^18.2.0",
|
||||||
"react-router-dom": "^6.20.0"
|
"react-router-dom": "^6.20.0",
|
||||||
|
"react-hot-toast": "^2.4.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
"@vitejs/plugin-react": "^4.2.1",
|
||||||
|
|||||||
62
frontend/src/components/ErrorBoundary.jsx
Normal file
62
frontend/src/components/ErrorBoundary.jsx
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import React from 'react';
|
||||||
|
|
||||||
|
class ErrorBoundary extends React.Component {
|
||||||
|
constructor(props) {
|
||||||
|
super(props);
|
||||||
|
this.state = { hasError: false, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
static getDerivedStateFromError(error) {
|
||||||
|
return { hasError: true, error };
|
||||||
|
}
|
||||||
|
|
||||||
|
componentDidCatch(error, errorInfo) {
|
||||||
|
console.error('Error caught by boundary:', error, errorInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (this.state.hasError) {
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
minHeight: '100vh',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
padding: '2rem'
|
||||||
|
}}>
|
||||||
|
<div className="card" style={{ maxWidth: '500px', textAlign: 'center' }}>
|
||||||
|
<h1 style={{ marginBottom: '1rem', color: 'var(--danger)' }}>Oops! Something went wrong</h1>
|
||||||
|
<p style={{ marginBottom: '1.5rem', color: 'var(--text-muted)' }}>
|
||||||
|
We're sorry, but something unexpected happened. Please refresh the page to try again.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
className="btn btn-primary"
|
||||||
|
onClick={() => window.location.href = '/'}
|
||||||
|
>
|
||||||
|
Go Home
|
||||||
|
</button>
|
||||||
|
{process.env.NODE_ENV === 'development' && this.state.error && (
|
||||||
|
<details style={{ marginTop: '2rem', textAlign: 'left' }}>
|
||||||
|
<summary style={{ cursor: 'pointer', color: 'var(--text-muted)' }}>Error Details</summary>
|
||||||
|
<pre style={{
|
||||||
|
marginTop: '1rem',
|
||||||
|
padding: '1rem',
|
||||||
|
background: 'var(--bg)',
|
||||||
|
borderRadius: '0.5rem',
|
||||||
|
overflow: 'auto',
|
||||||
|
fontSize: '0.75rem'
|
||||||
|
}}>
|
||||||
|
{this.state.error.toString()}
|
||||||
|
</pre>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.props.children;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ErrorBoundary;
|
||||||
20
frontend/src/hooks/useClickOutside.js
Normal file
20
frontend/src/hooks/useClickOutside.js
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { useEffect } from 'react';
|
||||||
|
|
||||||
|
export function useClickOutside(ref, handler) {
|
||||||
|
useEffect(() => {
|
||||||
|
const listener = (event) => {
|
||||||
|
if (!ref.current || ref.current.contains(event.target)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
handler(event);
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('mousedown', listener);
|
||||||
|
document.addEventListener('touchstart', listener);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousedown', listener);
|
||||||
|
document.removeEventListener('touchstart', listener);
|
||||||
|
};
|
||||||
|
}, [ref, handler]);
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import ReactDOM from 'react-dom/client';
|
import ReactDOM from 'react-dom/client';
|
||||||
import { BrowserRouter, Routes, Route, Navigate, Link } from 'react-router-dom';
|
import { BrowserRouter, Routes, Route, Navigate, Link } from 'react-router-dom';
|
||||||
|
import { Toaster } from 'react-hot-toast';
|
||||||
import { AuthProvider, useAuth } from './AuthContext';
|
import { AuthProvider, useAuth } from './AuthContext';
|
||||||
import Login from './pages/Login';
|
import Login from './pages/Login';
|
||||||
import Register from './pages/Register';
|
import Register from './pages/Register';
|
||||||
@@ -9,6 +10,7 @@ import ChallengeDetail from './pages/ChallengeDetail';
|
|||||||
import Profile from './pages/Profile';
|
import Profile from './pages/Profile';
|
||||||
import Friends from './pages/Friends';
|
import Friends from './pages/Friends';
|
||||||
import Leaderboard from './pages/Leaderboard';
|
import Leaderboard from './pages/Leaderboard';
|
||||||
|
import ErrorBoundary from './components/ErrorBoundary';
|
||||||
import './App.css';
|
import './App.css';
|
||||||
|
|
||||||
function ProtectedRoute({ children }) {
|
function ProtectedRoute({ children }) {
|
||||||
@@ -50,8 +52,32 @@ function Header() {
|
|||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
|
<ErrorBoundary>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
|
<Toaster
|
||||||
|
position="top-right"
|
||||||
|
toastOptions={{
|
||||||
|
duration: 3000,
|
||||||
|
style: {
|
||||||
|
background: '#1e293b',
|
||||||
|
color: '#f1f5f9',
|
||||||
|
border: '1px solid #334155',
|
||||||
|
},
|
||||||
|
success: {
|
||||||
|
iconTheme: {
|
||||||
|
primary: '#10b981',
|
||||||
|
secondary: '#f1f5f9',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
error: {
|
||||||
|
iconTheme: {
|
||||||
|
primary: '#ef4444',
|
||||||
|
secondary: '#f1f5f9',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<Header />
|
<Header />
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="/login" element={<Login />} />
|
<Route path="/login" element={<Login />} />
|
||||||
@@ -65,6 +91,7 @@ function App() {
|
|||||||
</Routes>
|
</Routes>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
|
</ErrorBoundary>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { useParams, Link } from 'react-router-dom';
|
import { useParams, Link } from 'react-router-dom';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
import { useAuth } from '../AuthContext';
|
import { useAuth } from '../AuthContext';
|
||||||
import api from '../api';
|
import api from '../api';
|
||||||
|
import { useClickOutside } from '../hooks/useClickOutside';
|
||||||
|
|
||||||
export default function ChallengeDetail() {
|
export default function ChallengeDetail() {
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
@@ -15,6 +17,11 @@ export default function ChallengeDetail() {
|
|||||||
const [showInvite, setShowInvite] = useState(false);
|
const [showInvite, setShowInvite] = useState(false);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [searchTimeout, setSearchTimeout] = useState(null);
|
const [searchTimeout, setSearchTimeout] = useState(null);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [validating, setValidating] = useState(null);
|
||||||
|
const searchRef = useRef(null);
|
||||||
|
|
||||||
|
useClickOutside(searchRef, () => setSearchResults([]));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadChallenge();
|
loadChallenge();
|
||||||
@@ -55,25 +62,33 @@ export default function ChallengeDetail() {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!newPrediction.trim()) return;
|
if (!newPrediction.trim()) return;
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
try {
|
try {
|
||||||
await api.createPrediction({
|
await api.createPrediction({
|
||||||
challenge_id: id,
|
challenge_id: id,
|
||||||
content: newPrediction
|
content: newPrediction
|
||||||
});
|
});
|
||||||
|
toast.success('Prediction submitted!');
|
||||||
setNewPrediction('');
|
setNewPrediction('');
|
||||||
await loadPredictions();
|
await loadPredictions();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('Failed to create prediction: ' + err.message);
|
toast.error('Failed to create prediction: ' + err.message);
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleValidate = async (predictionId, status) => {
|
const handleValidate = async (predictionId, status) => {
|
||||||
|
setValidating(predictionId);
|
||||||
try {
|
try {
|
||||||
await api.validatePrediction(predictionId, status);
|
await api.validatePrediction(predictionId, status);
|
||||||
|
toast.success(status === 'validated' ? 'Prediction validated!' : 'Prediction invalidated');
|
||||||
await loadPredictions();
|
await loadPredictions();
|
||||||
await loadLeaderboard();
|
await loadLeaderboard();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('Failed to validate: ' + err.message);
|
toast.error('Failed to validate: ' + err.message);
|
||||||
|
} finally {
|
||||||
|
setValidating(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -106,11 +121,11 @@ export default function ChallengeDetail() {
|
|||||||
const handleInvite = async (userId) => {
|
const handleInvite = async (userId) => {
|
||||||
try {
|
try {
|
||||||
await api.inviteToChallenge(id, { user_ids: [userId] });
|
await api.inviteToChallenge(id, { user_ids: [userId] });
|
||||||
|
toast.success('Invitation sent!');
|
||||||
setInviteQuery('');
|
setInviteQuery('');
|
||||||
setSearchResults([]);
|
setSearchResults([]);
|
||||||
alert('Invitation sent!');
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('Failed to send invite: ' + err.message);
|
toast.error('Failed to send invite: ' + err.message);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -154,7 +169,7 @@ export default function ChallengeDetail() {
|
|||||||
|
|
||||||
{/* Invite Section */}
|
{/* Invite Section */}
|
||||||
{showInvite && (
|
{showInvite && (
|
||||||
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }}>
|
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }} ref={searchRef}>
|
||||||
<h3 style={{ marginBottom: '1rem' }}>Invite Someone</h3>
|
<h3 style={{ marginBottom: '1rem' }}>Invite Someone</h3>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -232,8 +247,8 @@ export default function ChallengeDetail() {
|
|||||||
onChange={(e) => setNewPrediction(e.target.value)}
|
onChange={(e) => setNewPrediction(e.target.value)}
|
||||||
style={{ minHeight: '80px' }}
|
style={{ minHeight: '80px' }}
|
||||||
/>
|
/>
|
||||||
<button type="submit" className="btn btn-primary" style={{ marginTop: '1rem' }}>
|
<button type="submit" className="btn btn-primary" style={{ marginTop: '1rem' }} disabled={submitting}>
|
||||||
Submit Prediction
|
{submitting ? 'Submitting...' : 'Submit Prediction'}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
@@ -261,14 +276,16 @@ export default function ChallengeDetail() {
|
|||||||
<button
|
<button
|
||||||
className="btn btn-success btn-sm"
|
className="btn btn-success btn-sm"
|
||||||
onClick={() => handleValidate(pred.id, 'validated')}
|
onClick={() => handleValidate(pred.id, 'validated')}
|
||||||
|
disabled={validating === pred.id}
|
||||||
>
|
>
|
||||||
✓ Validate
|
{validating === pred.id ? '...' : '✓ Validate'}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="btn btn-danger btn-sm"
|
className="btn btn-danger btn-sm"
|
||||||
onClick={() => handleValidate(pred.id, 'invalidated')}
|
onClick={() => handleValidate(pred.id, 'invalidated')}
|
||||||
|
disabled={validating === pred.id}
|
||||||
>
|
>
|
||||||
✗ Invalidate
|
{validating === pred.id ? '...' : '✗ Invalidate'}
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Link } from 'react-router-dom';
|
import { Link } from 'react-router-dom';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
import api from '../api';
|
import api from '../api';
|
||||||
|
import { useClickOutside } from '../hooks/useClickOutside';
|
||||||
|
|
||||||
export default function ChallengeList() {
|
export default function ChallengeList() {
|
||||||
const [challenges, setChallenges] = useState([]);
|
const [challenges, setChallenges] = useState([]);
|
||||||
@@ -10,6 +12,10 @@ export default function ChallengeList() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [creating, setCreating] = useState(false);
|
const [creating, setCreating] = useState(false);
|
||||||
const [searchTimeout, setSearchTimeout] = useState(null);
|
const [searchTimeout, setSearchTimeout] = useState(null);
|
||||||
|
const [respondingTo, setRespondingTo] = useState(null);
|
||||||
|
const searchRef = useRef(null);
|
||||||
|
|
||||||
|
useClickOutside(searchRef, () => setShowResults([]));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadChallenges();
|
loadChallenges();
|
||||||
@@ -31,11 +37,15 @@ export default function ChallengeList() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleRespondToInvite = async (challengeId, status) => {
|
const handleRespondToInvite = async (challengeId, status) => {
|
||||||
|
setRespondingTo(challengeId);
|
||||||
try {
|
try {
|
||||||
await api.respondToChallenge(challengeId, status);
|
await api.respondToChallenge(challengeId, status);
|
||||||
|
toast.success(status === 'accepted' ? 'Challenge accepted!' : 'Challenge declined');
|
||||||
await loadChallenges();
|
await loadChallenges();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('Failed to respond: ' + err.message);
|
toast.error('Failed to respond: ' + err.message);
|
||||||
|
} finally {
|
||||||
|
setRespondingTo(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -72,18 +82,19 @@ export default function ChallengeList() {
|
|||||||
? `https://image.tmdb.org/t/p/w500${show.poster_path}`
|
? `https://image.tmdb.org/t/p/w500${show.poster_path}`
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const result = await api.createChallenge({
|
await api.createChallenge({
|
||||||
title: show.title,
|
title: show.title,
|
||||||
cover_image_url: coverImage,
|
cover_image_url: coverImage,
|
||||||
tmdb_id: show.id,
|
tmdb_id: show.id,
|
||||||
media_type: show.media_type
|
media_type: show.media_type
|
||||||
});
|
});
|
||||||
|
|
||||||
|
toast.success('Challenge created!');
|
||||||
setSearchQuery('');
|
setSearchQuery('');
|
||||||
setShowResults([]);
|
setShowResults([]);
|
||||||
await loadChallenges();
|
await loadChallenges();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('Failed to create challenge: ' + err.message);
|
toast.error('Failed to create challenge: ' + err.message);
|
||||||
} finally {
|
} finally {
|
||||||
setCreating(false);
|
setCreating(false);
|
||||||
}
|
}
|
||||||
@@ -124,14 +135,16 @@ export default function ChallengeList() {
|
|||||||
<button
|
<button
|
||||||
className="btn btn-success btn-sm"
|
className="btn btn-success btn-sm"
|
||||||
onClick={() => handleRespondToInvite(challenge.id, 'accepted')}
|
onClick={() => handleRespondToInvite(challenge.id, 'accepted')}
|
||||||
|
disabled={respondingTo === challenge.id}
|
||||||
>
|
>
|
||||||
Accept
|
{respondingTo === challenge.id ? '...' : 'Accept'}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="btn btn-danger btn-sm"
|
className="btn btn-danger btn-sm"
|
||||||
onClick={() => handleRespondToInvite(challenge.id, 'rejected')}
|
onClick={() => handleRespondToInvite(challenge.id, 'rejected')}
|
||||||
|
disabled={respondingTo === challenge.id}
|
||||||
>
|
>
|
||||||
Decline
|
{respondingTo === challenge.id ? '...' : 'Decline'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -141,7 +154,7 @@ export default function ChallengeList() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Search/Create */}
|
{/* Search/Create */}
|
||||||
<div style={{ marginBottom: '2rem', position: 'relative' }}>
|
<div style={{ marginBottom: '2rem', position: 'relative' }} ref={searchRef}>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
className="input"
|
className="input"
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
import api from '../api';
|
import api from '../api';
|
||||||
|
import { useClickOutside } from '../hooks/useClickOutside';
|
||||||
|
|
||||||
export default function Friends() {
|
export default function Friends() {
|
||||||
const [friends, setFriends] = useState([]);
|
const [friends, setFriends] = useState([]);
|
||||||
@@ -9,6 +11,11 @@ export default function Friends() {
|
|||||||
const [searchResults, setSearchResults] = useState([]);
|
const [searchResults, setSearchResults] = useState([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [searchTimeout, setSearchTimeout] = useState(null);
|
const [searchTimeout, setSearchTimeout] = useState(null);
|
||||||
|
const [responding, setResponding] = useState(null);
|
||||||
|
const [sending, setSending] = useState(null);
|
||||||
|
const searchRef = useRef(null);
|
||||||
|
|
||||||
|
useClickOutside(searchRef, () => setSearchResults([]));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadData();
|
loadData();
|
||||||
@@ -57,22 +64,29 @@ export default function Friends() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSendRequest = async (userId) => {
|
const handleSendRequest = async (userId) => {
|
||||||
|
setSending(userId);
|
||||||
try {
|
try {
|
||||||
await api.sendFriendRequest(userId);
|
await api.sendFriendRequest(userId);
|
||||||
setSearchQuery('');
|
setSearchQuery('');
|
||||||
setSearchResults([]);
|
setSearchResults([]);
|
||||||
alert('Friend request sent!');
|
toast.success('Friend request sent!');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('Failed to send request: ' + err.message);
|
toast.error('Failed to send request: ' + err.message);
|
||||||
|
} finally {
|
||||||
|
setSending(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleRespond = async (requestId, status) => {
|
const handleRespond = async (requestId, status) => {
|
||||||
|
setResponding(requestId);
|
||||||
try {
|
try {
|
||||||
await api.respondToFriendRequest(requestId, status);
|
await api.respondToFriendRequest(requestId, status);
|
||||||
|
toast.success(status === 'accepted' ? 'Friend request accepted!' : 'Friend request declined');
|
||||||
await loadData();
|
await loadData();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert('Failed to respond: ' + err.message);
|
toast.error('Failed to respond: ' + err.message);
|
||||||
|
} finally {
|
||||||
|
setResponding(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -86,7 +100,7 @@ export default function Friends() {
|
|||||||
<h1 style={{ marginBottom: '2rem' }}>Friends</h1>
|
<h1 style={{ marginBottom: '2rem' }}>Friends</h1>
|
||||||
|
|
||||||
{/* Search */}
|
{/* Search */}
|
||||||
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }}>
|
<div className="card" style={{ marginBottom: '2rem', position: 'relative' }} ref={searchRef}>
|
||||||
<h3 style={{ marginBottom: '1rem' }}>Add Friends</h3>
|
<h3 style={{ marginBottom: '1rem' }}>Add Friends</h3>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -127,8 +141,9 @@ export default function Friends() {
|
|||||||
<button
|
<button
|
||||||
className="btn btn-primary btn-sm"
|
className="btn btn-primary btn-sm"
|
||||||
onClick={() => handleSendRequest(user.id)}
|
onClick={() => handleSendRequest(user.id)}
|
||||||
|
disabled={sending === user.id}
|
||||||
>
|
>
|
||||||
Add Friend
|
{sending === user.id ? 'Sending...' : 'Add Friend'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -151,14 +166,16 @@ export default function Friends() {
|
|||||||
<button
|
<button
|
||||||
className="btn btn-success btn-sm"
|
className="btn btn-success btn-sm"
|
||||||
onClick={() => handleRespond(req.id, 'accepted')}
|
onClick={() => handleRespond(req.id, 'accepted')}
|
||||||
|
disabled={responding === req.id}
|
||||||
>
|
>
|
||||||
Accept
|
{responding === req.id ? '...' : 'Accept'}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
className="btn btn-danger btn-sm"
|
className="btn btn-danger btn-sm"
|
||||||
onClick={() => handleRespond(req.id, 'rejected')}
|
onClick={() => handleRespond(req.id, 'rejected')}
|
||||||
|
disabled={responding === req.id}
|
||||||
>
|
>
|
||||||
Reject
|
{responding === req.id ? '...' : 'Reject'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,25 +1,25 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { useNavigate, Link } from 'react-router-dom';
|
import { useNavigate, Link } from 'react-router-dom';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
import { useAuth } from '../AuthContext';
|
import { useAuth } from '../AuthContext';
|
||||||
|
|
||||||
export default function Login() {
|
export default function Login() {
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const { login } = useAuth();
|
const { login } = useAuth();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const handleSubmit = async (e) => {
|
const handleSubmit = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError('');
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await login(email, password);
|
await login(email, password);
|
||||||
|
toast.success('Welcome back!');
|
||||||
navigate('/challenges');
|
navigate('/challenges');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
toast.error(err.message || 'Login failed');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,6 @@ export default function Login() {
|
|||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{error && <div className="error">{error}</div>}
|
|
||||||
<button type="submit" className="btn btn-primary" style={{ width: '100%', marginTop: '1rem' }} disabled={loading}>
|
<button type="submit" className="btn btn-primary" style={{ width: '100%', marginTop: '1rem' }} disabled={loading}>
|
||||||
{loading ? 'Logging in...' : 'Login'}
|
{loading ? 'Logging in...' : 'Login'}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { useNavigate, Link } from 'react-router-dom';
|
import { useNavigate, Link } from 'react-router-dom';
|
||||||
|
import toast from 'react-hot-toast';
|
||||||
import { useAuth } from '../AuthContext';
|
import { useAuth } from '../AuthContext';
|
||||||
|
|
||||||
export default function Register() {
|
export default function Register() {
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [username, setUsername] = useState('');
|
const [username, setUsername] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [error, setError] = useState('');
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const { register } = useAuth();
|
const { register } = useAuth();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
|
||||||
const handleSubmit = async (e) => {
|
const handleSubmit = async (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError('');
|
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await register(email, username, password);
|
await register(email, username, password);
|
||||||
|
toast.success('Account created successfully!');
|
||||||
navigate('/challenges');
|
navigate('/challenges');
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err.message);
|
toast.error(err.message || 'Registration failed');
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -62,7 +62,6 @@ export default function Register() {
|
|||||||
minLength={6}
|
minLength={6}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{error && <div className="error">{error}</div>}
|
|
||||||
<button type="submit" className="btn btn-primary" style={{ width: '100%', marginTop: '1rem' }} disabled={loading}>
|
<button type="submit" className="btn btn-primary" style={{ width: '100%', marginTop: '1rem' }} disabled={loading}>
|
||||||
{loading ? 'Creating account...' : 'Register'}
|
{loading ? 'Creating account...' : 'Register'}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
Reference in New Issue
Block a user