import { randomInt, randomUUID } from "node:crypto"; import type { Config } from "../config/appConfig.js"; import type { Db } from "../config/db.js"; import { AppError } from "../utils/errors.js"; import { hashPassword } from "./authService.js"; import { branding, getMailer, link, renderMail } from "./mailService.js"; import { diskUsage } from "./storageService.js"; export interface AdminUserRow { id: string; email: string; first_name: string; last_name: string; role_slug: string; quota_bytes: number; used_bytes: number; max_file_bytes: number; is_active: number; must_change_password: number; last_login_at: string | null; created_at: string; } export const publicUser = (row: AdminUserRow) => ({ id: row.id, email: row.email, first_name: row.first_name, last_name: row.last_name, role_slug: row.role_slug, quota_bytes: row.quota_bytes, used_bytes: row.used_bytes, max_file_bytes: row.max_file_bytes, is_active: row.is_active === 1, must_change_password: row.must_change_password === 1, last_login_at: row.last_login_at, created_at: row.created_at, }); const SELECT_USER = ` SELECT u.id, u.email, u.first_name, u.last_name, r.slug AS role_slug, u.quota_bytes, u.used_bytes, u.max_file_bytes, u.is_active, u.must_change_password, u.last_login_at, u.created_at FROM users u JOIN roles r ON r.id = u.role_id`; const UNITS = ["o", "Ko", "Mo", "Go", "To", "Po"]; const humanBytes = (bytes: number): string => { let value = bytes; let unit = 0; while (value >= 1024 && unit < UNITS.length - 1) { value /= 1024; unit += 1; } return `${value.toFixed(unit === 0 || value >= 10 ? 0 : 1)} ${UNITS[unit]}`; }; const generatePasswordValue = (): string => { const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; let out = ""; for (let index = 0; index < 18; index += 1) out += alphabet[randomInt(alphabet.length)]; return out; }; /** Reaffecte ou supprime les dossiers d'un compte supprime. */ const rehomeUserFolders = async ( db: Db, userId: string, ): Promise<{ kept: number; deleted: number }> => { const folders = await db.query<{ id: string; parent_id: string | null }>( "SELECT id, parent_id FROM folders WHERE owner_id = ? AND deleted_at IS NULL AND is_system = 0", [userId], ); if (folders.length === 0) return { kept: 0, deleted: 0 }; const ids = folders.map((folder) => folder.id); const placeholders = ids.map(() => "?").join(","); const candidates = await db.query<{ folder_id: string; user_id: string; level: string; created_at: string; }>( `SELECT fp.folder_id, fp.user_id, fp.level, fp.created_at FROM folder_permissions fp JOIN users u ON u.id = fp.user_id AND u.deleted_at IS NULL AND u.is_active = 1 WHERE fp.folder_id IN (${placeholders}) AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ORDER BY FIELD(fp.level, 'admin', 'write', 'read'), fp.created_at ASC`, [...ids], ); const newOwner = new Map(); for (const row of candidates) { if (!newOwner.has(row.folder_id)) newOwner.set(row.folder_id, row.user_id); } const owned = new Map(folders.map((folder) => [folder.id, folder.parent_id])); const keepIds = [...newOwner.keys()]; const deleteIds = ids.filter((id) => !newOwner.has(id)); await db.transaction(async (connection) => { for (const [id, owner] of newOwner) { const parentId = owned.get(id) ?? null; const parentGone = parentId !== null && owned.has(parentId) && !newOwner.has(parentId); await connection.execute( "UPDATE folders SET owner_id = ?, parent_id = ? WHERE id = ?", [owner, parentGone ? null : parentId, id], ); } if (deleteIds.length > 0) { const delPh = deleteIds.map(() => "?").join(","); await connection.execute( `UPDATE folders SET parent_id = NULL WHERE parent_id IN (${delPh}) AND deleted_at IS NULL AND owner_id <> ? AND id NOT IN (${keepIds.map(() => "?").join(",") || "''"})`, [...deleteIds, userId, ...(keepIds.length > 0 ? keepIds : [])], ); await connection.execute( `UPDATE folders SET deleted_at = UTC_TIMESTAMP() WHERE id IN (${delPh}) AND deleted_at IS NULL`, deleteIds, ); await connection.execute( `UPDATE files SET deleted_at = UTC_TIMESTAMP() WHERE folder_id IN (${delPh}) AND deleted_at IS NULL`, deleteIds, ); } await connection.execute("DELETE FROM folder_permissions WHERE user_id = ?", [userId]); await connection.execute("DELETE FROM user_file_stars WHERE user_id = ?", [userId]); }); return { kept: keepIds.length, deleted: deleteIds.length }; }; const assertQuotaFits = async (config: Config, quota: number): Promise => { const disk = await diskUsage(config.MEDIA_DIR); if (disk !== null && quota > disk.total_bytes) { throw AppError.badRequest( `Le quota depasse la capacite du disque (${humanBytes(disk.total_bytes)}).`, ); } }; export const getStats = async (db: Db, config: Config) => { const [users] = await db.query<{ count: number }>( "SELECT COUNT(*) AS count FROM users WHERE deleted_at IS NULL", ); const [folders] = await db.query<{ count: number }>( "SELECT COUNT(*) AS count FROM folders WHERE deleted_at IS NULL", ); const [files] = await db.query<{ count: number; bytes: number }>( "SELECT COUNT(*) AS count, COALESCE(SUM(size_bytes), 0) AS bytes FROM files WHERE deleted_at IS NULL", ); const [trash] = await db.query<{ count: number }>( "SELECT COUNT(*) AS count FROM files WHERE deleted_at IS NOT NULL", ); const locations = await db.query<{ id: number; name: string; used_bytes: number; quota_bytes: number | null; }>( `SELECT id, name, used_bytes, quota_bytes FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`, ); return { users: users?.count ?? 0, folders: folders?.count ?? 0, files: files?.count ?? 0, usedBytes: Number(files?.bytes ?? 0), trashFiles: trash?.count ?? 0, locations, disk: await diskUsage(config.MEDIA_DIR), }; }; export const listUsers = async (db: Db, q: string): Promise => { const query = q.trim(); if (query) { return db.query( `${SELECT_USER} WHERE u.deleted_at IS NULL AND (u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?) ORDER BY u.email LIMIT 500`, [`%${query}%`, `%${query}%`, `%${query}%`], ); } return db.query( `${SELECT_USER} WHERE u.deleted_at IS NULL ORDER BY u.email LIMIT 500`, ); }; export interface CreateUserInput { email: string; first_name: string; last_name: string; role_slug: string; quota_bytes?: number | null | undefined; max_file_bytes?: number | null | undefined; password?: string | null | undefined; } export const createUser = async ( db: Db, config: Config, data: CreateUserInput, ): Promise => { const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]); if (!role) throw AppError.badRequest("Role inconnu."); const existing = await db.one("SELECT id FROM users WHERE active_email = ?", [data.email]); if (existing) throw AppError.conflict("Ce compte existe deja."); const password = data.password ?? generatePasswordValue(); const hash = await hashPassword(password); const id = randomUUID(); await db.exec( `INSERT INTO users (id, email, first_name, last_name, password_hash, role_id, quota_bytes, max_file_bytes, must_change_password, password_changed_at) VALUES (?, ?, ?, ?, ?, ?, COALESCE(?, (SELECT CAST(setting_value AS UNSIGNED) FROM settings WHERE setting_key = 'default_quota_bytes'), 429496729600), COALESCE(?, 5368709120), 1, NULL)`, [id, data.email, data.first_name, data.last_name, hash, role.id, data.quota_bytes ?? null, data.max_file_bytes ?? null], ); const created = await db.required(`${SELECT_USER} WHERE u.id = ?`, [id]); const mail = renderMail(branding(config), { preview: "Votre acces CoHaiSe Cloud est pret.", heading: "Votre compte a ete cree", intro: `Un compte CoHaiSe Cloud vient d'etre ouvert pour ${data.first_name}. Connectez-vous avec les identifiants ci-dessous.`, credentials: { email: data.email, password }, cta: { label: "Se connecter", url: link(config, "/login") }, note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.", }); await getMailer(config) .send({ to: data.email, subject: "CoHaiSe Cloud — votre compte est pret", text: mail.text, html: mail.html, }) .catch(() => undefined); return created; }; export interface UpdateUserInput { first_name?: string | undefined; last_name?: string | undefined; role_slug?: string | undefined; quota_bytes?: number | undefined; max_file_bytes?: number | undefined; is_active?: boolean | undefined; } export const updateUser = async ( db: Db, actorId: string, id: string, data: UpdateUserInput, ): Promise => { const existing = await db.one( `${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [id], ); if (!existing) throw AppError.notFound("Compte introuvable."); if (data.role_slug !== undefined && data.role_slug !== existing.role_slug) { const role = await db.one<{ id: number }>("SELECT id FROM roles WHERE slug = ?", [data.role_slug]); if (!role) throw AppError.badRequest("Role inconnu."); if (id === actorId) throw AppError.badRequest("Vous ne pouvez pas modifier votre propre role."); if (existing.role_slug === "admin") { const [count] = await db.query<{ count: number }>( `SELECT COUNT(*) AS count FROM users u JOIN roles r ON r.id = u.role_id WHERE r.slug = 'admin' AND u.is_active = 1 AND u.deleted_at IS NULL`, ); if ((count?.count ?? 0) <= 1) { throw AppError.badRequest("Impossible de retirer le dernier administrateur."); } } await db.exec("UPDATE users SET role_id = ? WHERE id = ?", [role.id, id]); } if (data.first_name !== undefined) { await db.exec("UPDATE users SET first_name = ? WHERE id = ?", [data.first_name, id]); } if (data.last_name !== undefined) { await db.exec("UPDATE users SET last_name = ? WHERE id = ?", [data.last_name, id]); } if (data.quota_bytes !== undefined) { if (data.quota_bytes < existing.used_bytes) { throw AppError.badRequest("Le quota ne peut pas etre inferieur a l'espace deja utilise."); } await db.exec("UPDATE users SET quota_bytes = ? WHERE id = ?", [data.quota_bytes, id]); } if (data.max_file_bytes !== undefined) { await db.exec("UPDATE users SET max_file_bytes = ? WHERE id = ?", [data.max_file_bytes, id]); } if (data.is_active !== undefined) { if (!data.is_active && id === actorId) { throw AppError.badRequest("Vous ne pouvez pas desactiver votre propre compte."); } await db.exec("UPDATE users SET is_active = ? WHERE id = ?", [data.is_active ? 1 : 0, id]); if (!data.is_active) { await db.exec( "UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL", [id], ); } } return db.required(`${SELECT_USER} WHERE u.id = ?`, [id]); }; /** Supprime (logiquement) un compte et reattribue ses dossiers. */ export const deleteUser = async ( db: Db, actorId: string, id: string, ): Promise<{ kept: number; deleted: number }> => { const result = await db.exec( "UPDATE users SET deleted_at = UTC_TIMESTAMP(), is_active = 0 WHERE id = ? AND deleted_at IS NULL", [id], ); if (result.affectedRows === 0) throw AppError.notFound("Compte introuvable."); if (id === actorId) throw AppError.badRequest("Vous ne pouvez pas supprimer votre propre compte."); const rehomed = await rehomeUserFolders(db, id); await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ?", [id]); return rehomed; }; /** Reinitialise le mot de passe d'un compte et envoie les identifiants. */ export const resetUserPassword = async (db: Db, config: Config, id: string): Promise => { const user = await db.one<{ email: string }>( "SELECT email FROM users WHERE id = ? AND deleted_at IS NULL", [id], ); if (!user) throw AppError.notFound("Compte introuvable."); const password = generatePasswordValue(); const hash = await hashPassword(password); await db.exec( "UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = NULL WHERE id = ?", [hash, id], ); await db.exec( "UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE user_id = ? AND revoked_at IS NULL", [id], ); const mail = renderMail(branding(config), { preview: "Un nouveau mot de passe a ete genere pour votre compte.", heading: "Mot de passe reinitialise", intro: "Un administrateur a reinitialise le mot de passe de votre compte CoHaiSe Cloud.", credentials: { email: user.email, password }, cta: { label: "Se connecter", url: link(config, "/login") }, note: "Ce mot de passe est temporaire : il vous sera demande de le changer des la premiere connexion.", }); await getMailer(config) .send({ to: user.email, subject: "CoHaiSe Cloud — mot de passe reinitialise", text: mail.text, html: mail.html, }) .catch(() => undefined); }; export interface StorageLocationRow { id: number; name: string; slug: string; mount_path: string; quota_bytes: number | null; used_bytes: number; is_active: number; created_at: string; } export const listStorageLocations = async (db: Db, config: Config) => ({ locations: await db.query( `SELECT id, name, slug, mount_path, quota_bytes, used_bytes, is_active, created_at FROM storage_locations WHERE deleted_at IS NULL ORDER BY id`, ), disk: await diskUsage(config.MEDIA_DIR), }); export const createStorageLocation = async ( db: Db, config: Config, data: { name: string; slug: string; mount_path: string; quota_bytes?: number | null | undefined }, ): Promise => { if (data.quota_bytes !== undefined && data.quota_bytes !== null) { await assertQuotaFits(config, data.quota_bytes); } try { await db.exec( `INSERT INTO storage_locations (name, slug, mount_path, quota_bytes) VALUES (?, ?, ?, ?)`, [data.name, data.slug, data.mount_path, data.quota_bytes ?? null], ); } catch (error) { if ((error as { errno?: number }).errno === 1062) { throw AppError.conflict("Un emplacement porte deja ce nom ou ce chemin."); } throw error; } }; export const updateStorageLocation = async ( db: Db, config: Config, id: number, data: { name?: string | undefined; quota_bytes?: number | null | undefined; is_active?: boolean | undefined }, ): Promise => { const row = await db.one<{ used_bytes: number }>( "SELECT used_bytes FROM storage_locations WHERE id = ? AND deleted_at IS NULL", [id], ); if (!row) throw AppError.notFound("Emplacement introuvable."); if (data.quota_bytes !== undefined && data.quota_bytes !== null && data.quota_bytes < row.used_bytes) { throw AppError.badRequest("Le quota est inferieur a l'espace deja utilise."); } if (data.quota_bytes !== undefined && data.quota_bytes !== null) { await assertQuotaFits(config, data.quota_bytes); } const fields: string[] = []; const values: unknown[] = []; if (data.name !== undefined) { fields.push("name = ?"); values.push(data.name); } if (data.quota_bytes !== undefined) { fields.push("quota_bytes = ?"); values.push(data.quota_bytes); } if (data.is_active !== undefined) { fields.push("is_active = ?"); values.push(data.is_active ? 1 : 0); } if (fields.length === 0) throw AppError.badRequest("Rien a modifier."); values.push(id); await db.exec(`UPDATE storage_locations SET ${fields.join(", ")} WHERE id = ?`, values); }; export const auditFilters = async (db: Db) => { const actions = await db.query<{ action: string }>( "SELECT DISTINCT action FROM audit_logs ORDER BY action ASC", ); const users = await db.query<{ user_id: string; user_email: string | null }>( `SELECT user_id, MAX(user_email) AS user_email FROM audit_logs WHERE user_id IS NOT NULL GROUP BY user_id ORDER BY user_email ASC`, ); return { actions: actions.map((row) => row.action), users: users.map((row) => ({ id: row.user_id, email: row.user_email })), }; }; export const auditEntries = async ( db: Db, options: { limit: number; offset: number; action?: string | null; userId?: string | null }, ) => { const conditions: string[] = []; const params: unknown[] = []; if (options.action) { conditions.push("action = ?"); params.push(options.action); } if (options.userId) { conditions.push("user_id = ?"); params.push(options.userId); } const where = conditions.length > 0 ? ` WHERE ${conditions.join(" AND ")}` : ""; return db.query( `SELECT id, user_id, user_email, action, resource, resource_id, details, ip_address, created_at FROM audit_logs${where} ORDER BY created_at DESC LIMIT ${options.limit} OFFSET ${options.offset}`, params, ); };