feat(chat,files): salon par dossier, favoris, cloisonnement des droits admin (#8)
CD — Déploiement / deploy (push) Successful in 19s
CD — Déploiement / deploy (push) Successful in 19s
- chat: salon attache a un dossier, membres = comptes ayant acces au dossier - securite: suppression du passage automatique admin sur fichiers/dossiers/ corbeille/recherche/galerie/chat ; l'admin n'accede qu'a ses partages - favoris: tri en tete dans l'explorateur + page dediee (GET /favorites) - ui: retrait des pastilles Systeme/Public sur la carte dossier - migration 007_chat : table chat_messages --------- Co-authored-by: xEsiah <[email protected]> Reviewed-on: #8 Reviewed-by: Esiah <[email protected]> Co-authored-by: Gitea Actions <-[email protected]>
This commit was merged in pull request #8.
This commit is contained in:
@@ -0,0 +1,214 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
AppError,
|
||||
createRateLimiter,
|
||||
currentUser,
|
||||
requireAuth,
|
||||
type App,
|
||||
type Config,
|
||||
type Db,
|
||||
} from "../lib/index.js";
|
||||
import { audit, canManageFolder, canRead } from "../access.js";
|
||||
|
||||
/**
|
||||
* Chat attache a un dossier. Le salon ne se lit et ne s'ecrit qu'avec l'acces
|
||||
* au dossier : le role global ne suffit jamais, `admin` compris.
|
||||
*
|
||||
* Les membres du salon sont exactement les comptes qui ont acces au dossier
|
||||
* (proprietaire, permissions nominatives, dossier public). Un administrateur
|
||||
* n'est donc membre que des salons des dossiers partages avec lui.
|
||||
*/
|
||||
|
||||
const uuid = z
|
||||
.string()
|
||||
.regex(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
||||
"Identifiant invalide.",
|
||||
);
|
||||
|
||||
const sendInput = z.object({
|
||||
body: z.string().trim().min(1, "Message vide.").max(2000, "Message trop long."),
|
||||
});
|
||||
|
||||
interface MessageRow {
|
||||
id: number;
|
||||
user_id: string | null;
|
||||
body: string;
|
||||
created_at: string;
|
||||
first_name: string | null;
|
||||
last_name: string | null;
|
||||
avatar_updated_at: Date | null;
|
||||
}
|
||||
|
||||
/** Auteur joint a la ligne : meme jointure que la lecture, pour la reponse du POST. */
|
||||
const SELECT_MESSAGE = `
|
||||
SELECT m.id, m.user_id, m.body, m.created_at,
|
||||
u.first_name, u.last_name, ua.updated_at AS avatar_updated_at
|
||||
FROM chat_messages m
|
||||
LEFT JOIN users u ON u.id = m.user_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = m.user_id`;
|
||||
|
||||
const publicMessage = (row: MessageRow) => ({
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
body: row.body,
|
||||
created_at: row.created_at,
|
||||
has_avatar: row.user_id !== null && row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
});
|
||||
|
||||
export const registerChatRoutes = (app: App, db: Db, config: Config): void => {
|
||||
// Ecriture bornee par compte : le salon reste utilisable meme si un client
|
||||
// s'emballe. La lecture (interrogation periodique) n'est pas limitee ici.
|
||||
const limiter = createRateLimiter(20, 10_000);
|
||||
|
||||
/**
|
||||
* Le dossier doit exister et etre accessible : `canRead` rejette une session
|
||||
* sans acces comme un dossier inexistant (404, pour ne rien confirmer).
|
||||
*/
|
||||
const assertFolder = async (
|
||||
folderId: string,
|
||||
): Promise<{ id: string; owner_id: string | null; access_type: string }> => {
|
||||
if (!uuid.safeParse(folderId).success) throw AppError.notFound("Dossier introuvable.");
|
||||
const folder = await db.one<{ id: string; owner_id: string | null; access_type: string }>(
|
||||
"SELECT id, owner_id, access_type FROM folders WHERE id = ? AND deleted_at IS NULL",
|
||||
[folderId],
|
||||
);
|
||||
if (!folder) throw AppError.notFound("Dossier introuvable.");
|
||||
return folder;
|
||||
};
|
||||
|
||||
app.get("/api/cloud/folders/:folderId/chat/members", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const folder = await assertFolder(folderId);
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
// Les membres sont ceux qui ont acces au dossier : proprietaire,
|
||||
// permission nominative non expiree, et tous les comptes actifs si le
|
||||
// dossier est public. Le role global ne compte pas.
|
||||
const rows = await db.query<{
|
||||
id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
role_slug: string;
|
||||
avatar_updated_at: Date | null;
|
||||
last_login_at: string | null;
|
||||
}>(
|
||||
`SELECT u.id, u.first_name, u.last_name, r.slug AS role_slug,
|
||||
ua.updated_at AS avatar_updated_at, u.last_login_at
|
||||
FROM users u
|
||||
JOIN roles r ON r.id = u.role_id
|
||||
LEFT JOIN user_avatars ua ON ua.user_id = u.id
|
||||
WHERE u.deleted_at IS NULL AND u.is_active = 1
|
||||
AND ( u.id = ?
|
||||
OR ? = 1
|
||||
OR EXISTS ( SELECT 1 FROM folder_permissions fp
|
||||
WHERE fp.folder_id = ? AND fp.user_id = u.id
|
||||
AND fp.level IN ('read', 'write', 'admin')
|
||||
AND ( fp.expires_at IS NULL OR fp.expires_at > UTC_TIMESTAMP() ) ) )
|
||||
ORDER BY u.first_name ASC, u.last_name ASC`,
|
||||
[folder.owner_id, folder.access_type === "public" ? 1 : 0, folderId],
|
||||
);
|
||||
|
||||
return context.json({
|
||||
members: rows.map((row) => ({
|
||||
id: row.id,
|
||||
first_name: row.first_name,
|
||||
last_name: row.last_name,
|
||||
role_slug: row.role_slug,
|
||||
has_avatar: row.avatar_updated_at !== null,
|
||||
avatar_updated_at: row.avatar_updated_at,
|
||||
last_login_at: row.last_login_at,
|
||||
is_self: row.id === user.id,
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
await assertFolder(folderId);
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
const limit = Math.min(200, Math.max(1, Number(context.req.query("limit")) || 50));
|
||||
const after = Math.max(0, Number(context.req.query("after")) || 0);
|
||||
|
||||
// `after` sert a la synchronisation incrementale (polling) : on ne remonte
|
||||
// que les messages posterieurs au dernier connu, dans l'ordre du temps.
|
||||
// Sans `after` : les `limit` derniers, remis dans l'ordre croissant.
|
||||
const rows =
|
||||
after > 0
|
||||
? await db.query<MessageRow>(
|
||||
`${SELECT_MESSAGE}
|
||||
WHERE m.folder_id = ? AND m.deleted_at IS NULL AND m.id > ?
|
||||
ORDER BY m.id ASC
|
||||
LIMIT ${limit}`,
|
||||
[folderId, after],
|
||||
)
|
||||
: (
|
||||
await db.query<MessageRow>(
|
||||
`${SELECT_MESSAGE}
|
||||
WHERE m.folder_id = ? AND m.deleted_at IS NULL
|
||||
ORDER BY m.id DESC
|
||||
LIMIT ${limit}`,
|
||||
[folderId],
|
||||
)
|
||||
).reverse();
|
||||
|
||||
return context.json({ messages: rows.map(publicMessage) });
|
||||
});
|
||||
|
||||
app.post("/api/cloud/folders/:folderId/chat/messages", requireAuth, async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
await assertFolder(folderId);
|
||||
// Etre membre du salon suffit a ecrire : un acces `read` participe a la
|
||||
// discussion, exactement comme le proprietaire.
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
|
||||
if (!limiter.allow(user.id)) {
|
||||
throw AppError.unprocessable("Vous envoyez des messages trop rapidement.");
|
||||
}
|
||||
const parsed = sendInput.safeParse(await context.req.json().catch(() => null));
|
||||
if (!parsed.success) {
|
||||
throw AppError.badRequest(parsed.error.issues[0]?.message ?? "Message invalide.");
|
||||
}
|
||||
|
||||
const result = await db.exec(
|
||||
"INSERT INTO chat_messages (folder_id, user_id, body) VALUES (?, ?, ?)",
|
||||
[folderId, user.id, parsed.data.body],
|
||||
);
|
||||
const row = await db.required<MessageRow>(`${SELECT_MESSAGE} WHERE m.id = ?`, [result.insertId]);
|
||||
return context.json({ message: publicMessage(row) }, 201);
|
||||
});
|
||||
|
||||
app.delete(
|
||||
"/api/cloud/folders/:folderId/chat/messages/:id",
|
||||
requireAuth,
|
||||
async (context) => {
|
||||
const user = currentUser(context);
|
||||
const folderId = context.req.param("folderId") ?? "";
|
||||
const id = Number(context.req.param("id"));
|
||||
await assertFolder(folderId);
|
||||
if (!(await canRead(db, user, folderId))) throw AppError.notFound("Dossier introuvable.");
|
||||
if (!Number.isSafeInteger(id) || id <= 0) throw AppError.notFound("Message introuvable.");
|
||||
|
||||
const row = await db.one<{ user_id: string | null }>(
|
||||
"SELECT user_id FROM chat_messages WHERE id = ? AND folder_id = ? AND deleted_at IS NULL",
|
||||
[id, folderId],
|
||||
);
|
||||
// Auteur ou gestionnaire du dossier (proprietaire) : meme reponse qu'un
|
||||
// message inexistant pour ne rien laisser deviner.
|
||||
if (!row || (row.user_id !== user.id && !(await canManageFolder(db, user, folderId)))) {
|
||||
throw AppError.notFound("Message introuvable.");
|
||||
}
|
||||
|
||||
await db.exec("UPDATE chat_messages SET deleted_at = UTC_TIMESTAMP(3) WHERE id = ?", [id]);
|
||||
await audit(db, context, user, "chat.delete", "message", String(id), { folderId }, config.TRUST_PROXY);
|
||||
return context.json({ ok: true });
|
||||
},
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user