feat: User management, SMTP email activation and password resets
Build and Deploy / build-and-push (push) Successful in 1m0s
Build and Deploy / build-and-push (push) Successful in 1m0s
This commit is contained in:
@@ -44,6 +44,18 @@ const initDB = async () => {
|
|||||||
// Ignore if it already exists
|
// Ignore if it already exists
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.query(`ALTER TABLE profiles ADD COLUMN activation_token TEXT`);
|
||||||
|
} catch (err) {
|
||||||
|
// Ignore if it already exists
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await client.query(`ALTER TABLE profiles ADD COLUMN reset_token TEXT`);
|
||||||
|
} catch (err) {
|
||||||
|
// Ignore if it already exists
|
||||||
|
}
|
||||||
|
|
||||||
await client.query(`
|
await client.query(`
|
||||||
CREATE TABLE IF NOT EXISTS projects (
|
CREATE TABLE IF NOT EXISTS projects (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
|
|||||||
@@ -40,7 +40,35 @@ const sendMail = async (to, subject, text, html = '') => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const sendActivationEmail = async (email, token, baseUrl) => {
|
||||||
|
const activationLink = `${baseUrl}/activate?token=${token}`;
|
||||||
|
const subject = "Activate your Titan 3D Account";
|
||||||
|
const html = `
|
||||||
|
<h2>Welcome to Titan 3D!</h2>
|
||||||
|
<p>Please click the link below to activate your account:</p>
|
||||||
|
<a href="${activationLink}">${activationLink}</a>
|
||||||
|
<p>If you did not request this, please ignore this email.</p>
|
||||||
|
`;
|
||||||
|
const text = `Welcome to Titan 3D! Please navigate to the following link to activate your account: ${activationLink}`;
|
||||||
|
return sendMail(email, subject, text, html);
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendPasswordResetEmail = async (email, token, baseUrl) => {
|
||||||
|
const resetLink = `${baseUrl}/reset-password?token=${token}`;
|
||||||
|
const subject = "Reset your Titan 3D Password";
|
||||||
|
const html = `
|
||||||
|
<h2>Password Reset Request</h2>
|
||||||
|
<p>Please click the link below to securely reset your password:</p>
|
||||||
|
<a href="${resetLink}">${resetLink}</a>
|
||||||
|
<p>If you did not request this, please ignore this email.</p>
|
||||||
|
`;
|
||||||
|
const text = `Please navigate to the following link to reset your password: ${resetLink}`;
|
||||||
|
return sendMail(email, subject, text, html);
|
||||||
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
sendMail,
|
sendMail,
|
||||||
|
sendActivationEmail,
|
||||||
|
sendPasswordResetEmail,
|
||||||
transporter
|
transporter
|
||||||
};
|
};
|
||||||
|
|||||||
+143
-4
@@ -11,8 +11,10 @@ const pdfParse = require('pdf-parse');
|
|||||||
const { GoogleGenerativeAI } = require('@google/generative-ai');
|
const { GoogleGenerativeAI } = require('@google/generative-ai');
|
||||||
const axios = require('axios');
|
const axios = require('axios');
|
||||||
|
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
const { db, run, get, all } = require('./database');
|
const { db, run, get, all } = require('./database');
|
||||||
const { sendMail } = require('./mail');
|
const { sendMail, sendActivationEmail, sendPasswordResetEmail } = require('./mail');
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
@@ -70,13 +72,26 @@ app.post('/api/auth/register', async (req, res) => {
|
|||||||
const role = parseInt(countRow.count) === 0 ? 'admin' : 'user';
|
const role = parseInt(countRow.count) === 0 ? 'admin' : 'user';
|
||||||
const is_active = parseInt(countRow.count) === 0 ? true : false;
|
const is_active = parseInt(countRow.count) === 0 ? true : false;
|
||||||
|
|
||||||
|
let activation_token = null;
|
||||||
|
if (!is_active) {
|
||||||
|
activation_token = crypto.randomBytes(32).toString('hex');
|
||||||
|
}
|
||||||
|
|
||||||
await run(
|
await run(
|
||||||
'INSERT INTO profiles (id, email, password_hash, role, api_credits, storage_limit_mb, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
'INSERT INTO profiles (id, email, password_hash, role, api_credits, storage_limit_mb, is_active, activation_token) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||||
[id, email, hash, role, 10, 500, is_active]
|
[id, email, hash, role, 10, 500, is_active, activation_token]
|
||||||
);
|
);
|
||||||
|
|
||||||
if (is_active === false) {
|
if (is_active === false) {
|
||||||
return res.json({ status: 'pending', message: 'Account created. Please contact an administrator to activate your account.' });
|
// Send activation email
|
||||||
|
const baseUrl = req.headers.origin || 'http://localhost:5173';
|
||||||
|
try {
|
||||||
|
await sendActivationEmail(email, activation_token, baseUrl);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to send activation email', err);
|
||||||
|
// We still return pending, maybe they can resend later
|
||||||
|
}
|
||||||
|
return res.json({ status: 'pending', message: 'Account created. Please check your email for the activation link.' });
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = jwt.sign({ id, email, role }, JWT_SECRET, { expiresIn: '7d' });
|
const token = jwt.sign({ id, email, role }, JWT_SECRET, { expiresIn: '7d' });
|
||||||
@@ -87,6 +102,21 @@ app.post('/api/auth/register', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 1.5. Auth Activate
|
||||||
|
app.post('/api/auth/activate', async (req, res) => {
|
||||||
|
const { token } = req.body;
|
||||||
|
if (!token) return res.status(400).json({ error: 'Activation token required' });
|
||||||
|
try {
|
||||||
|
const user = await get('SELECT * FROM profiles WHERE activation_token = ?', [token]);
|
||||||
|
if (!user) return res.status(400).json({ error: 'Invalid or expired activation token' });
|
||||||
|
|
||||||
|
await run('UPDATE profiles SET is_active = true, activation_token = NULL WHERE id = ?', [user.id]);
|
||||||
|
res.json({ success: true, message: 'Account activated successfully.' });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// 2. Auth Login
|
// 2. Auth Login
|
||||||
app.post('/api/auth/login', async (req, res) => {
|
app.post('/api/auth/login', async (req, res) => {
|
||||||
const { email, password } = req.body;
|
const { email, password } = req.body;
|
||||||
@@ -221,6 +251,53 @@ app.get('/api/users', authenticate, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 7.1. Add user (Admin only)
|
||||||
|
app.post('/api/users', authenticate, async (req, res) => {
|
||||||
|
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
|
||||||
|
const { email, role, api_credits, storage_limit_mb } = req.body;
|
||||||
|
if (!email) return res.status(400).json({ error: 'Email required' });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const existing = await get('SELECT * FROM profiles WHERE email = ?', [email]);
|
||||||
|
if (existing) return res.status(400).json({ error: 'User already exists' });
|
||||||
|
|
||||||
|
// Generate random temp password (they will reset it anyway)
|
||||||
|
const tempPassword = crypto.randomBytes(16).toString('hex');
|
||||||
|
const hash = await bcrypt.hash(tempPassword, 10);
|
||||||
|
const id = uuidv4();
|
||||||
|
const activation_token = crypto.randomBytes(32).toString('hex');
|
||||||
|
|
||||||
|
await run(
|
||||||
|
'INSERT INTO profiles (id, email, password_hash, role, api_credits, storage_limit_mb, is_active, activation_token) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
|
||||||
|
[id, email, hash, role || 'user', api_credits || 10, storage_limit_mb || 500, false, activation_token]
|
||||||
|
);
|
||||||
|
|
||||||
|
const baseUrl = req.headers.origin || 'http://localhost:5173';
|
||||||
|
try {
|
||||||
|
await sendActivationEmail(email, activation_token, baseUrl);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to send activation email', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ success: true, message: 'User created and activation email sent.' });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 7.2. Delete user (Admin only)
|
||||||
|
app.delete('/api/users/:id', authenticate, async (req, res) => {
|
||||||
|
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
|
||||||
|
try {
|
||||||
|
// Cascade delete projects for the user
|
||||||
|
await run('DELETE FROM projects WHERE user_id = ?', [req.params.id]);
|
||||||
|
await run('DELETE FROM profiles WHERE id = ?', [req.params.id]);
|
||||||
|
res.json({ success: true });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// 8. Update user (Admin only)
|
// 8. Update user (Admin only)
|
||||||
app.put('/api/users/:id', authenticate, async (req, res) => {
|
app.put('/api/users/:id', authenticate, async (req, res) => {
|
||||||
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
|
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
|
||||||
@@ -233,6 +310,68 @@ app.put('/api/users/:id', authenticate, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 8.1. Admin trigger reset password for user
|
||||||
|
app.post('/api/users/:id/reset-password', authenticate, async (req, res) => {
|
||||||
|
if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
|
||||||
|
try {
|
||||||
|
const user = await get('SELECT * FROM profiles WHERE id = ?', [req.params.id]);
|
||||||
|
if (!user) return res.status(404).json({ error: 'User not found' });
|
||||||
|
|
||||||
|
const reset_token = crypto.randomBytes(32).toString('hex');
|
||||||
|
await run('UPDATE profiles SET reset_token = ? WHERE id = ?', [reset_token, user.id]);
|
||||||
|
|
||||||
|
const baseUrl = req.headers.origin || 'http://localhost:5173';
|
||||||
|
try {
|
||||||
|
await sendPasswordResetEmail(user.email, reset_token, baseUrl);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to send reset email', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ success: true, message: 'Password reset email sent to user.' });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 8.2. Forgot Password (User request)
|
||||||
|
app.post('/api/auth/forgot-password', async (req, res) => {
|
||||||
|
const { email } = req.body;
|
||||||
|
if (!email) return res.status(400).json({ error: 'Email required' });
|
||||||
|
try {
|
||||||
|
const user = await get('SELECT * FROM profiles WHERE email = ?', [email]);
|
||||||
|
if (user) {
|
||||||
|
const reset_token = crypto.randomBytes(32).toString('hex');
|
||||||
|
await run('UPDATE profiles SET reset_token = ? WHERE id = ?', [reset_token, user.id]);
|
||||||
|
const baseUrl = req.headers.origin || 'http://localhost:5173';
|
||||||
|
try {
|
||||||
|
await sendPasswordResetEmail(user.email, reset_token, baseUrl);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to send reset email', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Always return success to prevent email enumeration
|
||||||
|
res.json({ success: true, message: 'If an account exists, a reset link has been sent.' });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 8.3. Reset Password (User submission)
|
||||||
|
app.post('/api/auth/reset-password', async (req, res) => {
|
||||||
|
const { token, newPassword } = req.body;
|
||||||
|
if (!token || !newPassword) return res.status(400).json({ error: 'Token and new password required' });
|
||||||
|
try {
|
||||||
|
const user = await get('SELECT * FROM profiles WHERE reset_token = ?', [token]);
|
||||||
|
if (!user) return res.status(400).json({ error: 'Invalid or expired reset token' });
|
||||||
|
|
||||||
|
const hash = await bcrypt.hash(newPassword, 10);
|
||||||
|
await run('UPDATE profiles SET password_hash = ?, reset_token = NULL WHERE id = ?', [hash, user.id]);
|
||||||
|
res.json({ success: true, message: 'Password has been reset successfully.' });
|
||||||
|
} catch (err) {
|
||||||
|
res.status(500).json({ error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// 9. Deduct API credit
|
// 9. Deduct API credit
|
||||||
app.post('/api/users/deduct-credit', authenticate, async (req, res) => {
|
app.post('/api/users/deduct-credit', authenticate, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import Home from './pages/Home';
|
|||||||
import Dashboard from './pages/Dashboard';
|
import Dashboard from './pages/Dashboard';
|
||||||
import Admin from './pages/Admin';
|
import Admin from './pages/Admin';
|
||||||
import SparkPlug from './pages/SparkPlug';
|
import SparkPlug from './pages/SparkPlug';
|
||||||
|
import Activate from './pages/Activate';
|
||||||
|
import ResetPassword from './pages/ResetPassword';
|
||||||
import { AuthModal } from './components/AuthModal';
|
import { AuthModal } from './components/AuthModal';
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
@@ -32,6 +34,8 @@ export default function App() {
|
|||||||
<Routes>
|
<Routes>
|
||||||
{/* Public Routes */}
|
{/* Public Routes */}
|
||||||
<Route path="/" element={<Home />} />
|
<Route path="/" element={<Home />} />
|
||||||
|
<Route path="/activate" element={<Activate />} />
|
||||||
|
<Route path="/reset-password" element={<ResetPassword />} />
|
||||||
|
|
||||||
{/* Protected Routes (User) */}
|
{/* Protected Routes (User) */}
|
||||||
<Route element={<ProtectedRoute allowedRoles={['user', 'admin']} />}>
|
<Route element={<ProtectedRoute allowedRoles={['user', 'admin']} />}>
|
||||||
|
|||||||
@@ -26,10 +26,13 @@ export function AuthModal() {
|
|||||||
setSuccess('');
|
setSuccess('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (isRegister) {
|
if (authMode === 'forgot-password') {
|
||||||
|
await api.forgotPassword(email);
|
||||||
|
setSuccess('If an account exists, a reset link has been sent to your email.');
|
||||||
|
} else if (isRegister) {
|
||||||
const res = await api.register(email, password);
|
const res = await api.register(email, password);
|
||||||
if (res.status === 'pending') {
|
if (res.status === 'pending') {
|
||||||
setSuccess(res.message || 'Account created successfully! Please contact an admin to activate your account.');
|
setSuccess(res.message || 'Account created successfully! Please check your email for the activation link.');
|
||||||
setEmail('');
|
setEmail('');
|
||||||
setPassword('');
|
setPassword('');
|
||||||
} else {
|
} else {
|
||||||
@@ -84,10 +87,10 @@ export function AuthModal() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h2 className="text-2xl font-bold text-white text-center mb-2 relative z-10">
|
<h2 className="text-2xl font-bold text-white text-center mb-2 relative z-10">
|
||||||
{isRegister ? 'Create an Account' : 'Welcome Back'}
|
{authMode === 'forgot-password' ? 'Reset Password' : isRegister ? 'Create an Account' : 'Welcome Back'}
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-zinc-400 text-sm text-center mb-8 relative z-10">
|
<p className="text-zinc-400 text-sm text-center mb-8 relative z-10">
|
||||||
{isRegister ? 'Sign up to start building 3D scenes.' : 'Sign in to access your projects.'}
|
{authMode === 'forgot-password' ? 'Enter your email to receive a reset link.' : isRegister ? 'Sign up to start building 3D scenes.' : 'Sign in to access your projects.'}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
@@ -116,6 +119,7 @@ export function AuthModal() {
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{authMode !== 'forgot-password' && (
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400" size={18} />
|
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-zinc-400" size={18} />
|
||||||
<input
|
<input
|
||||||
@@ -128,6 +132,15 @@ export function AuthModal() {
|
|||||||
className="w-full bg-zinc-950/50 border border-zinc-700/50 rounded-xl py-3 pl-10 pr-4 text-white placeholder-zinc-500 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all"
|
className="w-full bg-zinc-950/50 border border-zinc-700/50 rounded-xl py-3 pl-10 pr-4 text-white placeholder-zinc-500 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{authMode === 'login' && (
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<button type="button" onClick={() => openAuthModal('forgot-password')} className="text-xs text-primary hover:underline">
|
||||||
|
Forgot Password?
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
@@ -135,12 +148,14 @@ export function AuthModal() {
|
|||||||
className="w-full bg-primary hover:bg-primary/90 text-white font-bold py-3 rounded-xl mt-2 transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed shadow-[0_0_20px_rgba(var(--primary-rgb),0.3)] hover:shadow-[0_0_30px_rgba(var(--primary-rgb),0.5)]"
|
className="w-full bg-primary hover:bg-primary/90 text-white font-bold py-3 rounded-xl mt-2 transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed shadow-[0_0_20px_rgba(var(--primary-rgb),0.3)] hover:shadow-[0_0_30px_rgba(var(--primary-rgb),0.5)]"
|
||||||
>
|
>
|
||||||
{loading && <Loader2 size={18} className="animate-spin" />}
|
{loading && <Loader2 size={18} className="animate-spin" />}
|
||||||
{isRegister ? 'Sign Up' : 'Sign In'}
|
{authMode === 'forgot-password' ? 'Send Reset Link' : isRegister ? 'Sign Up' : 'Sign In'}
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<div className="mt-8 text-center text-sm text-zinc-400 relative z-10">
|
<div className="mt-8 text-center text-sm text-zinc-400 relative z-10">
|
||||||
{isRegister ? (
|
{authMode === 'forgot-password' ? (
|
||||||
|
<p>Remember your password? <button onClick={() => openAuthModal('login')} className="text-primary hover:underline font-medium">Sign in</button></p>
|
||||||
|
) : isRegister ? (
|
||||||
<p>Already have an account? <button onClick={() => openAuthModal('login')} className="text-primary hover:underline font-medium">Sign in</button></p>
|
<p>Already have an account? <button onClick={() => openAuthModal('login')} className="text-primary hover:underline font-medium">Sign in</button></p>
|
||||||
) : (
|
) : (
|
||||||
<p>Don't have an account? <button onClick={() => openAuthModal('register')} className="text-primary hover:underline font-medium">Sign up</button></p>
|
<p>Don't have an account? <button onClick={() => openAuthModal('register')} className="text-primary hover:underline font-medium">Sign up</button></p>
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||||
|
import { Loader2, CheckCircle, XCircle } from 'lucide-react';
|
||||||
|
import { api } from '../lib/api';
|
||||||
|
|
||||||
|
export default function Activate() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const token = searchParams.get('token');
|
||||||
|
|
||||||
|
const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading');
|
||||||
|
const [message, setMessage] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!token) {
|
||||||
|
setStatus('error');
|
||||||
|
setMessage('Invalid or missing activation token.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const activateAccount = async () => {
|
||||||
|
try {
|
||||||
|
await api.activateUser(token);
|
||||||
|
setStatus('success');
|
||||||
|
setMessage('Your account has been successfully activated!');
|
||||||
|
} catch (error: any) {
|
||||||
|
setStatus('error');
|
||||||
|
setMessage(error.message || 'Failed to activate account.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
activateAccount();
|
||||||
|
}, [token]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center p-4">
|
||||||
|
<div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-8 max-w-md w-full text-center shadow-2xl">
|
||||||
|
{status === 'loading' && (
|
||||||
|
<div className="flex flex-col items-center">
|
||||||
|
<Loader2 className="w-12 h-12 text-primary animate-spin mb-4" />
|
||||||
|
<h2 className="text-xl font-bold text-white mb-2">Activating Account...</h2>
|
||||||
|
<p className="text-zinc-400">Please wait while we verify your token.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'success' && (
|
||||||
|
<div className="flex flex-col items-center">
|
||||||
|
<CheckCircle className="w-12 h-12 text-green-500 mb-4" />
|
||||||
|
<h2 className="text-xl font-bold text-white mb-2">Success!</h2>
|
||||||
|
<p className="text-zinc-400 mb-6">{message}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate('/')}
|
||||||
|
className="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-xl transition-colors"
|
||||||
|
>
|
||||||
|
Go to Login
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{status === 'error' && (
|
||||||
|
<div className="flex flex-col items-center">
|
||||||
|
<XCircle className="w-12 h-12 text-red-500 mb-4" />
|
||||||
|
<h2 className="text-xl font-bold text-white mb-2">Activation Failed</h2>
|
||||||
|
<p className="text-zinc-400 mb-6">{message}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate('/')}
|
||||||
|
className="bg-zinc-800 hover:bg-zinc-700 text-white font-medium py-2 px-6 rounded-xl transition-colors"
|
||||||
|
>
|
||||||
|
Return Home
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+135
-13
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useAuthStore } from '../store/authStore';
|
import { useAuthStore } from '../store/authStore';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { ArrowLeft, ShieldAlert, Loader2, Save } from 'lucide-react';
|
import { ArrowLeft, ShieldAlert, Loader2, Save, Trash2, KeyRound, Plus, X } from 'lucide-react';
|
||||||
import { api } from '../lib/api';
|
import { api } from '../lib/api';
|
||||||
|
|
||||||
interface UserProfile {
|
interface UserProfile {
|
||||||
@@ -18,8 +18,10 @@ export default function Admin() {
|
|||||||
const { profile } = useAuthStore();
|
const { profile } = useAuthStore();
|
||||||
const [users, setUsers] = useState<UserProfile[]>([]);
|
const [users, setUsers] = useState<UserProfile[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [showAddUser, setShowAddUser] = useState(false);
|
||||||
|
const [newEmail, setNewEmail] = useState('');
|
||||||
|
const [newRole, setNewRole] = useState('user');
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const fetchUsers = async () => {
|
const fetchUsers = async () => {
|
||||||
if (profile?.role !== 'admin') return;
|
if (profile?.role !== 'admin') return;
|
||||||
try {
|
try {
|
||||||
@@ -31,6 +33,7 @@ export default function Admin() {
|
|||||||
setLoading(false);
|
setLoading(false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
fetchUsers();
|
fetchUsers();
|
||||||
}, [profile]);
|
}, [profile]);
|
||||||
|
|
||||||
@@ -48,6 +51,41 @@ export default function Admin() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (id: string) => {
|
||||||
|
if (!confirm("Are you sure you want to delete this user? All their projects will be permanently deleted as well.")) return;
|
||||||
|
try {
|
||||||
|
await api.deleteUser(id);
|
||||||
|
setUsers(users.filter(u => u.id !== id));
|
||||||
|
alert("User deleted successfully.");
|
||||||
|
} catch (error: any) {
|
||||||
|
alert("Failed to delete user: " + error.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResetPassword = async (id: string) => {
|
||||||
|
if (!confirm("Send a password reset email to this user?")) return;
|
||||||
|
try {
|
||||||
|
await api.triggerPasswordReset(id);
|
||||||
|
alert("Password reset email sent.");
|
||||||
|
} catch (error: any) {
|
||||||
|
alert("Failed to send reset email: " + error.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddUser = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newEmail) return;
|
||||||
|
try {
|
||||||
|
await api.addUser({ email: newEmail, role: newRole });
|
||||||
|
alert("User created and activation email sent.");
|
||||||
|
setShowAddUser(false);
|
||||||
|
setNewEmail('');
|
||||||
|
fetchUsers();
|
||||||
|
} catch (error: any) {
|
||||||
|
alert("Failed to create user: " + error.message);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (profile?.role !== 'admin') {
|
if (profile?.role !== 'admin') {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center text-white">
|
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center text-white">
|
||||||
@@ -62,8 +100,8 @@ export default function Admin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-zinc-950 text-white p-8">
|
<div className="min-h-screen bg-zinc-950 text-white p-8 relative">
|
||||||
<div className="max-w-6xl mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
<button
|
<button
|
||||||
onClick={() => navigate('/dashboard')}
|
onClick={() => navigate('/dashboard')}
|
||||||
className="flex items-center gap-2 text-zinc-400 hover:text-white mb-8 transition-colors"
|
className="flex items-center gap-2 text-zinc-400 hover:text-white mb-8 transition-colors"
|
||||||
@@ -71,11 +109,19 @@ export default function Admin() {
|
|||||||
<ArrowLeft size={16} /> Back to Dashboard
|
<ArrowLeft size={16} /> Back to Dashboard
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<h1 className="text-3xl font-bold mb-8">Admin Control Panel</h1>
|
<div className="flex items-center justify-between mb-8">
|
||||||
|
<h1 className="text-3xl font-bold">Admin Control Panel</h1>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAddUser(true)}
|
||||||
|
className="flex items-center gap-2 bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-xl transition-colors font-medium"
|
||||||
|
>
|
||||||
|
<Plus size={16} /> Add User
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
|
<div className="bg-zinc-900 border border-zinc-800 rounded-2xl overflow-hidden">
|
||||||
<div className="p-6 border-b border-zinc-800 flex justify-between items-center">
|
<div className="p-6 border-b border-zinc-800 flex justify-between items-center">
|
||||||
<h2 className="text-xl font-semibold">User Limit Management</h2>
|
<h2 className="text-xl font-semibold">User Management</h2>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
@@ -96,7 +142,13 @@ export default function Admin() {
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody className="divide-y divide-zinc-800">
|
<tbody className="divide-y divide-zinc-800">
|
||||||
{users.map(u => (
|
{users.map(u => (
|
||||||
<UserRow key={u.id} user={u} onUpdate={updateLimits} />
|
<UserRow
|
||||||
|
key={u.id}
|
||||||
|
user={u}
|
||||||
|
onUpdate={updateLimits}
|
||||||
|
onDelete={handleDelete}
|
||||||
|
onResetPassword={handleResetPassword}
|
||||||
|
/>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -104,11 +156,64 @@ export default function Admin() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{showAddUser && (
|
||||||
|
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
|
||||||
|
<div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-6 w-full max-w-md shadow-2xl">
|
||||||
|
<div className="flex justify-between items-center mb-6">
|
||||||
|
<h3 className="text-xl font-bold">Add New User</h3>
|
||||||
|
<button onClick={() => setShowAddUser(false)} className="p-2 text-zinc-500 hover:text-white rounded-lg transition-colors">
|
||||||
|
<X size={20} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form onSubmit={handleAddUser} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-zinc-400 mb-1">Email Address</label>
|
||||||
|
<input
|
||||||
|
type="email"
|
||||||
|
value={newEmail}
|
||||||
|
onChange={e => setNewEmail(e.target.value)}
|
||||||
|
className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-primary transition-colors"
|
||||||
|
placeholder="user@example.com"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-zinc-400 mb-1">Role</label>
|
||||||
|
<select
|
||||||
|
value={newRole}
|
||||||
|
onChange={e => setNewRole(e.target.value)}
|
||||||
|
className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-primary transition-colors"
|
||||||
|
>
|
||||||
|
<option value="user">User</option>
|
||||||
|
<option value="admin">Admin</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 rounded-xl transition-colors mt-2"
|
||||||
|
>
|
||||||
|
Send Activation Email
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const UserRow = ({ user, onUpdate }: { user: UserProfile, onUpdate: (u: UserProfile) => void }) => {
|
const UserRow = ({
|
||||||
|
user,
|
||||||
|
onUpdate,
|
||||||
|
onDelete,
|
||||||
|
onResetPassword
|
||||||
|
}: {
|
||||||
|
user: UserProfile,
|
||||||
|
onUpdate: (u: UserProfile) => void,
|
||||||
|
onDelete: (id: string) => void,
|
||||||
|
onResetPassword: (id: string) => void
|
||||||
|
}) => {
|
||||||
const [role, setRole] = useState(user.role);
|
const [role, setRole] = useState(user.role);
|
||||||
const [isActive, setIsActive] = useState(user.is_active);
|
const [isActive, setIsActive] = useState(user.is_active);
|
||||||
const [credits, setCredits] = useState(user.api_credits);
|
const [credits, setCredits] = useState(user.api_credits);
|
||||||
@@ -153,7 +258,7 @@ const UserRow = ({ user, onUpdate }: { user: UserProfile, onUpdate: (u: UserProf
|
|||||||
type="number"
|
type="number"
|
||||||
value={credits}
|
value={credits}
|
||||||
onChange={e => setCredits(Number(e.target.value))}
|
onChange={e => setCredits(Number(e.target.value))}
|
||||||
className="w-24 bg-zinc-950 border border-zinc-700 rounded px-2 py-1 text-white focus:outline-none focus:border-primary"
|
className="w-20 bg-zinc-950 border border-zinc-700 rounded px-2 py-1 text-white focus:outline-none focus:border-primary"
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td className="p-4">
|
<td className="p-4">
|
||||||
@@ -161,16 +266,33 @@ const UserRow = ({ user, onUpdate }: { user: UserProfile, onUpdate: (u: UserProf
|
|||||||
type="number"
|
type="number"
|
||||||
value={storage}
|
value={storage}
|
||||||
onChange={e => setStorage(Number(e.target.value))}
|
onChange={e => setStorage(Number(e.target.value))}
|
||||||
className="w-24 bg-zinc-950 border border-zinc-700 rounded px-2 py-1 text-white focus:outline-none focus:border-primary"
|
className="w-20 bg-zinc-950 border border-zinc-700 rounded px-2 py-1 text-white focus:outline-none focus:border-primary"
|
||||||
/>
|
/>
|
||||||
</td>
|
</td>
|
||||||
<td className="p-4 text-right">
|
<td className="p-4">
|
||||||
|
<div className="flex items-center justify-end gap-2">
|
||||||
<button
|
<button
|
||||||
onClick={handleUpdate}
|
onClick={handleUpdate}
|
||||||
className="bg-zinc-800 hover:bg-zinc-700 text-white px-3 py-1.5 rounded flex items-center justify-center gap-2 ml-auto transition-colors"
|
title="Save Changes"
|
||||||
|
className="p-1.5 text-zinc-400 hover:text-white bg-zinc-800 hover:bg-zinc-700 rounded transition-colors"
|
||||||
>
|
>
|
||||||
<Save size={14} /> Save
|
<Save size={16} />
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => onResetPassword(user.id)}
|
||||||
|
title="Send Password Reset"
|
||||||
|
className="p-1.5 text-amber-500/70 hover:text-amber-400 bg-amber-500/10 hover:bg-amber-500/20 rounded transition-colors"
|
||||||
|
>
|
||||||
|
<KeyRound size={16} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => onDelete(user.id)}
|
||||||
|
title="Delete User"
|
||||||
|
className="p-1.5 text-red-500/70 hover:text-red-400 bg-red-500/10 hover:bg-red-500/20 rounded transition-colors"
|
||||||
|
>
|
||||||
|
<Trash2 size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import { useState } from 'react';
|
||||||
|
import { useSearchParams, useNavigate } from 'react-router-dom';
|
||||||
|
import { Loader2, KeyRound } from 'lucide-react';
|
||||||
|
import { api } from '../lib/api';
|
||||||
|
|
||||||
|
export default function ResetPassword() {
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const token = searchParams.get('token');
|
||||||
|
|
||||||
|
const [password, setPassword] = useState('');
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [message, setMessage] = useState('');
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [success, setSuccess] = useState(false);
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center p-4">
|
||||||
|
<div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-8 max-w-md w-full text-center shadow-2xl text-white">
|
||||||
|
<h2 className="text-xl font-bold text-red-500 mb-2">Invalid Link</h2>
|
||||||
|
<p className="text-zinc-400 mb-6">The password reset token is missing or invalid.</p>
|
||||||
|
<button onClick={() => navigate('/')} className="bg-zinc-800 hover:bg-zinc-700 text-white font-medium py-2 px-6 rounded-xl transition-colors">
|
||||||
|
Return Home
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleReset = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (password !== confirmPassword) {
|
||||||
|
setError('Passwords do not match.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (password.length < 6) {
|
||||||
|
setError('Password must be at least 6 characters.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
setError('');
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api.resetPassword(token, password);
|
||||||
|
setSuccess(true);
|
||||||
|
setMessage('Your password has been reset successfully!');
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(err.message || 'Failed to reset password.');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-zinc-950 flex flex-col items-center justify-center p-4">
|
||||||
|
<div className="bg-zinc-900 border border-zinc-800 rounded-2xl p-8 max-w-md w-full shadow-2xl">
|
||||||
|
<div className="flex justify-center mb-6">
|
||||||
|
<div className="w-12 h-12 bg-primary/20 rounded-full flex items-center justify-center text-primary">
|
||||||
|
<KeyRound size={24} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2 className="text-2xl font-bold text-white text-center mb-2">Reset Password</h2>
|
||||||
|
|
||||||
|
{success ? (
|
||||||
|
<div className="text-center">
|
||||||
|
<p className="text-green-400 mb-6">{message}</p>
|
||||||
|
<button
|
||||||
|
onClick={() => navigate('/')}
|
||||||
|
className="bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-xl transition-colors w-full"
|
||||||
|
>
|
||||||
|
Go to Login
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<form onSubmit={handleReset} className="space-y-4">
|
||||||
|
<p className="text-zinc-400 text-sm text-center mb-6">Enter your new password below.</p>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="bg-red-500/10 border border-red-500/20 text-red-400 text-sm p-3 rounded-lg">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-zinc-400 mb-1">New Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={e => setPassword(e.target.value)}
|
||||||
|
className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-primary transition-colors"
|
||||||
|
placeholder="••••••••"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-zinc-400 mb-1">Confirm New Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={e => setConfirmPassword(e.target.value)}
|
||||||
|
className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-4 py-3 text-white focus:outline-none focus:border-primary transition-colors"
|
||||||
|
placeholder="••••••••"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 rounded-xl transition-colors flex items-center justify-center disabled:opacity-50 mt-2"
|
||||||
|
>
|
||||||
|
{loading ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Reset Password'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -18,9 +18,9 @@ interface AuthState {
|
|||||||
signOut: () => void;
|
signOut: () => void;
|
||||||
setProfile: (profile: UserProfile) => void;
|
setProfile: (profile: UserProfile) => void;
|
||||||
isAuthModalOpen: boolean;
|
isAuthModalOpen: boolean;
|
||||||
openAuthModal: (mode?: 'login' | 'register') => void;
|
openAuthModal: (mode?: 'login' | 'register' | 'forgot-password') => void;
|
||||||
closeAuthModal: () => void;
|
closeAuthModal: () => void;
|
||||||
authMode: 'login' | 'register';
|
authMode: 'login' | 'register' | 'forgot-password';
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useAuthStore = create<AuthState>((set) => ({
|
export const useAuthStore = create<AuthState>((set) => ({
|
||||||
|
|||||||
Reference in New Issue
Block a user