Spaces:
Build error
Build error
File size: 8,112 Bytes
ef73937 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | import type { FastifyInstance } from 'fastify';
import { userRepository } from '@core/storage/repositories/users.js';
import { channelRepository } from '@core/storage/repositories/channels.js';
import { logRepository } from '@core/storage/repositories/logs.js';
import { validateInput, profileUpdateSchema } from '@core/security/validation.js';
import { requireAuth, checkBanned } from '@core/auth/middleware.js';
import { hashPassword, verifyPassword } from '@core/auth/password.js';
import { destroyAllUserSessions, createUserSession } from '@core/auth/session.js';
import { config } from '@config/index.js';
import { getClientIP } from '@core/security/vpnDetect.js';
import { formatNumber, formatRelativeTime } from '@core/utils/helpers.js';
export async function userRoutes(app: FastifyInstance) {
// User dashboard
app.get('/user', { preHandler: [requireAuth, checkBanned] }, async (request, reply) => {
const user = await userRepository.findById(request.user!.id);
if (!user) {
return reply.status(404).view('pages/404.njk', { user: request.user });
}
const channels = await channelRepository.findByOwner(user.id, { limit: 10 });
return reply.view('pages/user/dashboard.njk', {
csrfToken: request.csrfToken(),
user: request.user,
profile: {
...user,
formattedChannels: formatNumber(user.channelCount),
memberSince: formatRelativeTime(user.createdAt),
lastLogin: user.lastLoginAt ? formatRelativeTime(user.lastLoginAt) : 'Jamais',
},
channels: channels.map(c => ({
...c,
formattedFollowers: formatNumber(c.followerCount),
formattedVotes: formatNumber(c.voteCount),
relativeTime: formatRelativeTime(c.createdAt),
statusLabel: getStatusLabel(c.status),
})),
maxChannels: config.maxChannelsPerUser || 10,
});
});
// Profile settings page
app.get('/user/profile', { preHandler: [requireAuth, checkBanned] }, async (request, reply) => {
return reply.view('pages/user/profile.njk', {
csrfToken: request.csrfToken(),
user: request.user,
});
});
// Update profile
app.post('/user/profile', { preHandler: [requireAuth, checkBanned] }, async (request, reply) => {
const validation = validateInput(profileUpdateSchema, request.body);
if (!validation.success) {
return reply.status(400).view('pages/user/profile.njk', {
csrfToken: request.csrfToken(),
user: request.user,
errors: validation.errors.map(e => e.message),
formData: request.body,
});
}
const { email, currentPassword, newPassword } = validation.data;
const user = await userRepository.findById(request.user!.id);
if (!user) {
return reply.status(404).send({ error: 'User not found' });
}
const updates: Record<string, unknown> = {};
if (email !== undefined) {
updates.email = email || null;
}
if (newPassword) {
if (!currentPassword) {
return reply.status(400).view('pages/user/profile.njk', {
csrfToken: request.csrfToken(),
user: request.user,
errors: ['Mot de passe actuel requis'],
formData: request.body,
});
}
const validPassword = await verifyPassword(user.passwordHash, currentPassword);
if (!validPassword) {
return reply.status(400).view('pages/user/profile.njk', {
csrfToken: request.csrfToken(),
user: request.user,
errors: ['Mot de passe actuel incorrect'],
formData: request.body,
});
}
updates.passwordHash = await hashPassword(newPassword);
// Invalidate all other sessions
await destroyAllUserSessions(user.id);
const newSessionId = await createUserSession(user.id);
reply.setCookie('session_id', newSessionId, {
httpOnly: true,
secure: config.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: config.sessionTtlMs / 1000,
path: '/',
});
}
if (Object.keys(updates).length > 0) {
await userRepository.update(user.id, updates);
await logRepository.log({
level: 'info',
message: 'Profile updated',
context: { fields: Object.keys(updates) },
userId: user.id,
ip: getClientIP(request),
userAgent: request.headers['user-agent'],
url: request.url,
method: request.method,
});
}
return reply.view('pages/user/profile.njk', {
csrfToken: request.csrfToken(),
user: request.user,
success: 'Profil mis à jour avec succès',
});
});
// Channel stats for user
app.get('/user/stats', { preHandler: [requireAuth, checkBanned] }, async (request, reply) => {
const channels = await channelRepository.findByOwner(request.user!.id, { limit: 1000 });
const stats = {
totalChannels: channels.length,
publishedChannels: channels.filter(c => c.status === 'published' && !c.isBanned).length,
pendingChannels: channels.filter(c => c.status === 'pending' || c.status === 'scraping' || c.status === 'validating').length,
rejectedChannels: channels.filter(c => c.status === 'rejected').length,
bannedChannels: channels.filter(c => c.isBanned).length,
totalFollowers: channels.reduce((sum, c) => sum + c.followerCount, 0),
totalVotes: channels.reduce((sum, c) => sum + c.voteCount, 0),
totalViews: channels.reduce((sum, c) => sum + c.viewCount, 0),
topChannel: channels.reduce((max, c) => c.followerCount > (max?.followerCount || 0) ? c : max, null as any),
};
return reply.view('pages/user/stats.njk', {
csrfToken: request.csrfToken(),
user: request.user,
stats: {
...stats,
formattedFollowers: formatNumber(stats.totalFollowers),
formattedVotes: formatNumber(stats.totalVotes),
formattedViews: formatNumber(stats.totalViews),
},
channels: channels.slice(0, 10).map(c => ({
...c,
formattedFollowers: formatNumber(c.followerCount),
formattedVotes: formatNumber(c.voteCount),
})),
});
});
// Delete account
app.post('/user/delete-account', { preHandler: [requireAuth, checkBanned] }, async (request, reply) => {
const { password } = request.body as { password?: string };
const user = await userRepository.findById(request.user!.id);
if (!user) {
return reply.status(404).send({ error: 'User not found' });
}
if (!password) {
return reply.status(400).send({ error: 'Mot de passe requis pour supprimer le compte' });
}
const validPassword = await verifyPassword(user.passwordHash, password);
if (!validPassword) {
return reply.status(400).send({ error: 'Mot de passe incorrect' });
}
// Delete user's channels
const channels = await channelRepository.findByOwner(user.id, { limit: 1000 });
for (const channel of channels) {
await channelRepository.delete(channel.id);
}
// Delete user
await userRepository.delete(user.id);
await destroyAllUserSessions(user.id);
await logRepository.log({
level: 'warn',
message: 'Account deleted by user',
context: { username: user.username },
userId: user.id,
ip: getClientIP(request),
userAgent: request.headers['user-agent'],
url: request.url,
method: request.method,
});
reply.clearCookie('session_id', { path: '/' });
return reply.redirect('/auth/login?deleted=1');
});
}
function getStatusLabel(status: string): { label: string; class: string } {
const labels: Record<string, { label: string; class: string }> = {
pending: { label: 'En attente', class: 'badge-warning' },
scraping: { label: 'Scraping', class: 'badge-info' },
validating: { label: 'Vérification', class: 'badge-info' },
published: { label: 'Publié', class: 'badge-success' },
rejected: { label: 'Rejeté', class: 'badge-danger' },
banned: { label: 'Banni', class: 'badge-dark' },
};
return labels[status] || { label: status, class: 'badge-secondary' };
} |