diff --git a/.adonisjs/client/data.d.ts b/.adonisjs/client/data.d.ts new file mode 100644 index 0000000..43bc86e --- /dev/null +++ b/.adonisjs/client/data.d.ts @@ -0,0 +1,59 @@ +/** + * This file is automatically generated. + * DO NOT EDIT manually + */ + +/// +import type { InferData, InferVariants } from '@adonisjs/core/types/transformers' +import type { InferSharedProps, InferFlashData } from '@adonisjs/inertia/types' +import type ArticleTransformer from '#transformers/article_transformer' +import type ChannelTransformer from '#transformers/channel_transformer' +import type DiscussionTransformer from '#transformers/discussion_transformer' +import type NotificationTransformer from '#transformers/notification_transformer' +import type ReplyTransformer from '#transformers/reply_transformer' +import type ReportTransformer from '#transformers/report_transformer' +import type TagTransformer from '#transformers/tag_transformer' +import type ThreadTransformer from '#transformers/thread_transformer' +import type UserTransformer from '#transformers/user_transformer' +import type InertiaMiddleware from '#middleware/inertia_middleware' + +export namespace Data { + export type Article = InferData + export namespace Article { + export type Variants = InferVariants + } + export type Channel = InferData + export namespace Channel { + export type Variants = InferVariants + } + export type Discussion = InferData + export namespace Discussion { + export type Variants = InferVariants + } + export type Notification = InferData + export namespace Notification { + export type Variants = InferVariants + } + export type Reply = InferData + export namespace Reply { + export type Variants = InferVariants + } + export type Report = InferData + export namespace Report { + export type Variants = InferVariants + } + export type Tag = InferData + export namespace Tag { + export type Variants = InferVariants + } + export type Thread = InferData + export namespace Thread { + export type Variants = InferVariants + } + export type User = InferData + export namespace User { + export type Variants = InferVariants + } + export type SharedProps = InferSharedProps + export type FlashMessages = InferFlashData +} diff --git a/.adonisjs/client/manifest.d.ts b/.adonisjs/client/manifest.d.ts new file mode 100644 index 0000000..f2817ea --- /dev/null +++ b/.adonisjs/client/manifest.d.ts @@ -0,0 +1,11 @@ +/** + * This file is automatically generated. + * DO NOT EDIT manually + */ + +/// +/// +/// +/// +/// +/// diff --git a/.adonisjs/client/registry/index.ts b/.adonisjs/client/registry/index.ts new file mode 100644 index 0000000..0acbad5 --- /dev/null +++ b/.adonisjs/client/registry/index.ts @@ -0,0 +1,527 @@ +/* eslint-disable prettier/prettier */ +import type { AdonisEndpoint } from '@tuyau/core/types' +import type { Registry } from './schema.d.ts' +import type { ApiDefinition } from './tree.d.ts' + +const placeholder: any = {} + +const routes = { + 'home': { + methods: ["GET","HEAD"], + pattern: '/', + tokens: [{"old":"/","type":0,"val":"/","end":""}], + types: placeholder as Registry['home']['types'], + }, + 'health': { + methods: ["GET","HEAD"], + pattern: '/up', + tokens: [{"old":"/up","type":0,"val":"up","end":""}], + types: placeholder as Registry['health']['types'], + }, + 'pages.about': { + methods: ["GET","HEAD"], + pattern: '/a-propos', + tokens: [{"old":"/a-propos","type":0,"val":"a-propos","end":""}], + types: placeholder as Registry['pages.about']['types'], + }, + 'pages.code_of_conduct': { + methods: ["GET","HEAD"], + pattern: '/code-de-conduite', + tokens: [{"old":"/code-de-conduite","type":0,"val":"code-de-conduite","end":""}], + types: placeholder as Registry['pages.code_of_conduct']['types'], + }, + 'login': { + methods: ["GET","HEAD"], + pattern: '/login', + tokens: [{"old":"/login","type":0,"val":"login","end":""}], + types: placeholder as Registry['login']['types'], + }, + 'login.store': { + methods: ["POST"], + pattern: '/login', + tokens: [{"old":"/login","type":0,"val":"login","end":""}], + types: placeholder as Registry['login.store']['types'], + }, + 'register': { + methods: ["GET","HEAD"], + pattern: '/register', + tokens: [{"old":"/register","type":0,"val":"register","end":""}], + types: placeholder as Registry['register']['types'], + }, + 'register.store': { + methods: ["POST"], + pattern: '/register', + tokens: [{"old":"/register","type":0,"val":"register","end":""}], + types: placeholder as Registry['register.store']['types'], + }, + 'auth.github': { + methods: ["GET","HEAD"], + pattern: '/auth/github', + tokens: [{"old":"/auth/github","type":0,"val":"auth","end":""},{"old":"/auth/github","type":0,"val":"github","end":""}], + types: placeholder as Registry['auth.github']['types'], + }, + 'auth.github.callback': { + methods: ["GET","HEAD"], + pattern: '/auth/github/callback', + tokens: [{"old":"/auth/github/callback","type":0,"val":"auth","end":""},{"old":"/auth/github/callback","type":0,"val":"github","end":""},{"old":"/auth/github/callback","type":0,"val":"callback","end":""}], + types: placeholder as Registry['auth.github.callback']['types'], + }, + 'logout': { + methods: ["POST"], + pattern: '/logout', + tokens: [{"old":"/logout","type":0,"val":"logout","end":""}], + types: placeholder as Registry['logout']['types'], + }, + 'markdown.preview': { + methods: ["POST"], + pattern: '/markdown/preview', + tokens: [{"old":"/markdown/preview","type":0,"val":"markdown","end":""},{"old":"/markdown/preview","type":0,"val":"preview","end":""}], + types: placeholder as Registry['markdown.preview']['types'], + }, + 'replies.update': { + methods: ["PUT"], + pattern: '/replies/:id', + tokens: [{"old":"/replies/:id","type":0,"val":"replies","end":""},{"old":"/replies/:id","type":1,"val":"id","end":""}], + types: placeholder as Registry['replies.update']['types'], + }, + 'replies.destroy': { + methods: ["DELETE"], + pattern: '/replies/:id', + tokens: [{"old":"/replies/:id","type":0,"val":"replies","end":""},{"old":"/replies/:id","type":1,"val":"id","end":""}], + types: placeholder as Registry['replies.destroy']['types'], + }, + 'replies.like': { + methods: ["POST"], + pattern: '/replies/:id/like', + tokens: [{"old":"/replies/:id/like","type":0,"val":"replies","end":""},{"old":"/replies/:id/like","type":1,"val":"id","end":""},{"old":"/replies/:id/like","type":0,"val":"like","end":""}], + types: placeholder as Registry['replies.like']['types'], + }, + 'seo.robots': { + methods: ["GET","HEAD"], + pattern: '/robots.txt', + tokens: [{"old":"/robots.txt","type":0,"val":"robots.txt","end":""}], + types: placeholder as Registry['seo.robots']['types'], + }, + 'seo.sitemap': { + methods: ["GET","HEAD"], + pattern: '/sitemap.xml', + tokens: [{"old":"/sitemap.xml","type":0,"val":"sitemap.xml","end":""}], + types: placeholder as Registry['seo.sitemap']['types'], + }, + 'seo.feed': { + methods: ["GET","HEAD"], + pattern: '/feed.xml', + tokens: [{"old":"/feed.xml","type":0,"val":"feed.xml","end":""}], + types: placeholder as Registry['seo.feed']['types'], + }, + 'articles.index': { + methods: ["GET","HEAD"], + pattern: '/articles', + tokens: [{"old":"/articles","type":0,"val":"articles","end":""}], + types: placeholder as Registry['articles.index']['types'], + }, + 'articles.create': { + methods: ["GET","HEAD"], + pattern: '/articles/nouveau', + tokens: [{"old":"/articles/nouveau","type":0,"val":"articles","end":""},{"old":"/articles/nouveau","type":0,"val":"nouveau","end":""}], + types: placeholder as Registry['articles.create']['types'], + }, + 'articles.store': { + methods: ["POST"], + pattern: '/articles', + tokens: [{"old":"/articles","type":0,"val":"articles","end":""}], + types: placeholder as Registry['articles.store']['types'], + }, + 'articles.edit': { + methods: ["GET","HEAD"], + pattern: '/articles/:slug/modifier', + tokens: [{"old":"/articles/:slug/modifier","type":0,"val":"articles","end":""},{"old":"/articles/:slug/modifier","type":1,"val":"slug","end":""},{"old":"/articles/:slug/modifier","type":0,"val":"modifier","end":""}], + types: placeholder as Registry['articles.edit']['types'], + }, + 'articles.update': { + methods: ["PUT"], + pattern: '/articles/:slug', + tokens: [{"old":"/articles/:slug","type":0,"val":"articles","end":""},{"old":"/articles/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['articles.update']['types'], + }, + 'articles.destroy': { + methods: ["DELETE"], + pattern: '/articles/:slug', + tokens: [{"old":"/articles/:slug","type":0,"val":"articles","end":""},{"old":"/articles/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['articles.destroy']['types'], + }, + 'articles.like': { + methods: ["POST"], + pattern: '/articles/:slug/like', + tokens: [{"old":"/articles/:slug/like","type":0,"val":"articles","end":""},{"old":"/articles/:slug/like","type":1,"val":"slug","end":""},{"old":"/articles/:slug/like","type":0,"val":"like","end":""}], + types: placeholder as Registry['articles.like']['types'], + }, + 'articles.publish': { + methods: ["POST"], + pattern: '/articles/:slug/publish', + tokens: [{"old":"/articles/:slug/publish","type":0,"val":"articles","end":""},{"old":"/articles/:slug/publish","type":1,"val":"slug","end":""},{"old":"/articles/:slug/publish","type":0,"val":"publish","end":""}], + types: placeholder as Registry['articles.publish']['types'], + }, + 'articles.unpublish': { + methods: ["POST"], + pattern: '/articles/:slug/unpublish', + tokens: [{"old":"/articles/:slug/unpublish","type":0,"val":"articles","end":""},{"old":"/articles/:slug/unpublish","type":1,"val":"slug","end":""},{"old":"/articles/:slug/unpublish","type":0,"val":"unpublish","end":""}], + types: placeholder as Registry['articles.unpublish']['types'], + }, + 'articles.feature': { + methods: ["POST"], + pattern: '/articles/:slug/feature', + tokens: [{"old":"/articles/:slug/feature","type":0,"val":"articles","end":""},{"old":"/articles/:slug/feature","type":1,"val":"slug","end":""},{"old":"/articles/:slug/feature","type":0,"val":"feature","end":""}], + types: placeholder as Registry['articles.feature']['types'], + }, + 'articles.comments.store': { + methods: ["POST"], + pattern: '/articles/:slug/comments', + tokens: [{"old":"/articles/:slug/comments","type":0,"val":"articles","end":""},{"old":"/articles/:slug/comments","type":1,"val":"slug","end":""},{"old":"/articles/:slug/comments","type":0,"val":"comments","end":""}], + types: placeholder as Registry['articles.comments.store']['types'], + }, + 'articles.show': { + methods: ["GET","HEAD"], + pattern: '/articles/:slug', + tokens: [{"old":"/articles/:slug","type":0,"val":"articles","end":""},{"old":"/articles/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['articles.show']['types'], + }, + 'forum.index': { + methods: ["GET","HEAD"], + pattern: '/forum', + tokens: [{"old":"/forum","type":0,"val":"forum","end":""}], + types: placeholder as Registry['forum.index']['types'], + }, + 'forum.create': { + methods: ["GET","HEAD"], + pattern: '/forum/nouveau', + tokens: [{"old":"/forum/nouveau","type":0,"val":"forum","end":""},{"old":"/forum/nouveau","type":0,"val":"nouveau","end":""}], + types: placeholder as Registry['forum.create']['types'], + }, + 'forum.store': { + methods: ["POST"], + pattern: '/forum', + tokens: [{"old":"/forum","type":0,"val":"forum","end":""}], + types: placeholder as Registry['forum.store']['types'], + }, + 'forum.edit': { + methods: ["GET","HEAD"], + pattern: '/forum/:slug/modifier', + tokens: [{"old":"/forum/:slug/modifier","type":0,"val":"forum","end":""},{"old":"/forum/:slug/modifier","type":1,"val":"slug","end":""},{"old":"/forum/:slug/modifier","type":0,"val":"modifier","end":""}], + types: placeholder as Registry['forum.edit']['types'], + }, + 'forum.update': { + methods: ["PUT"], + pattern: '/forum/:slug', + tokens: [{"old":"/forum/:slug","type":0,"val":"forum","end":""},{"old":"/forum/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['forum.update']['types'], + }, + 'forum.destroy': { + methods: ["DELETE"], + pattern: '/forum/:slug', + tokens: [{"old":"/forum/:slug","type":0,"val":"forum","end":""},{"old":"/forum/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['forum.destroy']['types'], + }, + 'forum.replies.store': { + methods: ["POST"], + pattern: '/forum/:slug/replies', + tokens: [{"old":"/forum/:slug/replies","type":0,"val":"forum","end":""},{"old":"/forum/:slug/replies","type":1,"val":"slug","end":""},{"old":"/forum/:slug/replies","type":0,"val":"replies","end":""}], + types: placeholder as Registry['forum.replies.store']['types'], + }, + 'forum.solution.store': { + methods: ["POST"], + pattern: '/forum/:slug/solution', + tokens: [{"old":"/forum/:slug/solution","type":0,"val":"forum","end":""},{"old":"/forum/:slug/solution","type":1,"val":"slug","end":""},{"old":"/forum/:slug/solution","type":0,"val":"solution","end":""}], + types: placeholder as Registry['forum.solution.store']['types'], + }, + 'forum.solution.destroy': { + methods: ["DELETE"], + pattern: '/forum/:slug/solution', + tokens: [{"old":"/forum/:slug/solution","type":0,"val":"forum","end":""},{"old":"/forum/:slug/solution","type":1,"val":"slug","end":""},{"old":"/forum/:slug/solution","type":0,"val":"solution","end":""}], + types: placeholder as Registry['forum.solution.destroy']['types'], + }, + 'forum.pin': { + methods: ["POST"], + pattern: '/forum/:slug/pin', + tokens: [{"old":"/forum/:slug/pin","type":0,"val":"forum","end":""},{"old":"/forum/:slug/pin","type":1,"val":"slug","end":""},{"old":"/forum/:slug/pin","type":0,"val":"pin","end":""}], + types: placeholder as Registry['forum.pin']['types'], + }, + 'forum.lock': { + methods: ["POST"], + pattern: '/forum/:slug/lock', + tokens: [{"old":"/forum/:slug/lock","type":0,"val":"forum","end":""},{"old":"/forum/:slug/lock","type":1,"val":"slug","end":""},{"old":"/forum/:slug/lock","type":0,"val":"lock","end":""}], + types: placeholder as Registry['forum.lock']['types'], + }, + 'forum.show': { + methods: ["GET","HEAD"], + pattern: '/forum/:slug', + tokens: [{"old":"/forum/:slug","type":0,"val":"forum","end":""},{"old":"/forum/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['forum.show']['types'], + }, + 'discussions.index': { + methods: ["GET","HEAD"], + pattern: '/discussions', + tokens: [{"old":"/discussions","type":0,"val":"discussions","end":""}], + types: placeholder as Registry['discussions.index']['types'], + }, + 'discussions.create': { + methods: ["GET","HEAD"], + pattern: '/discussions/nouvelle', + tokens: [{"old":"/discussions/nouvelle","type":0,"val":"discussions","end":""},{"old":"/discussions/nouvelle","type":0,"val":"nouvelle","end":""}], + types: placeholder as Registry['discussions.create']['types'], + }, + 'discussions.store': { + methods: ["POST"], + pattern: '/discussions', + tokens: [{"old":"/discussions","type":0,"val":"discussions","end":""}], + types: placeholder as Registry['discussions.store']['types'], + }, + 'discussions.edit': { + methods: ["GET","HEAD"], + pattern: '/discussions/:slug/modifier', + tokens: [{"old":"/discussions/:slug/modifier","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/modifier","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/modifier","type":0,"val":"modifier","end":""}], + types: placeholder as Registry['discussions.edit']['types'], + }, + 'discussions.update': { + methods: ["PUT"], + pattern: '/discussions/:slug', + tokens: [{"old":"/discussions/:slug","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['discussions.update']['types'], + }, + 'discussions.destroy': { + methods: ["DELETE"], + pattern: '/discussions/:slug', + tokens: [{"old":"/discussions/:slug","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['discussions.destroy']['types'], + }, + 'discussions.replies.store': { + methods: ["POST"], + pattern: '/discussions/:slug/replies', + tokens: [{"old":"/discussions/:slug/replies","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/replies","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/replies","type":0,"val":"replies","end":""}], + types: placeholder as Registry['discussions.replies.store']['types'], + }, + 'discussions.pin': { + methods: ["POST"], + pattern: '/discussions/:slug/pin', + tokens: [{"old":"/discussions/:slug/pin","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/pin","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/pin","type":0,"val":"pin","end":""}], + types: placeholder as Registry['discussions.pin']['types'], + }, + 'discussions.lock': { + methods: ["POST"], + pattern: '/discussions/:slug/lock', + tokens: [{"old":"/discussions/:slug/lock","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/lock","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/lock","type":0,"val":"lock","end":""}], + types: placeholder as Registry['discussions.lock']['types'], + }, + 'discussions.show': { + methods: ["GET","HEAD"], + pattern: '/discussions/:slug', + tokens: [{"old":"/discussions/:slug","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug","type":1,"val":"slug","end":""}], + types: placeholder as Registry['discussions.show']['types'], + }, + 'search': { + methods: ["GET","HEAD"], + pattern: '/recherche', + tokens: [{"old":"/recherche","type":0,"val":"recherche","end":""}], + types: placeholder as Registry['search']['types'], + }, + 'notifications.index': { + methods: ["GET","HEAD"], + pattern: '/notifications', + tokens: [{"old":"/notifications","type":0,"val":"notifications","end":""}], + types: placeholder as Registry['notifications.index']['types'], + }, + 'notifications.read_all': { + methods: ["POST"], + pattern: '/notifications/read-all', + tokens: [{"old":"/notifications/read-all","type":0,"val":"notifications","end":""},{"old":"/notifications/read-all","type":0,"val":"read-all","end":""}], + types: placeholder as Registry['notifications.read_all']['types'], + }, + 'notifications.read': { + methods: ["POST"], + pattern: '/notifications/:id/read', + tokens: [{"old":"/notifications/:id/read","type":0,"val":"notifications","end":""},{"old":"/notifications/:id/read","type":1,"val":"id","end":""},{"old":"/notifications/:id/read","type":0,"val":"read","end":""}], + types: placeholder as Registry['notifications.read']['types'], + }, + 'notifications.show': { + methods: ["GET","HEAD"], + pattern: '/notifications/:id', + tokens: [{"old":"/notifications/:id","type":0,"val":"notifications","end":""},{"old":"/notifications/:id","type":1,"val":"id","end":""}], + types: placeholder as Registry['notifications.show']['types'], + }, + 'reports.store': { + methods: ["POST"], + pattern: '/signalements', + tokens: [{"old":"/signalements","type":0,"val":"signalements","end":""}], + types: placeholder as Registry['reports.store']['types'], + }, + 'members.index': { + methods: ["GET","HEAD"], + pattern: '/membres', + tokens: [{"old":"/membres","type":0,"val":"membres","end":""}], + types: placeholder as Registry['members.index']['types'], + }, + 'dashboard': { + methods: ["GET","HEAD"], + pattern: '/dashboard', + tokens: [{"old":"/dashboard","type":0,"val":"dashboard","end":""}], + types: placeholder as Registry['dashboard']['types'], + }, + 'settings.profile': { + methods: ["GET","HEAD"], + pattern: '/settings', + tokens: [{"old":"/settings","type":0,"val":"settings","end":""}], + types: placeholder as Registry['settings.profile']['types'], + }, + 'settings.profile.update': { + methods: ["PUT"], + pattern: '/settings', + tokens: [{"old":"/settings","type":0,"val":"settings","end":""}], + types: placeholder as Registry['settings.profile.update']['types'], + }, + 'settings.password': { + methods: ["GET","HEAD"], + pattern: '/settings/password', + tokens: [{"old":"/settings/password","type":0,"val":"settings","end":""},{"old":"/settings/password","type":0,"val":"password","end":""}], + types: placeholder as Registry['settings.password']['types'], + }, + 'settings.password.update': { + methods: ["PUT"], + pattern: '/settings/password', + tokens: [{"old":"/settings/password","type":0,"val":"settings","end":""},{"old":"/settings/password","type":0,"val":"password","end":""}], + types: placeholder as Registry['settings.password.update']['types'], + }, + 'settings.account': { + methods: ["GET","HEAD"], + pattern: '/settings/account', + tokens: [{"old":"/settings/account","type":0,"val":"settings","end":""},{"old":"/settings/account","type":0,"val":"account","end":""}], + types: placeholder as Registry['settings.account']['types'], + }, + 'settings.account.destroy': { + methods: ["DELETE"], + pattern: '/settings/account', + tokens: [{"old":"/settings/account","type":0,"val":"settings","end":""},{"old":"/settings/account","type":0,"val":"account","end":""}], + types: placeholder as Registry['settings.account.destroy']['types'], + }, + 'profile.show': { + methods: ["GET","HEAD"], + pattern: '/:username', + tokens: [{"old":"/:username","type":1,"val":"username","end":""}], + types: placeholder as Registry['profile.show']['types'], + }, + 'admin.index': { + methods: ["GET","HEAD"], + pattern: '/admin', + tokens: [{"old":"/admin","type":0,"val":"admin","end":""}], + types: placeholder as Registry['admin.index']['types'], + }, + 'admin.reports.index': { + methods: ["GET","HEAD"], + pattern: '/admin/signalements', + tokens: [{"old":"/admin/signalements","type":0,"val":"admin","end":""},{"old":"/admin/signalements","type":0,"val":"signalements","end":""}], + types: placeholder as Registry['admin.reports.index']['types'], + }, + 'admin.reports.resolve': { + methods: ["POST"], + pattern: '/admin/signalements/:target/:id/traiter', + tokens: [{"old":"/admin/signalements/:target/:id/traiter","type":0,"val":"admin","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":0,"val":"signalements","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":1,"val":"target","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":1,"val":"id","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":0,"val":"traiter","end":""}], + types: placeholder as Registry['admin.reports.resolve']['types'], + }, + 'admin.reports.dismiss': { + methods: ["POST"], + pattern: '/admin/signalements/:target/:id/ignorer', + tokens: [{"old":"/admin/signalements/:target/:id/ignorer","type":0,"val":"admin","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":0,"val":"signalements","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":1,"val":"target","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":1,"val":"id","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":0,"val":"ignorer","end":""}], + types: placeholder as Registry['admin.reports.dismiss']['types'], + }, + 'admin.reports.destroy': { + methods: ["DELETE"], + pattern: '/admin/signalements/:target/:id/contenu', + tokens: [{"old":"/admin/signalements/:target/:id/contenu","type":0,"val":"admin","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":0,"val":"signalements","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":1,"val":"target","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":1,"val":"id","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":0,"val":"contenu","end":""}], + types: placeholder as Registry['admin.reports.destroy']['types'], + }, + 'admin.members.index': { + methods: ["GET","HEAD"], + pattern: '/admin/membres', + tokens: [{"old":"/admin/membres","type":0,"val":"admin","end":""},{"old":"/admin/membres","type":0,"val":"membres","end":""}], + types: placeholder as Registry['admin.members.index']['types'], + }, + 'admin.members.role': { + methods: ["PUT"], + pattern: '/admin/membres/:id/role', + tokens: [{"old":"/admin/membres/:id/role","type":0,"val":"admin","end":""},{"old":"/admin/membres/:id/role","type":0,"val":"membres","end":""},{"old":"/admin/membres/:id/role","type":1,"val":"id","end":""},{"old":"/admin/membres/:id/role","type":0,"val":"role","end":""}], + types: placeholder as Registry['admin.members.role']['types'], + }, + 'admin.members.ban': { + methods: ["POST"], + pattern: '/admin/membres/:id/ban', + tokens: [{"old":"/admin/membres/:id/ban","type":0,"val":"admin","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"membres","end":""},{"old":"/admin/membres/:id/ban","type":1,"val":"id","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"ban","end":""}], + types: placeholder as Registry['admin.members.ban']['types'], + }, + 'admin.members.unban': { + methods: ["DELETE"], + pattern: '/admin/membres/:id/ban', + tokens: [{"old":"/admin/membres/:id/ban","type":0,"val":"admin","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"membres","end":""},{"old":"/admin/membres/:id/ban","type":1,"val":"id","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"ban","end":""}], + types: placeholder as Registry['admin.members.unban']['types'], + }, + 'admin.tags.index': { + methods: ["GET","HEAD"], + pattern: '/admin/tags', + tokens: [{"old":"/admin/tags","type":0,"val":"admin","end":""},{"old":"/admin/tags","type":0,"val":"tags","end":""}], + types: placeholder as Registry['admin.tags.index']['types'], + }, + 'admin.tags.store': { + methods: ["POST"], + pattern: '/admin/tags', + tokens: [{"old":"/admin/tags","type":0,"val":"admin","end":""},{"old":"/admin/tags","type":0,"val":"tags","end":""}], + types: placeholder as Registry['admin.tags.store']['types'], + }, + 'admin.tags.update': { + methods: ["PUT"], + pattern: '/admin/tags/:id', + tokens: [{"old":"/admin/tags/:id","type":0,"val":"admin","end":""},{"old":"/admin/tags/:id","type":0,"val":"tags","end":""},{"old":"/admin/tags/:id","type":1,"val":"id","end":""}], + types: placeholder as Registry['admin.tags.update']['types'], + }, + 'admin.tags.destroy': { + methods: ["DELETE"], + pattern: '/admin/tags/:id', + tokens: [{"old":"/admin/tags/:id","type":0,"val":"admin","end":""},{"old":"/admin/tags/:id","type":0,"val":"tags","end":""},{"old":"/admin/tags/:id","type":1,"val":"id","end":""}], + types: placeholder as Registry['admin.tags.destroy']['types'], + }, + 'admin.channels.index': { + methods: ["GET","HEAD"], + pattern: '/admin/canaux', + tokens: [{"old":"/admin/canaux","type":0,"val":"admin","end":""},{"old":"/admin/canaux","type":0,"val":"canaux","end":""}], + types: placeholder as Registry['admin.channels.index']['types'], + }, + 'admin.channels.store': { + methods: ["POST"], + pattern: '/admin/canaux', + tokens: [{"old":"/admin/canaux","type":0,"val":"admin","end":""},{"old":"/admin/canaux","type":0,"val":"canaux","end":""}], + types: placeholder as Registry['admin.channels.store']['types'], + }, + 'admin.channels.update': { + methods: ["PUT"], + pattern: '/admin/canaux/:id', + tokens: [{"old":"/admin/canaux/:id","type":0,"val":"admin","end":""},{"old":"/admin/canaux/:id","type":0,"val":"canaux","end":""},{"old":"/admin/canaux/:id","type":1,"val":"id","end":""}], + types: placeholder as Registry['admin.channels.update']['types'], + }, + 'admin.channels.destroy': { + methods: ["DELETE"], + pattern: '/admin/canaux/:id', + tokens: [{"old":"/admin/canaux/:id","type":0,"val":"admin","end":""},{"old":"/admin/canaux/:id","type":0,"val":"canaux","end":""},{"old":"/admin/canaux/:id","type":1,"val":"id","end":""}], + types: placeholder as Registry['admin.channels.destroy']['types'], + }, +} as const satisfies Record + +export { routes } + +export const registry = { + routes, + $tree: {} as ApiDefinition, +} + +declare module '@tuyau/core/types' { + export interface UserRegistry { + routes: typeof routes + $tree: ApiDefinition + } +} diff --git a/.adonisjs/client/registry/schema.d.ts b/.adonisjs/client/registry/schema.d.ts new file mode 100644 index 0000000..a1c8243 --- /dev/null +++ b/.adonisjs/client/registry/schema.d.ts @@ -0,0 +1,1018 @@ +/* eslint-disable prettier/prettier */ +/// + +import type { ExtractBody, ExtractErrorResponse, ExtractQuery, ExtractQueryForGet, ExtractResponse } from '@tuyau/core/types' +import type { InferInput, SimpleError } from '@vinejs/vine/types' + +export type ParamValue = string | number | bigint | boolean + +export interface Registry { + 'home': { + methods: ["GET","HEAD"] + pattern: '/' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'health': { + methods: ["GET","HEAD"] + pattern: '/up' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: unknown + errorResponse: unknown + } + } + 'pages.about': { + methods: ["GET","HEAD"] + pattern: '/a-propos' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: unknown + errorResponse: unknown + } + } + 'pages.code_of_conduct': { + methods: ["GET","HEAD"] + pattern: '/code-de-conduite' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: unknown + errorResponse: unknown + } + } + 'login': { + methods: ["GET","HEAD"] + pattern: '/login' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'login.store': { + methods: ["POST"] + pattern: '/login' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'register': { + methods: ["GET","HEAD"] + pattern: '/register' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'register.store': { + methods: ["POST"] + pattern: '/register' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'auth.github': { + methods: ["GET","HEAD"] + pattern: '/auth/github' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'auth.github.callback': { + methods: ["GET","HEAD"] + pattern: '/auth/github/callback' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'logout': { + methods: ["POST"] + pattern: '/logout' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'markdown.preview': { + methods: ["POST"] + pattern: '/markdown/preview' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'replies.update': { + methods: ["PUT"] + pattern: '/replies/:id' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'replies.destroy': { + methods: ["DELETE"] + pattern: '/replies/:id' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'replies.like': { + methods: ["POST"] + pattern: '/replies/:id/like' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'seo.robots': { + methods: ["GET","HEAD"] + pattern: '/robots.txt' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'seo.sitemap': { + methods: ["GET","HEAD"] + pattern: '/sitemap.xml' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'seo.feed': { + methods: ["GET","HEAD"] + pattern: '/feed.xml' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.index': { + methods: ["GET","HEAD"] + pattern: '/articles' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.create': { + methods: ["GET","HEAD"] + pattern: '/articles/nouveau' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.store': { + methods: ["POST"] + pattern: '/articles' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'articles.edit': { + methods: ["GET","HEAD"] + pattern: '/articles/:slug/modifier' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.update': { + methods: ["PUT"] + pattern: '/articles/:slug' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'articles.destroy': { + methods: ["DELETE"] + pattern: '/articles/:slug' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.like': { + methods: ["POST"] + pattern: '/articles/:slug/like' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.publish': { + methods: ["POST"] + pattern: '/articles/:slug/publish' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.unpublish': { + methods: ["POST"] + pattern: '/articles/:slug/unpublish' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.feature': { + methods: ["POST"] + pattern: '/articles/:slug/feature' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'articles.comments.store': { + methods: ["POST"] + pattern: '/articles/:slug/comments' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'articles.show': { + methods: ["GET","HEAD"] + pattern: '/articles/:slug' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.index': { + methods: ["GET","HEAD"] + pattern: '/forum' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.create': { + methods: ["GET","HEAD"] + pattern: '/forum/nouveau' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.store': { + methods: ["POST"] + pattern: '/forum' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'forum.edit': { + methods: ["GET","HEAD"] + pattern: '/forum/:slug/modifier' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.update': { + methods: ["PUT"] + pattern: '/forum/:slug' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'forum.destroy': { + methods: ["DELETE"] + pattern: '/forum/:slug' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.replies.store': { + methods: ["POST"] + pattern: '/forum/:slug/replies' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'forum.solution.store': { + methods: ["POST"] + pattern: '/forum/:slug/solution' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'forum.solution.destroy': { + methods: ["DELETE"] + pattern: '/forum/:slug/solution' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.pin': { + methods: ["POST"] + pattern: '/forum/:slug/pin' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.lock': { + methods: ["POST"] + pattern: '/forum/:slug/lock' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'forum.show': { + methods: ["GET","HEAD"] + pattern: '/forum/:slug' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'discussions.index': { + methods: ["GET","HEAD"] + pattern: '/discussions' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'discussions.create': { + methods: ["GET","HEAD"] + pattern: '/discussions/nouvelle' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'discussions.store': { + methods: ["POST"] + pattern: '/discussions' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'discussions.edit': { + methods: ["GET","HEAD"] + pattern: '/discussions/:slug/modifier' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'discussions.update': { + methods: ["PUT"] + pattern: '/discussions/:slug' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'discussions.destroy': { + methods: ["DELETE"] + pattern: '/discussions/:slug' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'discussions.replies.store': { + methods: ["POST"] + pattern: '/discussions/:slug/replies' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'discussions.pin': { + methods: ["POST"] + pattern: '/discussions/:slug/pin' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'discussions.lock': { + methods: ["POST"] + pattern: '/discussions/:slug/lock' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'discussions.show': { + methods: ["GET","HEAD"] + pattern: '/discussions/:slug' + types: { + body: {} + paramsTuple: [ParamValue] + params: { slug: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'search': { + methods: ["GET","HEAD"] + pattern: '/recherche' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'notifications.index': { + methods: ["GET","HEAD"] + pattern: '/notifications' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'notifications.read_all': { + methods: ["POST"] + pattern: '/notifications/read-all' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'notifications.read': { + methods: ["POST"] + pattern: '/notifications/:id/read' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'notifications.show': { + methods: ["GET","HEAD"] + pattern: '/notifications/:id' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'reports.store': { + methods: ["POST"] + pattern: '/signalements' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'members.index': { + methods: ["GET","HEAD"] + pattern: '/membres' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'dashboard': { + methods: ["GET","HEAD"] + pattern: '/dashboard' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'settings.profile': { + methods: ["GET","HEAD"] + pattern: '/settings' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'settings.profile.update': { + methods: ["PUT"] + pattern: '/settings' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'settings.password': { + methods: ["GET","HEAD"] + pattern: '/settings/password' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'settings.password.update': { + methods: ["PUT"] + pattern: '/settings/password' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'settings.account': { + methods: ["GET","HEAD"] + pattern: '/settings/account' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'settings.account.destroy': { + methods: ["DELETE"] + pattern: '/settings/account' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'profile.show': { + methods: ["GET","HEAD"] + pattern: '/:username' + types: { + body: {} + paramsTuple: [ParamValue] + params: { username: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.index': { + methods: ["GET","HEAD"] + pattern: '/admin' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.reports.index': { + methods: ["GET","HEAD"] + pattern: '/admin/signalements' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.reports.resolve': { + methods: ["POST"] + pattern: '/admin/signalements/:target/:id/traiter' + types: { + body: {} + paramsTuple: [ParamValue, ParamValue] + params: { target: ParamValue; id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.reports.dismiss': { + methods: ["POST"] + pattern: '/admin/signalements/:target/:id/ignorer' + types: { + body: {} + paramsTuple: [ParamValue, ParamValue] + params: { target: ParamValue; id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.reports.destroy': { + methods: ["DELETE"] + pattern: '/admin/signalements/:target/:id/contenu' + types: { + body: {} + paramsTuple: [ParamValue, ParamValue] + params: { target: ParamValue; id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.members.index': { + methods: ["GET","HEAD"] + pattern: '/admin/membres' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.members.role': { + methods: ["PUT"] + pattern: '/admin/membres/:id/role' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'admin.members.ban': { + methods: ["POST"] + pattern: '/admin/membres/:id/ban' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.members.unban': { + methods: ["DELETE"] + pattern: '/admin/membres/:id/ban' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.tags.index': { + methods: ["GET","HEAD"] + pattern: '/admin/tags' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.tags.store': { + methods: ["POST"] + pattern: '/admin/tags' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'admin.tags.update': { + methods: ["PUT"] + pattern: '/admin/tags/:id' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'admin.tags.destroy': { + methods: ["DELETE"] + pattern: '/admin/tags/:id' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.channels.index': { + methods: ["GET","HEAD"] + pattern: '/admin/canaux' + types: { + body: {} + paramsTuple: [] + params: {} + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } + 'admin.channels.store': { + methods: ["POST"] + pattern: '/admin/canaux' + types: { + body: ExtractBody> + paramsTuple: [] + params: {} + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'admin.channels.update': { + methods: ["PUT"] + pattern: '/admin/canaux/:id' + types: { + body: ExtractBody> + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: ExtractQuery> + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } } + } + } + 'admin.channels.destroy': { + methods: ["DELETE"] + pattern: '/admin/canaux/:id' + types: { + body: {} + paramsTuple: [ParamValue] + params: { id: ParamValue } + query: {} + response: ExtractResponse>> + errorResponse: ExtractErrorResponse>> + } + } +} diff --git a/.adonisjs/client/registry/tree.d.ts b/.adonisjs/client/registry/tree.d.ts new file mode 100644 index 0000000..5f14d6c --- /dev/null +++ b/.adonisjs/client/registry/tree.d.ts @@ -0,0 +1,139 @@ +/* eslint-disable prettier/prettier */ +import type { routes } from './index.ts' + +export interface ApiDefinition { + home: typeof routes['home'] + health: typeof routes['health'] + pages: { + about: typeof routes['pages.about'] + codeOfConduct: typeof routes['pages.code_of_conduct'] + } + login: typeof routes['login'] & { + store: typeof routes['login.store'] + } + register: typeof routes['register'] & { + store: typeof routes['register.store'] + } + auth: { + github: typeof routes['auth.github'] & { + callback: typeof routes['auth.github.callback'] + } + } + logout: typeof routes['logout'] + markdown: { + preview: typeof routes['markdown.preview'] + } + replies: { + update: typeof routes['replies.update'] + destroy: typeof routes['replies.destroy'] + like: typeof routes['replies.like'] + } + seo: { + robots: typeof routes['seo.robots'] + sitemap: typeof routes['seo.sitemap'] + feed: typeof routes['seo.feed'] + } + articles: { + index: typeof routes['articles.index'] + create: typeof routes['articles.create'] + store: typeof routes['articles.store'] + edit: typeof routes['articles.edit'] + update: typeof routes['articles.update'] + destroy: typeof routes['articles.destroy'] + like: typeof routes['articles.like'] + publish: typeof routes['articles.publish'] + unpublish: typeof routes['articles.unpublish'] + feature: typeof routes['articles.feature'] + comments: { + store: typeof routes['articles.comments.store'] + } + show: typeof routes['articles.show'] + } + forum: { + index: typeof routes['forum.index'] + create: typeof routes['forum.create'] + store: typeof routes['forum.store'] + edit: typeof routes['forum.edit'] + update: typeof routes['forum.update'] + destroy: typeof routes['forum.destroy'] + replies: { + store: typeof routes['forum.replies.store'] + } + solution: { + store: typeof routes['forum.solution.store'] + destroy: typeof routes['forum.solution.destroy'] + } + pin: typeof routes['forum.pin'] + lock: typeof routes['forum.lock'] + show: typeof routes['forum.show'] + } + discussions: { + index: typeof routes['discussions.index'] + create: typeof routes['discussions.create'] + store: typeof routes['discussions.store'] + edit: typeof routes['discussions.edit'] + update: typeof routes['discussions.update'] + destroy: typeof routes['discussions.destroy'] + replies: { + store: typeof routes['discussions.replies.store'] + } + pin: typeof routes['discussions.pin'] + lock: typeof routes['discussions.lock'] + show: typeof routes['discussions.show'] + } + search: typeof routes['search'] + notifications: { + index: typeof routes['notifications.index'] + readAll: typeof routes['notifications.read_all'] + read: typeof routes['notifications.read'] + show: typeof routes['notifications.show'] + } + reports: { + store: typeof routes['reports.store'] + } + members: { + index: typeof routes['members.index'] + } + dashboard: typeof routes['dashboard'] + settings: { + profile: typeof routes['settings.profile'] & { + update: typeof routes['settings.profile.update'] + } + password: typeof routes['settings.password'] & { + update: typeof routes['settings.password.update'] + } + account: typeof routes['settings.account'] & { + destroy: typeof routes['settings.account.destroy'] + } + } + profile: { + show: typeof routes['profile.show'] + } + admin: { + index: typeof routes['admin.index'] + reports: { + index: typeof routes['admin.reports.index'] + resolve: typeof routes['admin.reports.resolve'] + dismiss: typeof routes['admin.reports.dismiss'] + destroy: typeof routes['admin.reports.destroy'] + } + members: { + index: typeof routes['admin.members.index'] + role: typeof routes['admin.members.role'] + ban: typeof routes['admin.members.ban'] + unban: typeof routes['admin.members.unban'] + } + tags: { + index: typeof routes['admin.tags.index'] + store: typeof routes['admin.tags.store'] + update: typeof routes['admin.tags.update'] + destroy: typeof routes['admin.tags.destroy'] + } + channels: { + index: typeof routes['admin.channels.index'] + store: typeof routes['admin.channels.store'] + update: typeof routes['admin.channels.update'] + destroy: typeof routes['admin.channels.destroy'] + } + } +} diff --git a/.adonisjs/server/controllers.ts b/.adonisjs/server/controllers.ts new file mode 100644 index 0000000..5fb12f0 --- /dev/null +++ b/.adonisjs/server/controllers.ts @@ -0,0 +1,37 @@ +/** + * This file is automatically generated. + * DO NOT EDIT manually + */ + +export const controllers = { + admin: { + Channels: () => import('#controllers/admin/channels_controller'), + Members: () => import('#controllers/admin/members_controller'), + Overview: () => import('#controllers/admin/overview_controller'), + Reports: () => import('#controllers/admin/reports_controller'), + Tags: () => import('#controllers/admin/tags_controller'), + }, + ArticleActions: () => import('#controllers/article_actions_controller'), + ArticleComments: () => import('#controllers/article_comments_controller'), + Articles: () => import('#controllers/articles_controller'), + auth: { + Github: () => import('#controllers/auth/github_controller'), + Login: () => import('#controllers/auth/login_controller'), + Register: () => import('#controllers/auth/register_controller'), + }, + Dashboard: () => import('#controllers/dashboard_controller'), + DiscussionActions: () => import('#controllers/discussion_actions_controller'), + Discussions: () => import('#controllers/discussions_controller'), + Home: () => import('#controllers/home_controller'), + Markdown: () => import('#controllers/markdown_controller'), + Members: () => import('#controllers/members_controller'), + Notifications: () => import('#controllers/notifications_controller'), + Profile: () => import('#controllers/profile_controller'), + Replies: () => import('#controllers/replies_controller'), + Reports: () => import('#controllers/reports_controller'), + Search: () => import('#controllers/search_controller'), + Seo: () => import('#controllers/seo_controller'), + Settings: () => import('#controllers/settings_controller'), + ThreadActions: () => import('#controllers/thread_actions_controller'), + Threads: () => import('#controllers/threads_controller'), +} diff --git a/.adonisjs/server/events.ts b/.adonisjs/server/events.ts new file mode 100644 index 0000000..a74e59b --- /dev/null +++ b/.adonisjs/server/events.ts @@ -0,0 +1,6 @@ +/** + * This file is automatically generated. + * DO NOT EDIT manually + */ + +export const events = {} diff --git a/.adonisjs/server/listeners.ts b/.adonisjs/server/listeners.ts new file mode 100644 index 0000000..05f35f8 --- /dev/null +++ b/.adonisjs/server/listeners.ts @@ -0,0 +1,6 @@ +/** + * This file is automatically generated. + * DO NOT EDIT manually + */ + +export const listeners = {} diff --git a/.adonisjs/server/pages.d.ts b/.adonisjs/server/pages.d.ts new file mode 100644 index 0000000..a219e86 --- /dev/null +++ b/.adonisjs/server/pages.d.ts @@ -0,0 +1,48 @@ +import '@adonisjs/inertia/types' + +import type React from 'react' +import type { Prettify } from '@adonisjs/core/types/common' + +type ExtractProps = + T extends React.FC + ? Prettify> + : T extends React.Component + ? Prettify> + : never + +declare module '@adonisjs/inertia/types' { + export interface InertiaPages { + 'admin/channels': ExtractProps<(typeof import('../../inertia/pages/admin/channels.tsx'))['default']> + 'admin/index': ExtractProps<(typeof import('../../inertia/pages/admin/index.tsx'))['default']> + 'admin/members': ExtractProps<(typeof import('../../inertia/pages/admin/members.tsx'))['default']> + 'admin/reports': ExtractProps<(typeof import('../../inertia/pages/admin/reports.tsx'))['default']> + 'admin/tags': ExtractProps<(typeof import('../../inertia/pages/admin/tags.tsx'))['default']> + 'articles/[slug]': ExtractProps<(typeof import('../../inertia/pages/articles/[slug].tsx'))['default']> + 'articles/create': ExtractProps<(typeof import('../../inertia/pages/articles/create.tsx'))['default']> + 'articles/edit': ExtractProps<(typeof import('../../inertia/pages/articles/edit.tsx'))['default']> + 'articles/index': ExtractProps<(typeof import('../../inertia/pages/articles/index.tsx'))['default']> + 'auth/login': ExtractProps<(typeof import('../../inertia/pages/auth/login.tsx'))['default']> + 'auth/register': ExtractProps<(typeof import('../../inertia/pages/auth/register.tsx'))['default']> + 'dashboard/index': ExtractProps<(typeof import('../../inertia/pages/dashboard/index.tsx'))['default']> + 'discussions/create': ExtractProps<(typeof import('../../inertia/pages/discussions/create.tsx'))['default']> + 'discussions/edit': ExtractProps<(typeof import('../../inertia/pages/discussions/edit.tsx'))['default']> + 'discussions/index': ExtractProps<(typeof import('../../inertia/pages/discussions/index.tsx'))['default']> + 'discussions/show': ExtractProps<(typeof import('../../inertia/pages/discussions/show.tsx'))['default']> + 'errors/not_found': ExtractProps<(typeof import('../../inertia/pages/errors/not_found.tsx'))['default']> + 'errors/server_error': ExtractProps<(typeof import('../../inertia/pages/errors/server_error.tsx'))['default']> + 'forum/create': ExtractProps<(typeof import('../../inertia/pages/forum/create.tsx'))['default']> + 'forum/edit': ExtractProps<(typeof import('../../inertia/pages/forum/edit.tsx'))['default']> + 'forum/index': ExtractProps<(typeof import('../../inertia/pages/forum/index.tsx'))['default']> + 'forum/show': ExtractProps<(typeof import('../../inertia/pages/forum/show.tsx'))['default']> + 'home': ExtractProps<(typeof import('../../inertia/pages/home.tsx'))['default']> + 'members/index': ExtractProps<(typeof import('../../inertia/pages/members/index.tsx'))['default']> + 'notifications/index': ExtractProps<(typeof import('../../inertia/pages/notifications/index.tsx'))['default']> + 'pages/about': ExtractProps<(typeof import('../../inertia/pages/pages/about.tsx'))['default']> + 'pages/code_of_conduct': ExtractProps<(typeof import('../../inertia/pages/pages/code_of_conduct.tsx'))['default']> + 'profile/show': ExtractProps<(typeof import('../../inertia/pages/profile/show.tsx'))['default']> + 'search/index': ExtractProps<(typeof import('../../inertia/pages/search/index.tsx'))['default']> + 'settings/account': ExtractProps<(typeof import('../../inertia/pages/settings/account.tsx'))['default']> + 'settings/password': ExtractProps<(typeof import('../../inertia/pages/settings/password.tsx'))['default']> + 'settings/profile': ExtractProps<(typeof import('../../inertia/pages/settings/profile.tsx'))['default']> + } +} diff --git a/.adonisjs/server/routes.d.ts b/.adonisjs/server/routes.d.ts new file mode 100644 index 0000000..64a76af --- /dev/null +++ b/.adonisjs/server/routes.d.ts @@ -0,0 +1,226 @@ +import '@adonisjs/core/types/http' + +type ParamValue = string | number | bigint | boolean + +export type ScannedRoutes = { + ALL: { + 'home': { paramsTuple?: []; params?: {} } + 'health': { paramsTuple?: []; params?: {} } + 'pages.about': { paramsTuple?: []; params?: {} } + 'pages.code_of_conduct': { paramsTuple?: []; params?: {} } + 'login': { paramsTuple?: []; params?: {} } + 'login.store': { paramsTuple?: []; params?: {} } + 'register': { paramsTuple?: []; params?: {} } + 'register.store': { paramsTuple?: []; params?: {} } + 'auth.github': { paramsTuple?: []; params?: {} } + 'auth.github.callback': { paramsTuple?: []; params?: {} } + 'logout': { paramsTuple?: []; params?: {} } + 'markdown.preview': { paramsTuple?: []; params?: {} } + 'replies.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'replies.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'replies.like': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'seo.robots': { paramsTuple?: []; params?: {} } + 'seo.sitemap': { paramsTuple?: []; params?: {} } + 'seo.feed': { paramsTuple?: []; params?: {} } + 'articles.index': { paramsTuple?: []; params?: {} } + 'articles.create': { paramsTuple?: []; params?: {} } + 'articles.store': { paramsTuple?: []; params?: {} } + 'articles.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.like': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.publish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.unpublish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.feature': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.comments.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.index': { paramsTuple?: []; params?: {} } + 'forum.create': { paramsTuple?: []; params?: {} } + 'forum.store': { paramsTuple?: []; params?: {} } + 'forum.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.solution.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.solution.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.index': { paramsTuple?: []; params?: {} } + 'discussions.create': { paramsTuple?: []; params?: {} } + 'discussions.store': { paramsTuple?: []; params?: {} } + 'discussions.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'search': { paramsTuple?: []; params?: {} } + 'notifications.index': { paramsTuple?: []; params?: {} } + 'notifications.read_all': { paramsTuple?: []; params?: {} } + 'notifications.read': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'notifications.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'reports.store': { paramsTuple?: []; params?: {} } + 'members.index': { paramsTuple?: []; params?: {} } + 'dashboard': { paramsTuple?: []; params?: {} } + 'settings.profile': { paramsTuple?: []; params?: {} } + 'settings.profile.update': { paramsTuple?: []; params?: {} } + 'settings.password': { paramsTuple?: []; params?: {} } + 'settings.password.update': { paramsTuple?: []; params?: {} } + 'settings.account': { paramsTuple?: []; params?: {} } + 'settings.account.destroy': { paramsTuple?: []; params?: {} } + 'profile.show': { paramsTuple: [ParamValue]; params: {'username': ParamValue} } + 'admin.index': { paramsTuple?: []; params?: {} } + 'admin.reports.index': { paramsTuple?: []; params?: {} } + 'admin.reports.resolve': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} } + 'admin.reports.dismiss': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} } + 'admin.reports.destroy': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} } + 'admin.members.index': { paramsTuple?: []; params?: {} } + 'admin.members.role': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.members.ban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.members.unban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.tags.index': { paramsTuple?: []; params?: {} } + 'admin.tags.store': { paramsTuple?: []; params?: {} } + 'admin.tags.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.tags.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.channels.index': { paramsTuple?: []; params?: {} } + 'admin.channels.store': { paramsTuple?: []; params?: {} } + 'admin.channels.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.channels.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + } + GET: { + 'home': { paramsTuple?: []; params?: {} } + 'health': { paramsTuple?: []; params?: {} } + 'pages.about': { paramsTuple?: []; params?: {} } + 'pages.code_of_conduct': { paramsTuple?: []; params?: {} } + 'login': { paramsTuple?: []; params?: {} } + 'register': { paramsTuple?: []; params?: {} } + 'auth.github': { paramsTuple?: []; params?: {} } + 'auth.github.callback': { paramsTuple?: []; params?: {} } + 'seo.robots': { paramsTuple?: []; params?: {} } + 'seo.sitemap': { paramsTuple?: []; params?: {} } + 'seo.feed': { paramsTuple?: []; params?: {} } + 'articles.index': { paramsTuple?: []; params?: {} } + 'articles.create': { paramsTuple?: []; params?: {} } + 'articles.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.index': { paramsTuple?: []; params?: {} } + 'forum.create': { paramsTuple?: []; params?: {} } + 'forum.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.index': { paramsTuple?: []; params?: {} } + 'discussions.create': { paramsTuple?: []; params?: {} } + 'discussions.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'search': { paramsTuple?: []; params?: {} } + 'notifications.index': { paramsTuple?: []; params?: {} } + 'notifications.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'members.index': { paramsTuple?: []; params?: {} } + 'dashboard': { paramsTuple?: []; params?: {} } + 'settings.profile': { paramsTuple?: []; params?: {} } + 'settings.password': { paramsTuple?: []; params?: {} } + 'settings.account': { paramsTuple?: []; params?: {} } + 'profile.show': { paramsTuple: [ParamValue]; params: {'username': ParamValue} } + 'admin.index': { paramsTuple?: []; params?: {} } + 'admin.reports.index': { paramsTuple?: []; params?: {} } + 'admin.members.index': { paramsTuple?: []; params?: {} } + 'admin.tags.index': { paramsTuple?: []; params?: {} } + 'admin.channels.index': { paramsTuple?: []; params?: {} } + } + HEAD: { + 'home': { paramsTuple?: []; params?: {} } + 'health': { paramsTuple?: []; params?: {} } + 'pages.about': { paramsTuple?: []; params?: {} } + 'pages.code_of_conduct': { paramsTuple?: []; params?: {} } + 'login': { paramsTuple?: []; params?: {} } + 'register': { paramsTuple?: []; params?: {} } + 'auth.github': { paramsTuple?: []; params?: {} } + 'auth.github.callback': { paramsTuple?: []; params?: {} } + 'seo.robots': { paramsTuple?: []; params?: {} } + 'seo.sitemap': { paramsTuple?: []; params?: {} } + 'seo.feed': { paramsTuple?: []; params?: {} } + 'articles.index': { paramsTuple?: []; params?: {} } + 'articles.create': { paramsTuple?: []; params?: {} } + 'articles.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.index': { paramsTuple?: []; params?: {} } + 'forum.create': { paramsTuple?: []; params?: {} } + 'forum.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.index': { paramsTuple?: []; params?: {} } + 'discussions.create': { paramsTuple?: []; params?: {} } + 'discussions.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'search': { paramsTuple?: []; params?: {} } + 'notifications.index': { paramsTuple?: []; params?: {} } + 'notifications.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'members.index': { paramsTuple?: []; params?: {} } + 'dashboard': { paramsTuple?: []; params?: {} } + 'settings.profile': { paramsTuple?: []; params?: {} } + 'settings.password': { paramsTuple?: []; params?: {} } + 'settings.account': { paramsTuple?: []; params?: {} } + 'profile.show': { paramsTuple: [ParamValue]; params: {'username': ParamValue} } + 'admin.index': { paramsTuple?: []; params?: {} } + 'admin.reports.index': { paramsTuple?: []; params?: {} } + 'admin.members.index': { paramsTuple?: []; params?: {} } + 'admin.tags.index': { paramsTuple?: []; params?: {} } + 'admin.channels.index': { paramsTuple?: []; params?: {} } + } + POST: { + 'login.store': { paramsTuple?: []; params?: {} } + 'register.store': { paramsTuple?: []; params?: {} } + 'logout': { paramsTuple?: []; params?: {} } + 'markdown.preview': { paramsTuple?: []; params?: {} } + 'replies.like': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'articles.store': { paramsTuple?: []; params?: {} } + 'articles.like': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.publish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.unpublish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.feature': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'articles.comments.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.store': { paramsTuple?: []; params?: {} } + 'forum.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.solution.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.store': { paramsTuple?: []; params?: {} } + 'discussions.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'notifications.read_all': { paramsTuple?: []; params?: {} } + 'notifications.read': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'reports.store': { paramsTuple?: []; params?: {} } + 'admin.reports.resolve': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} } + 'admin.reports.dismiss': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} } + 'admin.members.ban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.tags.store': { paramsTuple?: []; params?: {} } + 'admin.channels.store': { paramsTuple?: []; params?: {} } + } + PUT: { + 'replies.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'articles.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'settings.profile.update': { paramsTuple?: []; params?: {} } + 'settings.password.update': { paramsTuple?: []; params?: {} } + 'admin.members.role': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.tags.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.channels.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + } + DELETE: { + 'replies.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'articles.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'forum.solution.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'discussions.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} } + 'settings.account.destroy': { paramsTuple?: []; params?: {} } + 'admin.reports.destroy': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} } + 'admin.members.unban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.tags.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + 'admin.channels.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + } +} +declare module '@adonisjs/core/types/http' { + export interface RoutesList extends ScannedRoutes {} +} \ No newline at end of file diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..6f3cc9d --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +node_modules +build +tmp +.git +.github +.env +.env.* +!.env.example +npm-debug.log +.DS_Store +.vscode +.idea diff --git a/.env.example b/.env.example index 25b1a45..fe0f0ce 100644 --- a/.env.example +++ b/.env.example @@ -1,15 +1,28 @@ +# Node TZ=UTC PORT=3333 HOST=localhost +NODE_ENV=development + +# App LOG_LEVEL=info APP_KEY= -NODE_ENV=development +APP_URL=http://${HOST}:${PORT} + +# Session SESSION_DRIVER=cookie + +# Database (PostgreSQL) DB_HOST=127.0.0.1 -DB_PORT=3306 -DB_USER=root -DB_PASSWORD=root -DB_DATABASE=app +DB_PORT=5432 +DB_USER=jscm +DB_PASSWORD=jscm +DB_DATABASE=jscm + +# Rate limiting +LIMITER_STORE=database + +# GitHub OAuth — https://github.com/settings/developers +# Callback URL: ${APP_URL}/auth/github/callback GITHUB_CLIENT_ID= GITHUB_CLIENT_SECRET= -GITHUB_CALLBACK_URL= \ No newline at end of file diff --git a/.env.test b/.env.test new file mode 100644 index 0000000..837fd45 --- /dev/null +++ b/.env.test @@ -0,0 +1,5 @@ +NODE_ENV=test +SESSION_DRIVER=memory +LIMITER_STORE=memory +DB_DATABASE=jscm_test +APP_URL=http://localhost:3333 diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml new file mode 100644 index 0000000..7d19db6 --- /dev/null +++ b/.github/workflows/deploy-staging.yml @@ -0,0 +1,77 @@ +name: CI & staging deploy + +on: + push: + pull_request: + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/staging' }} + +jobs: + check: + name: Typecheck, tests & build + runs-on: ubuntu-latest + services: + postgres: + image: postgres:18-alpine + env: + POSTGRES_USER: jscm + POSTGRES_PASSWORD: jscm + POSTGRES_DB: jscm_test + ports: ['5432:5432'] + options: >- + --health-cmd "pg_isready -U jscm -d jscm_test" + --health-interval 5s + --health-timeout 5s + --health-retries 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Prepare environment + run: | + cp .env.example .env + sed -i "s/^APP_KEY=.*/APP_KEY=$(openssl rand -hex 32)/" .env + - run: npm run typecheck + - run: node ace test + - run: node ace build + + deploy: + name: Deploy to staging.javascript.cm + needs: check + if: github.event_name == 'push' && github.ref == 'refs/heads/staging' + runs-on: ubuntu-latest + concurrency: + group: staging-deploy + cancel-in-progress: false + environment: + name: staging + url: https://staging.javascript.cm + steps: + - name: Check deploy secrets + id: secrets + env: + HOST: ${{ secrets.STAGING_HOST }} + run: | + if [ -z "$HOST" ]; then + echo "::warning title=Deploy skipped::STAGING_SSH_KEY, STAGING_KNOWN_HOSTS, STAGING_HOST and STAGING_SSH_USER secrets are not configured." + echo "ready=false" >> "$GITHUB_OUTPUT" + else + echo "ready=true" >> "$GITHUB_OUTPUT" + fi + - name: Configure SSH + if: steps.secrets.outputs.ready == 'true' + run: | + install -m 700 -d ~/.ssh + echo "${{ secrets.STAGING_SSH_KEY }}" > ~/.ssh/deploy_key + chmod 600 ~/.ssh/deploy_key + echo "${{ secrets.STAGING_KNOWN_HOSTS }}" > ~/.ssh/known_hosts + # The key is restricted server-side (forced command): it can only run the deploy script. + - name: Deploy + if: steps.secrets.outputs.ready == 'true' + run: ssh -i ~/.ssh/deploy_key ${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_HOST }} deploy diff --git a/.gitignore b/.gitignore index 4e9b445..dd7579a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,8 @@ # Dependencies and AdonisJS build node_modules build -tmp +tmp/* +!tmp/.gitkeep # Secrets .env diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..2614418 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,6 @@ +.adonisjs +node_modules +build + +# Generated +database/schema.ts diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..58bab20 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,43 @@ +# syntax=docker/dockerfile:1.7 + +# --------------------------------------------------------------------------- +# javascript.cm — production image +# --------------------------------------------------------------------------- +FROM node:24-bookworm-slim AS base +WORKDIR /app +ENV CI=true \ + npm_config_fund=false \ + npm_config_audit=false \ + npm_config_update_notifier=false + +# All dependencies (build tooling included) +FROM base AS deps +COPY package.json package-lock.json ./ +RUN --mount=type=cache,target=/root/.npm npm ci + +# Production dependencies only +FROM base AS production-deps +COPY package.json package-lock.json ./ +RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev + +# Compile TypeScript + Vite client and SSR bundles into ./build +FROM deps AS build +COPY . . +RUN node ace build + +# Runtime +FROM base AS runtime +ENV NODE_ENV=production \ + HOST=0.0.0.0 \ + PORT=3333 \ + LOG_LEVEL=info +COPY --from=production-deps --chown=node:node /app/node_modules ./node_modules +COPY --from=build --chown=node:node /app/build ./ +COPY --chown=node:node docker/entrypoint.sh /usr/local/bin/entrypoint.sh +RUN chmod +x /usr/local/bin/entrypoint.sh && mkdir -p tmp && chown node:node tmp +USER node +EXPOSE 3333 +HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \ + CMD node -e "fetch('http://127.0.0.1:3333/up').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))" +ENTRYPOINT ["/usr/local/bin/entrypoint.sh"] +CMD ["node", "bin/server.js"] diff --git a/README.md b/README.md index dff0775..31f3cf6 100644 --- a/README.md +++ b/README.md @@ -1,96 +1,94 @@ -# JavaScript.cm +# javascript.cm -This repository contains the source code for the [javascript.cm](https://javascript.cm) website ( javascript community in Cameroon ), inspired by [laravel.cm](https://laravel.cm). Laravel Cameroon is the largest community of PHP & Laravel developers residing in Cameroon. +Le site de **JavaScript Cameroun**, la communauté des développeurs JavaScript du 237 : articles, forum d’entraide (questions / solutions acceptées), discussions, profils et annuaire des membres. -## Server Requirements +Staging : -The following dependencies are required to start the installation: +## Stack -- Node.js >= 22.0.0 -- npm or yarn -- PostgreSQL or MySQL +| Couche | Outils | +| --------------- | -------------------------------------------------------------------------------------------------------------- | +| Backend | [AdonisJS 7](https://adonisjs.com) (TypeScript), Lucid ORM, VineJS, sessions + remember-me, rate limiting | +| Frontend | [Inertia 3](https://inertiajs.com) + React 19 (rendu serveur / SSR), [Tailwind CSS 4](https://tailwindcss.com) | +| Base de données | PostgreSQL 18 | +| Contenu | Markdown (GFM) rendu côté serveur, nettoyé (`rehype-sanitize`) et coloré par [Shiki](https://shiki.style) | +| Déploiement | Docker Compose derrière [Caddy](https://caddyserver.com) (HTTPS automatique) | -## Installation +## Démarrer en local -1. Clone this repo: - -```bash -git clone https://github.com/bleriotnoguia/javascript.cm.git -``` - -2. Install dependencies: +Prérequis : **Node.js ≥ 24**, Docker (ou un PostgreSQL local). ```bash +git clone https://github.com/javascriptcm/javascript.cm.git +cd javascript.cm npm install -``` -or +# PostgreSQL de développement +docker run -d --name jscm-pg -p 5455:5432 \ + -e POSTGRES_USER=jscm -e POSTGRES_PASSWORD=jscm -e POSTGRES_DB=jscm postgres:18-alpine -```bash -yarn install +cp .env.example .env # puis DB_PORT=5455 +node ace generate:key # remplit APP_KEY +node ace migration:run +node ace db:seed # canaux, tags + contenu de démonstration en développement +npm run dev # http://localhost:3333 ``` -3. Configure your database in `.env`: +Donner un rôle à un membre : `node ace user:promote --role=admin|moderator|member`. -```env -DB_CONNECTION=mysql -MYSQL_HOST=localhost -MYSQL_PORT=3306 -MYSQL_USER=root -MYSQL_PASSWORD= -MYSQL_DB_NAME=javascript_cm -``` +### Connexion GitHub (optionnelle) -4. Run migrations: +Créez une OAuth App sur avec comme callback `${APP_URL}/auth/github/callback`, puis renseignez `GITHUB_CLIENT_ID` et `GITHUB_CLIENT_SECRET`. Sans ces variables, le bouton « Continuer avec GitHub » est simplement masqué. -```bash -node ace migration:run -``` +## Commandes utiles -5. Start the development server: +| Commande | Rôle | +| ------------------------ | -------------------------------------------------------------------------------- | +| `npm run dev` | Serveur de développement (HMR) | +| `npm run typecheck` | Vérification TypeScript (backend + frontend) | +| `node ace test` | Tests (Japa) | +| `node ace build` | Build de production dans `build/` | +| `node ace codegen` | Régénère les types partagés (`.adonisjs/`) | +| `node ace migration:run` | Applique les migrations (le schéma TypeScript `database/schema.ts` est régénéré) | -```bash -node ace serve --watch -``` +## Organisation du code -## Features +``` +app/ + controllers/ contrôleurs HTTP (auth, articles, forum, discussions, membres, admin…) + models/ modèles Lucid (étendent les classes générées dans database/schema.ts) + transformers/ sérialisation typée vers Inertia (types Data.* côté React) + services/ markdown, slugs, réponses, OAuth GitHub… + validators/ schémas VineJS (messages en français : start/validator.ts) +inertia/ + pages/ une page React par écran + components/ui/ design system (boutons, champs, menus, éditeur Markdown…) + css/app.css tokens de design (clair / sombre) et utilitaires +start/routes/ routes par domaine (articles, forum, discussions, membres, admin) +deploy/ Caddyfile et script de déploiement +``` -- [x] User Authentication -- [x] GitHub Authentication -- [ ] Twitter Integration -- [ ] Article Management -- [ ] Forum -- [ ] Discussions -- [ ] Admin Dashboard -- [ ] Telegram Notifications +### Design -## Available Commands +Direction artistique : _un journal technique imprimé de la scène JavaScript camerounaise_. Papier chaud et encre carbone, le jaune JavaScript comme unique signal (surligneur, survols, focus), filets fins, Bricolage Grotesque + JetBrains Mono, thèmes clair et sombre. Toutes les couleurs passent par les tokens de `inertia/css/app.css`. -| Command | Description | -| ----------------------------- | ------------------------ | -| `node ace serve --watch` | Start development server | -| `node ace build` | Build for production | -| `node ace test` | Run tests | -| `node ace migration:run` | Run database migrations | -| `node ace migration:rollback` | Rollback migrations | +## Déploiement -## Stack / Resources +Le serveur exécute `docker-compose.yml` (application + PostgreSQL) ; Caddy, installé sur l’hôte, termine le TLS et relaie vers `127.0.0.1:3333` (`deploy/Caddyfile`). -- [AdonisJS](https://adonisjs.com/) -- [React.js](https://react.dev/) -- [Inertia.js](https://inertiajs.com/) -- [TailwindCSS](https://tailwindcss.com/) -- [MySQL](https://www.mysql.com/) -- [Lucid ORM](https://lucid.adonisjs.com/) +- Chaque push sur la branche `staging` lance le workflow GitHub Actions _Staging_ : typecheck + build, puis déploiement par SSH. La clé utilisée est restreinte côté serveur à une seule commande (`deploy/deploy.sh`). +- Au démarrage, le conteneur applique les migrations et les seeders idempotents. Le contenu de démonstration (membres et publications fictifs) n’est inséré en production que si `SEED_DEMO=true`. +- Déploiement manuel sur le serveur : `./deploy/deploy.sh staging`. +- Sauvegardes : `deploy/backup.sh` (dump PostgreSQL compressé, rotation 14 jours dans `~/backups/jscm`) est lancé chaque nuit par le timer systemd `jscm-backup` (`deploy/jscm-backup.{service,timer}`). Restauration : `docker compose exec -T db pg_restore -U -d --clean --if-exists < fichier.dump`. -## Contributing +## Contribuer -Please read the contribution guide before creating an issue or sending a pull request. +Les issues et pull requests sont les bienvenues. Ouvrez une issue pour discuter d’une fonctionnalité avant de vous lancer, gardez les PR ciblées, et vérifiez `npm run typecheck` et `node ace test` avant de pousser. -## Security Vulnerabilities +## Sécurité -If you discover a security vulnerability in the application, please send an email to [support@javascript.cm](mailto:support@javascript.cm). +Pour signaler une vulnérabilité, écrivez à [support@javascript.cm](mailto:support@javascript.cm) plutôt que d’ouvrir une issue publique. -## License +## Licence -The MIT License. Please see the License file for more information. +MIT. Inspiré par [Laravel Cameroun](https://laravel.cm). diff --git a/ace.js b/ace.js index e04fbe0..0eefd20 100644 --- a/ace.js +++ b/ace.js @@ -17,9 +17,9 @@ */ /** - * Register hook to process TypeScript files using ts-node-maintained + * Register hook to process TypeScript files using @poppinss/ts-exec */ -import 'ts-node-maintained/register/esm' +import '@poppinss/ts-exec' /** * Import ace console entrypoint diff --git a/adonisrc.ts b/adonisrc.ts index 5235734..243457b 100644 --- a/adonisrc.ts +++ b/adonisrc.ts @@ -1,6 +1,21 @@ +import { indexPages } from '@adonisjs/inertia' +import { indexEntities } from '@adonisjs/core/generators' import { defineConfig } from '@adonisjs/core/app' +import { generateRegistry } from '@tuyau/core/hooks' export default defineConfig({ + /* + |-------------------------------------------------------------------------- + | Experimental flags + |-------------------------------------------------------------------------- + | + | The following features will be enabled by default in the next major release + | of AdonisJS. You can opt into them today to avoid any breaking changes + | during upgrade. + | + */ + experimental: {}, + /* |-------------------------------------------------------------------------- | Commands @@ -10,7 +25,12 @@ export default defineConfig({ | will be scanned automatically from the "./commands" directory. | */ - commands: [() => import('@adonisjs/core/commands'), () => import('@adonisjs/lucid/commands')], + commands: [ + () => import('@adonisjs/core/commands'), + () => import('@adonisjs/lucid/commands'), + () => import('@adonisjs/session/commands'), + () => import('@adonisjs/inertia/commands'), + ], /* |-------------------------------------------------------------------------- @@ -34,11 +54,12 @@ export default defineConfig({ () => import('@adonisjs/vite/vite_provider'), () => import('@adonisjs/shield/shield_provider'), () => import('@adonisjs/static/static_provider'), - () => import('@adonisjs/cors/cors_provider'), () => import('@adonisjs/lucid/database_provider'), - () => import('@adonisjs/auth/auth_provider'), + () => import('@adonisjs/cors/cors_provider'), () => import('@adonisjs/inertia/inertia_provider'), - () => import('@adonisjs/ally/ally_provider'), + () => import('@adonisjs/auth/auth_provider'), + () => import('@adonisjs/limiter/limiter_provider'), + () => import('#providers/api_provider'), ], /* @@ -49,7 +70,11 @@ export default defineConfig({ | List of modules to import before starting the application. | */ - preloads: [() => import('#start/routes'), () => import('#start/kernel')], + preloads: [ + () => import('#start/routes'), + () => import('#start/kernel'), + () => import('#start/validator'), + ], /* |-------------------------------------------------------------------------- @@ -63,12 +88,12 @@ export default defineConfig({ tests: { suites: [ { - files: ['tests/unit/**/*.spec(.ts|.js)'], + files: ['tests/unit/**/*.spec.{ts,js}'], name: 'unit', timeout: 2000, }, { - files: ['tests/functional/**/*.spec(.ts|.js)'], + files: ['tests/functional/**/*.spec.{ts,js}'], name: 'functional', timeout: 30000, }, @@ -96,8 +121,14 @@ export default defineConfig({ }, ], - assetsBundler: false, hooks: { - onBuildStarting: [() => import('@adonisjs/vite/build_hook')], + init: [ + indexEntities({ + transformers: { enabled: true, withSharedProps: true }, + }), + indexPages({ framework: 'react' }), + generateRegistry(), + ], + buildStarting: [() => import('@adonisjs/vite/build_hook')], }, }) diff --git a/app/controllers/admin/channels_controller.ts b/app/controllers/admin/channels_controller.ts new file mode 100644 index 0000000..33e19d6 --- /dev/null +++ b/app/controllers/admin/channels_controller.ts @@ -0,0 +1,77 @@ +import type { HttpContext } from '@adonisjs/core/http' +import Channel from '#models/channel' +import ChannelTransformer from '#transformers/channel_transformer' +import { channelValidator } from '#validators/admin_validator' +import { uniqueSlug } from '#services/slug' + +export default class AdminChannelsController { + /** + * GET /admin/canaux + */ + async index({ inertia }: HttpContext) { + const channels = await Channel.query() + .withCount('threads') + .orderBy('position', 'asc') + .orderBy('name', 'asc') + + return inertia.render('admin/channels', { + // ChannelTransformer has no "position": extend its public shape. + channels: channels.map((channel) => ({ + ...new ChannelTransformer(channel).toObject(), + position: channel.position, + })), + nextPosition: channels.reduce((max, channel) => Math.max(max, channel.position), 0) + 1, + }) + } + + /** + * POST /admin/canaux + */ + async store({ request, response, session }: HttpContext) { + const data = await request.validateUsing(channelValidator, { meta: {} }) + const channel = await Channel.create({ + name: data.name, + slug: data.slug ?? (await uniqueSlug('channels', data.name)), + description: data.description, + position: data.position, + }) + session.flash('success', `Canal « ${channel.name} » créé.`) + return response.redirect().toPath('/admin/canaux') + } + + /** + * PUT /admin/canaux/:id + */ + async update({ params, request, response, session }: HttpContext) { + const channel = await Channel.findOrFail(params.id) + const data = await request.validateUsing(channelValidator, { meta: { id: channel.id } }) + channel.merge({ + name: data.name, + slug: data.slug ?? channel.slug, + description: data.description, + position: data.position, + }) + await channel.save() + session.flash('success', `Canal « ${channel.name} » mis à jour.`) + return response.redirect().toPath('/admin/canaux') + } + + /** + * DELETE /admin/canaux/:id — refused while questions live in the channel + * (the foreign key would delete them with it). + */ + async destroy({ params, response, session }: HttpContext) { + const channel = await Channel.query().where('id', params.id).withCount('threads').firstOrFail() + const threads = Number(channel.$extras.threads_count ?? 0) + if (threads > 0) { + session.flash( + 'error', + `Le canal « ${channel.name} » contient ${threads} question${threads > 1 ? 's' : ''} : déplacez-les avant de le supprimer.` + ) + return response.redirect().toPath('/admin/canaux') + } + await channel.delete() + session.flash('success', `Canal « ${channel.name} » supprimé.`) + return response.redirect().toPath('/admin/canaux') + } +} diff --git a/app/controllers/admin/members_controller.ts b/app/controllers/admin/members_controller.ts new file mode 100644 index 0000000..0c4236a --- /dev/null +++ b/app/controllers/admin/members_controller.ts @@ -0,0 +1,155 @@ +import type { HttpContext } from '@adonisjs/core/http' +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import User from '#models/user' +import UserTransformer from '#transformers/user_transformer' +import { roleValidator } from '#validators/admin_validator' +import { MEMBER_COUNTERS, likePattern } from '#controllers/members_controller' + +const FILTERS = ['tous', 'equipe', 'suspendus'] as const +type Filter = (typeof FILTERS)[number] + +const RANK = { member: 0, moderator: 1, admin: 2 } as const + +export default class AdminMembersController { + /** + * GET /admin/membres — search, filter, moderate. + */ + async index({ request, inertia, auth }: HttpContext) { + const viewer = auth.getUserOrFail() + const q = String(request.input('q') ?? '') + .trim() + .slice(0, 80) + const requested = request.input('filtre') + const filter: Filter = FILTERS.includes(requested) ? requested : 'tous' + const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1) + + const query = User.query() + .select('users.*') + .select(db.raw(`${MEMBER_COUNTERS.articles} as articles_count`)) + .select(db.raw(`${MEMBER_COUNTERS.threads} as threads_count`)) + .select(db.raw(`${MEMBER_COUNTERS.replies} as replies_count`)) + + if (q) { + const pattern = likePattern(q.replace(/^@/, '')) + query.where((builder) => { + builder.whereILike('users.username', pattern).orWhereILike('users.name', pattern) + // Only admins may look members up by e-mail. + if (viewer.isAdmin) builder.orWhereILike('users.email', pattern) + }) + } + if (filter === 'equipe') query.whereIn('role', ['admin', 'moderator']) + if (filter === 'suspendus') query.whereNotNull('banned_at') + + const [paginator, counts] = await Promise.all([ + query.orderBy('users.created_at', 'desc').orderBy('users.id', 'desc').paginate(page, 30), + db + .rawQuery( + `select + (select count(*) from users) as tous, + (select count(*) from users where role in ('admin', 'moderator')) as equipe, + (select count(*) from users where banned_at is not null) as suspendus` + ) + .then((result) => result.rows[0]), + ]) + + const items = paginator.all() + const meta = paginator.getMeta() + + return inertia.render('admin/members', { + members: viewer.isAdmin + ? UserTransformer.paginate(items, meta).useVariant('forAdmin') + : UserTransformer.paginate(items, meta).useVariant('forModeration'), + filters: { q, filter }, + counts: { + tous: Number(counts.tous), + equipe: Number(counts.equipe), + suspendus: Number(counts.suspendus), + }, + }) + } + + /** + * PUT /admin/membres/:id/role — admins only (see routes). + */ + async updateRole({ params, request, auth, response, session }: HttpContext) { + const viewer = auth.getUserOrFail() + const member = await User.findOrFail(params.id) + const { role } = await request.validateUsing(roleValidator) + + if (member.id === viewer.id) { + session.flash('error', 'Vous ne pouvez pas modifier votre propre rôle.') + return response.redirect().back() + } + if (member.isBanned && role !== 'member') { + session.flash('error', 'Réactivez ce compte avant de lui confier un rôle.') + return response.redirect().back() + } + + member.role = role + await member.save() + + const labels = { member: 'membre', moderator: 'modérateur', admin: 'administrateur' } + session.flash('success', `@${member.username} est désormais ${labels[role]}.`) + return response.redirect().back() + } + + /** + * POST /admin/membres/:id/ban — suspend an account. + */ + async ban({ params, auth, response, session }: HttpContext) { + const viewer = auth.getUserOrFail() + const member = await User.findOrFail(params.id) + + const refusal = this.cannotModerate(viewer, member) + if (refusal) { + session.flash('error', refusal) + return response.redirect().back() + } + if (member.isBanned) { + session.flash('error', `@${member.username} est déjà suspendu.`) + return response.redirect().back() + } + + member.bannedAt = DateTime.now() + await member.save() + // Close the "remember me" sessions; the auth middleware does the rest. + await db.from('remember_me_tokens').where('tokenable_id', member.id).delete() + + session.flash('success', `Le compte @${member.username} est suspendu.`) + return response.redirect().back() + } + + /** + * DELETE /admin/membres/:id/ban — lift a suspension. + */ + async unban({ params, auth, response, session }: HttpContext) { + const viewer = auth.getUserOrFail() + const member = await User.findOrFail(params.id) + + const refusal = this.cannotModerate(viewer, member) + if (refusal) { + session.flash('error', refusal) + return response.redirect().back() + } + + member.bannedAt = null + await member.save() + session.flash('success', `Le compte @${member.username} est réactivé.`) + return response.redirect().back() + } + + /** + * Nobody moderates themselves; staff can only act on lower ranks + * (moderators cannot touch the staff, admins cannot ban admins). + */ + private cannotModerate(viewer: User, member: User): string | null { + if (viewer.id === member.id) return 'Vous ne pouvez pas suspendre votre propre compte.' + if (RANK[member.role] >= RANK[viewer.role]) { + return viewer.isAdmin + ? 'Retirez d’abord son rôle d’administrateur à ce compte.' + : 'Seul un administrateur peut suspendre un membre de l’équipe.' + } + return null + } +} diff --git a/app/controllers/admin/overview_controller.ts b/app/controllers/admin/overview_controller.ts new file mode 100644 index 0000000..99ac6c4 --- /dev/null +++ b/app/controllers/admin/overview_controller.ts @@ -0,0 +1,88 @@ +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' +import User from '#models/user' +import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import UserTransformer from '#transformers/user_transformer' +import ArticleTransformer from '#transformers/article_transformer' +import ThreadTransformer from '#transformers/thread_transformer' +import DiscussionTransformer from '#transformers/discussion_transformer' +import { MEMBER_COUNTERS } from '#controllers/members_controller' + +export default class OverviewController { + /** + * GET /admin — community vital signs and the latest arrivals. + */ + async index({ inertia, auth }: HttpContext) { + const [counts, members, articles, threads, discussions] = await Promise.all([ + db + .rawQuery( + `select + (select count(*) from users where banned_at is null) as members, + (select count(*) from users where banned_at is not null) as banned, + (select count(*) from users where role in ('admin', 'moderator')) as staff, + (select count(*) from users where created_at > now() - interval '7 days') as signups_week, + (select count(*) from articles where published_at is not null and published_at <= now()) as articles, + (select count(*) from articles where published_at is null or published_at > now()) as drafts, + (select count(*) from threads) as threads, + (select count(*) from threads where solution_reply_id is null) as unsolved, + (select count(*) from discussions) as discussions, + (select count(*) from replies) as replies, + (select count(*) from tags) as tags, + (select count(*) from channels) as channels, + (select count(*) from reports where status = 'open') as reports_open, + (select count(*) from ( + select 1 from reports where status = 'open' group by target_type, target_id + ) as queue) as reports_queue` + ) + .then((result) => result.rows[0]), + User.query() + .select('users.*') + .select(db.raw(`${MEMBER_COUNTERS.articles} as articles_count`)) + .select(db.raw(`${MEMBER_COUNTERS.threads} as threads_count`)) + .select(db.raw(`${MEMBER_COUNTERS.replies} as replies_count`)) + .orderBy('created_at', 'desc') + .limit(8), + Article.query() + .withScopes((s) => s.published()) + .preload('author') + .withCount('likes') + .withCount('comments') + .orderBy('published_at', 'desc') + .limit(6), + Thread.query().preload('author').preload('channel').orderBy('created_at', 'desc').limit(6), + Discussion.query().preload('author').orderBy('created_at', 'desc').limit(6), + ]) + + const stats = Object.fromEntries( + Object.entries(counts as Record).map(([key, value]) => [key, Number(value)]) + ) as Record< + | 'members' + | 'banned' + | 'staff' + | 'signups_week' + | 'articles' + | 'drafts' + | 'threads' + | 'unsolved' + | 'discussions' + | 'replies' + | 'tags' + | 'channels' + | 'reports_open' + | 'reports_queue', + number + > + + return inertia.render('admin/index', { + stats, + members: auth.user!.isAdmin + ? UserTransformer.transform(members).useVariant('forAdmin') + : UserTransformer.transform(members).useVariant('forModeration'), + articles: ArticleTransformer.transform(articles), + threads: ThreadTransformer.transform(threads), + discussions: DiscussionTransformer.transform(discussions), + }) + } +} diff --git a/app/controllers/admin/reports_controller.ts b/app/controllers/admin/reports_controller.ts new file mode 100644 index 0000000..15aa9c8 --- /dev/null +++ b/app/controllers/admin/reports_controller.ts @@ -0,0 +1,436 @@ +import type { HttpContext } from '@adonisjs/core/http' +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import type { DatabaseQueryBuilderContract } from '@adonisjs/lucid/types/querybuilder' +import Report from '#models/report' +import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Reply from '#models/reply' +import User from '#models/user' +import ReportTransformer, { type ReportQueueTarget } from '#transformers/report_transformer' +import { deleteReply } from '#services/reply_service' +import { plainExcerpt } from '#services/markdown' +import { THREAD_REPLIES_PER_PAGE } from '#controllers/threads_controller' +import { DISCUSSION_REPLIES_PER_PAGE } from '#controllers/discussions_controller' +import { REPORT_TARGETS, type ReportTarget } from '#validators/report_validator' + +const TABS = { ouverts: 'open', traites: 'resolved', ignores: 'dismissed' } as const +type Tab = keyof typeof TABS +type Status = (typeof TABS)[Tab] + +const PER_PAGE = 20 + +/** + * Column of "replies" pointing at each kind of parent. + */ +const REPLY_PARENT_COLUMNS = { + article: 'article_id', + thread: 'thread_id', + discussion: 'discussion_id', +} as const + +type Row = { type: ReportTarget; id: number } + +/** + * Same rule as User.canManageContent, from an already loaded owner (the + * queue lists up to 20 rows: no query per row). + */ +function canManage(viewer: User, owner: User | null) { + if (!owner) return viewer.isAdmin + if (viewer.id === owner.id || viewer.isAdmin) return true + return viewer.isModerator && owner.role === 'member' +} + +/** + * Restrict a query on "reports" to the reports of one content. + */ +function ofTarget(query: DatabaseQueryBuilderContract, type: ReportTarget, id: number) { + return query.where('target_type', type).where('target_id', id) +} + +/** + * Number of rows (distinct contents) per status, for the tabs. + */ +export async function reportQueueCounts(): Promise> { + const result = await db.rawQuery( + `select status, count(*) as total from ( + select status from reports group by status, target_type, target_id + ) as grouped group by status` + ) + const counts: Record = { open: 0, resolved: 0, dismissed: 0 } + for (const row of result.rows as { status: Status; total: string }[]) { + counts[row.status] = Number(row.total) + } + return counts +} + +/** + * The moderation queue: what members reported, grouped by content. Reports + * outlive their content (deleted from the queue or elsewhere): such rows + * are shown from the snapshot taken when the report was filed. + */ +export default class AdminReportsController { + /** + * GET /admin/signalements?statut=ouverts|traites|ignores + */ + async index({ request, inertia, auth }: HttpContext) { + const viewer = auth.getUserOrFail() + const requested = String(request.input('statut') ?? '') + const tab: Tab = Object.hasOwn(TABS, requested) ? (requested as Tab) : 'ouverts' + const status = TABS[tab] + const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1) + + const groups = db + .from('reports') + .select('target_type', 'target_id') + .select(db.raw('max(created_at) as last_reported_at')) + .where('status', status) + .groupBy('target_type', 'target_id') + if (status === 'open') { + groups.orderBy('last_reported_at', 'desc') + } else { + groups.orderByRaw('max(resolved_at) desc nulls last').orderBy('last_reported_at', 'desc') + } + groups.orderByRaw('max(id) desc') + + const [paginator, counts] = await Promise.all([ + groups.paginate(page, PER_PAGE), + reportQueueCounts(), + ]) + const rows: Row[] = (paginator.all() as { target_type: ReportTarget; target_id: number }[]).map( + (row) => ({ type: row.target_type, id: Number(row.target_id) }) + ) + + const ids: Record = { + article: [], + thread: [], + discussion: [], + reply: [], + } + for (const row of rows) ids[row.type].push(row.id) + + const [reports, articles, threads, discussions, replies] = rows.length + ? await Promise.all([ + Report.query() + .where('status', status) + .where((query) => { + for (const type of REPORT_TARGETS) { + if (!ids[type].length) continue + query.orWhere((sub) => + sub.where('target_type', type).whereIn('target_id', ids[type]) + ) + } + }) + .preload('reporter') + .preload('resolvedBy') + .orderBy('created_at', 'desc') + .orderBy('id', 'desc'), + Article.query() + .select('id', 'user_id', 'title', 'slug', 'published_at') + .whereIn('id', ids.article) + .preload('author'), + Thread.query() + .select('id', 'user_id', 'title', 'slug') + .whereIn('id', ids.thread) + .preload('author'), + Discussion.query() + .select('id', 'user_id', 'title', 'slug') + .whereIn('id', ids.discussion) + .preload('author'), + Reply.query() + .select('replies.*') + // Position among its siblings, to link to the right page of a long thread. + .select( + db.raw( + `(select count(*) from replies as siblings + where (siblings.thread_id = replies.thread_id or siblings.discussion_id = replies.discussion_id) + and siblings.id < replies.id) as position` + ) + ) + .whereIn('id', ids.reply) + .preload('author') + .preload('thread', (query) => query.select('id', 'title', 'slug')) + .preload('discussion', (query) => query.select('id', 'title', 'slug')) + .preload('article', (query) => query.select('id', 'title', 'slug', 'published_at')), + ]) + : [[], [], [], [], []] + + const grouped = rows + .map((row) => ({ + row, + reports: reports.filter( + (report) => report.targetType === row.type && report.targetId === row.id + ), + live: describe(row, { articles, threads, discussions, replies }), + })) + .filter((item) => item.reports.length) + + // Owners of deleted contents, from the snapshots. + const missingOwnerIds = grouped + .filter((item) => !item.live) + .map((item) => item.reports.find((report) => report.targetOwnerId)?.targetOwnerId) + .filter((id): id is number => typeof id === 'number') + const owners = missingOwnerIds.length + ? await User.query().whereIn('id', [...new Set(missingOwnerIds)]) + : [] + + const leads = grouped.map(({ row, reports: group, live }) => { + const content = live ?? snapshot(row, group, owners) + const [lead] = group + lead.$extras.queue = { + target: content.target, + owner: content.owner, + reports: group, + canDelete: !content.target.deleted && canManage(viewer, content.owner), + } + return lead + }) + + return inertia.render('admin/reports', { + rows: ReportTransformer.paginate(leads, paginator.getMeta()).useVariant('forQueue').depth(3), + tab, + counts: { + ouverts: counts.open, + traites: counts.resolved, + ignores: counts.dismissed, + }, + }) + } + + /** + * POST /admin/signalements/:target/:id/ignorer — the content stays online. + */ + async dismiss(ctx: HttpContext) { + return this.close(ctx, 'dismissed') + } + + /** + * POST /admin/signalements/:target/:id/traiter — handled another way + * (content edited, author contacted…), or the content is already gone. + */ + async resolve(ctx: HttpContext) { + return this.close(ctx, 'resolved') + } + + /** + * DELETE /admin/signalements/:target/:id/contenu — remove the reported + * content. Staff ranks apply: moderators cannot delete the staff's content. + * Its reports stay, marked as resolved (with those of its replies, which + * go with it). + */ + async destroyContent({ params, auth, response, session }: HttpContext) { + const viewer = auth.getUserOrFail() + const type = params.target as ReportTarget + const id = Number(params.id) + + const open = await this.openReportsCount(type, id) + if (!open) { + session.flash('error', 'Ces signalements ont déjà été traités.') + return response.redirect().back() + } + + const content = await this.findContent(type, id) + if (!content) { + session.flash( + 'error', + 'Ce contenu a déjà été supprimé : marquez plutôt le signalement comme traité.' + ) + return response.redirect().back() + } + if (!(await viewer.canManageContent(content.userId))) { + session.flash( + 'error', + 'Seul un administrateur peut supprimer le contenu d’un membre de l’équipe.' + ) + return response.redirect().back() + } + + // Record the decision, then delete (the reports keep their target + // identity and snapshot: ON DELETE SET NULL). Replies go through the + // reply service so the thread / discussion counters stay right. + const closed = await this.closeReports(type, id, 'resolved', viewer, { withReplies: true }) + try { + if (content instanceof Reply) { + await deleteReply(content) + } else { + await content.delete() + } + } catch (error) { + await db + .from('reports') + .whereIn('id', closed) + .update({ status: 'open', resolved_by_id: null, resolved_at: null }) + throw error + } + + const label = closed.length > 1 ? `${closed.length} signalements clos` : 'signalement clos' + session.flash('success', `Contenu supprimé, ${label}.`) + return response.redirect().back() + } + + private async close({ params, auth, response, session }: HttpContext, status: Status) { + const viewer = auth.getUserOrFail() + const closed = await this.closeReports( + params.target as ReportTarget, + Number(params.id), + status, + viewer + ) + if (!closed.length) { + session.flash('error', 'Ces signalements ont déjà été traités.') + return response.redirect().back() + } + session.flash( + 'success', + status === 'dismissed' + ? 'Signalement ignoré : le contenu reste en ligne.' + : 'Signalement marqué comme traité.' + ) + return response.redirect().back() + } + + /** + * Close every open report of a content (and, when it is deleted, of its + * replies). Returns the ids of the reports closed. + */ + private async closeReports( + type: ReportTarget, + id: number, + status: Status, + viewer: User, + options: { withReplies?: boolean } = {} + ): Promise { + const now = DateTime.now().toSQL() + const rows: { id: number }[] = await db + .from('reports') + .where('status', 'open') + .where((query) => { + query.where((sub) => ofTarget(sub, type, id)) + if (options.withReplies && type !== 'reply') { + query.orWhere((sub) => + sub + .where('target_type', 'reply') + .whereIn( + 'target_id', + db.from('replies').select('id').where(REPLY_PARENT_COLUMNS[type], id) + ) + ) + } + }) + .update({ status, resolved_by_id: viewer.id, resolved_at: now, updated_at: now }, ['id']) + return rows.map((row) => row.id) + } + + private async openReportsCount(type: ReportTarget, id: number) { + const [row] = await ofTarget(db.from('reports'), type, id) + .where('status', 'open') + .count('* as total') + return Number(row?.total ?? 0) + } + + private async findContent(type: ReportTarget, id: number) { + switch (type) { + case 'article': + return Article.find(id) + case 'thread': + return Thread.find(id) + case 'discussion': + return Discussion.find(id) + case 'reply': + return Reply.find(id) + } + } +} + +type Described = { target: ReportQueueTarget; owner: User | null } + +/** + * A deleted content, as the reports remember it: label (title, or the + * parent's title for a reply) and owner. No link. + */ +function snapshot(row: Row, reports: Report[], owners: User[]): Described { + const label = reports.find((report) => report.targetLabel)?.targetLabel ?? null + const ownerId = reports.find((report) => report.targetOwnerId)?.targetOwnerId ?? null + const isReply = row.type === 'reply' + return { + target: { + type: row.type, + id: row.id, + title: isReply ? '' : (label ?? ''), + parent: isReply && label ? { type: null, title: label } : null, + href: null, + isDraft: false, + deleted: true, + }, + owner: owners.find((owner) => owner.id === ownerId) ?? null, + } +} + +/** + * Title, link and owner of a reported content that still exists. + */ +function describe( + row: Row, + loaded: { articles: Article[]; threads: Thread[]; discussions: Discussion[]; replies: Reply[] } +): Described | null { + const base = { type: row.type, id: row.id, parent: null, isDraft: false, deleted: false } + switch (row.type) { + case 'article': { + const article = loaded.articles.find((item) => item.id === row.id) + if (!article) return null + return { + target: { + ...base, + title: article.title, + href: `/articles/${article.slug}`, + isDraft: !article.isPublished, + }, + owner: article.author ?? null, + } + } + case 'thread': { + const thread = loaded.threads.find((item) => item.id === row.id) + if (!thread) return null + return { + target: { ...base, title: thread.title, href: `/forum/${thread.slug}` }, + owner: thread.author ?? null, + } + } + case 'discussion': { + const discussion = loaded.discussions.find((item) => item.id === row.id) + if (!discussion) return null + return { + target: { ...base, title: discussion.title, href: `/discussions/${discussion.slug}` }, + owner: discussion.author ?? null, + } + } + case 'reply': { + const reply = loaded.replies.find((item) => item.id === row.id) + if (!reply) return null + const position = Number(reply.$extras.position ?? 0) + const anchor = `#reponse-${reply.id}` + const excerpt = plainExcerpt(reply.body, 280) || 'Réponse composée uniquement de code.' + let parent: ReportQueueTarget['parent'] = null + let href = anchor + let isDraft = false + if (reply.thread) { + const page = Math.floor(position / THREAD_REPLIES_PER_PAGE) + 1 + parent = { type: 'thread', title: reply.thread.title } + href = `/forum/${reply.thread.slug}${page > 1 ? `?page=${page}` : ''}${anchor}` + } else if (reply.discussion) { + const page = Math.floor(position / DISCUSSION_REPLIES_PER_PAGE) + 1 + parent = { type: 'discussion', title: reply.discussion.title } + href = `/discussions/${reply.discussion.slug}${page > 1 ? `?page=${page}` : ''}${anchor}` + } else if (reply.article) { + parent = { type: 'article', title: reply.article.title } + href = `/articles/${reply.article.slug}${anchor}` + isDraft = !reply.article.isPublished + } + return { + target: { ...base, title: excerpt, parent, href, isDraft }, + owner: reply.author ?? null, + } + } + } +} diff --git a/app/controllers/admin/tags_controller.ts b/app/controllers/admin/tags_controller.ts new file mode 100644 index 0000000..af5820f --- /dev/null +++ b/app/controllers/admin/tags_controller.ts @@ -0,0 +1,61 @@ +import type { HttpContext } from '@adonisjs/core/http' +import Tag from '#models/tag' +import TagTransformer from '#transformers/tag_transformer' +import { tagValidator } from '#validators/admin_validator' +import { uniqueSlug } from '#services/slug' + +export default class AdminTagsController { + /** + * GET /admin/tags + */ + async index({ inertia }: HttpContext) { + const tags = await Tag.query().withCount('articles').withCount('discussions') + // French alphabetical order ("Événements" next to "DevOps", not after "Vue"). + tags.sort((a, b) => a.name.localeCompare(b.name, 'fr', { sensitivity: 'base' })) + + return inertia.render('admin/tags', { + tags: TagTransformer.transform(tags), + }) + } + + /** + * POST /admin/tags + */ + async store({ request, response, session }: HttpContext) { + const data = await request.validateUsing(tagValidator, { meta: {} }) + const tag = await Tag.create({ + name: data.name, + slug: data.slug ?? (await uniqueSlug('tags', data.name)), + description: data.description, + }) + session.flash('success', `Tag « ${tag.name} » créé.`) + return response.redirect().toPath('/admin/tags') + } + + /** + * PUT /admin/tags/:id — the slug only changes when edited explicitly + * (it appears in public URLs such as /articles?tag=…). + */ + async update({ params, request, response, session }: HttpContext) { + const tag = await Tag.findOrFail(params.id) + const data = await request.validateUsing(tagValidator, { meta: { id: tag.id } }) + tag.merge({ + name: data.name, + slug: data.slug ?? tag.slug, + description: data.description, + }) + await tag.save() + session.flash('success', `Tag « ${tag.name} » mis à jour.`) + return response.redirect().toPath('/admin/tags') + } + + /** + * DELETE /admin/tags/:id — content keeps existing, only the label goes. + */ + async destroy({ params, response, session }: HttpContext) { + const tag = await Tag.findOrFail(params.id) + await tag.delete() + session.flash('success', `Tag « ${tag.name} » supprimé.`) + return response.redirect().toPath('/admin/tags') + } +} diff --git a/app/controllers/article_actions_controller.ts b/app/controllers/article_actions_controller.ts new file mode 100644 index 0000000..67461eb --- /dev/null +++ b/app/controllers/article_actions_controller.ts @@ -0,0 +1,116 @@ +import type { HttpContext } from '@adonisjs/core/http' +import { DateTime } from 'luxon' +import { errors as lucidErrors } from '@adonisjs/lucid' +import Article from '#models/article' +import Like from '#models/like' +import type User from '#models/user' + +/** + * Load an article the user may manage (owner or moderator). Drafts of + * other people stay invisible (404); published articles get a flash error. + */ +async function managedArticle(slug: string, user: User) { + const article = await Article.findByOrFail('slug', slug) + if (await user.canManageContent(article.userId)) return { article, allowed: true as const } + if (!article.isPublished) throw new lucidErrors.E_ROW_NOT_FOUND() + return { article, allowed: false as const } +} + +/** + * One-click actions on an article: like, publish / unpublish, feature. + */ +export default class ArticleActionsController { + /** + * POST /articles/:slug/like — toggle the viewer's like. + */ + async like({ params, auth, response, session }: HttpContext) { + const user = auth.user! + const article = await Article.query() + .where('slug', params.slug) + .withScopes((scopes) => scopes.published()) + .firstOrFail() + + if (article.userId === user.id) { + session.flash('error', 'Vous ne pouvez pas aimer votre propre article.') + return response.redirect().back() + } + + const existing = await Like.query() + .where('user_id', user.id) + .where('article_id', article.id) + .first() + if (existing) { + await existing.delete() + } else { + try { + await Like.create({ userId: user.id, articleId: article.id }) + } catch (error) { + // Double click: the unique (user_id, article_id) index already holds it. + if ((error as { code?: string }).code !== '23505') throw error + } + } + return response.redirect().back() + } + + /** + * POST /articles/:slug/publish — publish a draft right away. + */ + async publish({ params, auth, response, session }: HttpContext) { + const { article, allowed } = await managedArticle(params.slug, auth.user!) + if (!allowed || article.userId !== auth.user!.id) { + session.flash('error', 'Seul l’auteur de cet article peut le publier.') + return response.redirect().back() + } + + if (!article.isPublished) { + article.publishedAt = DateTime.now() + await article.save() + session.flash('success', 'Article publié. Merci pour ce partage !') + } + return response.redirect().toPath(`/articles/${article.slug}`) + } + + /** + * POST /articles/:slug/unpublish — back to draft (and off the front page). + */ + async unpublish({ params, auth, response, session }: HttpContext) { + const { article, allowed } = await managedArticle(params.slug, auth.user!) + if (!allowed) { + session.flash('error', 'Seul l’auteur de cet article peut le dépublier.') + return response.redirect().back() + } + + if (article.publishedAt) { + article.publishedAt = null + article.featuredAt = null + await article.save() + } + session.flash('success', 'Article repassé en brouillon : il n’est plus visible publiquement.') + return response.redirect().back() + } + + /** + * POST /articles/:slug/feature — moderators toggle "à la une". + */ + async feature({ params, auth, response, session }: HttpContext) { + const user = auth.user! + if (!user.isModerator) { + session.flash('error', 'Action réservée à l’équipe de modération.') + return response.redirect().back() + } + + const article = await Article.findByOrFail('slug', params.slug) + if (!article.isPublished) { + session.flash('error', 'Publiez l’article avant de le mettre à la une.') + return response.redirect().back() + } + + // Query update: featuring is editorial, not a content change (keeps updated_at). + const featuring = article.featuredAt === null + await Article.query() + .where('id', article.id) + .update({ featured_at: featuring ? DateTime.now().toSQL() : null }) + session.flash('success', featuring ? 'Article mis à la une.' : 'Article retiré de la une.') + return response.redirect().back() + } +} diff --git a/app/controllers/article_comments_controller.ts b/app/controllers/article_comments_controller.ts new file mode 100644 index 0000000..1122106 --- /dev/null +++ b/app/controllers/article_comments_controller.ts @@ -0,0 +1,26 @@ +import type { HttpContext } from '@adonisjs/core/http' +import Article from '#models/article' +import { replyValidator } from '#validators/reply_validator' +import { createReply } from '#services/reply_service' + +/** + * Comments on articles are replies (edit / delete / like go through the + * shared /replies routes). Only published articles accept comments. + */ +export default class ArticleCommentsController { + /** + * POST /articles/:slug/comments + */ + async store({ params, request, auth, response, session }: HttpContext) { + const article = await Article.query() + .where('slug', params.slug) + .withScopes((scopes) => scopes.published()) + .firstOrFail() + + const { body } = await request.validateUsing(replyValidator) + const reply = await createReply({ type: 'article', id: article.id }, auth.user!, body) + + session.flash('success', 'Commentaire publié.') + return response.redirect().toPath(`/articles/${article.slug}#reponse-${reply.id}`) + } +} diff --git a/app/controllers/articles_controller.ts b/app/controllers/articles_controller.ts index 7a5d845..6c4fe40 100644 --- a/app/controllers/articles_controller.ts +++ b/app/controllers/articles_controller.ts @@ -1,48 +1,360 @@ -import { HttpContext } from '@adonisjs/core/http' -import { articleValidator } from '#validators/article_validator' -import Article from '#models/article' +import { markSubjectRead } from '#services/notifications' +import type { HttpContext } from '@adonisjs/core/http' import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import { errors as lucidErrors } from '@adonisjs/lucid' +import Article from '#models/article' +import Tag from '#models/tag' +import Like from '#models/like' +import Reply from '#models/reply' +import type User from '#models/user' +import ArticleTransformer from '#transformers/article_transformer' +import TagTransformer from '#transformers/tag_transformer' +import UserTransformer from '#transformers/user_transformer' +import ReplyTransformer from '#transformers/reply_transformer' +import { articleValidator } from '#validators/article_validator' +import { plainExcerpt, readingMinutes, renderMarkdown } from '#services/markdown' +import { uniqueSlug } from '#services/slug' +import { withReplyMeta } from '#services/reply_service' + +const PER_PAGE = 15 +const SEEN_SESSION_KEY = 'articles_seen' + +type ArticleSort = 'recents' | 'populaires' +type ArticlePayload = Awaited> + +/** + * Escape LIKE wildcards so a search for "100%" stays literal. + */ +function likePattern(term: string) { + return `%${term.replace(/[\\%_]/g, (char) => `\\${char}`)}%` +} + +/** + * Excerpt generated from the body when the author leaves it blank + * (headings are skipped: they read badly once flattened into a sentence). + */ +function autoExcerpt(body: string) { + return plainExcerpt(body.replace(/^#{1,6}\s.*$/gm, '')) +} + +/** + * Copy validated form data onto the model: rendered HTML, reading time, + * and an excerpt generated from the body when the author left it blank. + */ +async function fillArticle(article: Article, data: ArticlePayload) { + article.title = data.title + article.body = data.body + article.bodyHtml = await renderMarkdown(data.body) + article.readingMinutes = readingMinutes(data.body) + article.excerpt = data.excerpt ?? autoExcerpt(data.body) + article.coverUrl = data.coverUrl ?? null +} + +/** + * Only keep tag ids that exist (unknown ids are silently dropped). + */ +async function existingTagIds(ids: number[] | undefined) { + if (!ids?.length) return [] + const tags = await Tag.query() + .whereIn('id', [...new Set(ids)]) + .select('id') + return tags.map((tag) => tag.id) +} + +async function saveWithTags(article: Article, tagIds: number[]) { + await db.transaction(async (trx) => { + article.useTransaction(trx) + await article.save() + await article.related('tags').sync(tagIds, true, trx) + }) +} + +/** + * "À lire ensuite": up to 3 published articles sharing the most tags with + * "article", completed with the latest ones. + */ +async function relatedArticles(article: Article) { + const base = () => + Article.query() + .withScopes((scopes) => scopes.published()) + .whereNot('id', article.id) + .preload('author') + .preload('tags') + + const tagIds = article.tags.map((tag) => tag.id) + let related: Article[] = [] + if (tagIds.length) { + related = await base() + .whereHas('tags', (query) => query.whereIn('tags.id', tagIds)) + .orderByRaw( + `(select count(*) from article_tag where article_tag.article_id = articles.id and article_tag.tag_id in (${tagIds.map(() => '?').join(', ')})) desc`, + tagIds + ) + .orderBy('published_at', 'desc') + .limit(3) + } + if (related.length < 3) { + const latest = await base() + .whereNotIn( + 'id', + related.map((item) => item.id) + ) + .orderBy('published_at', 'desc') + .limit(3 - related.length) + related = [...related, ...latest] + } + return related +} + +/** + * Drafts (unpublished or scheduled) only exist for their author and the + * moderators; everyone else gets a 404. + */ +function assertVisible(article: Article, viewer: User | undefined) { + if (article.isPublished) return + if (viewer && viewer.canSeeDraftsOf(article.userId)) return + throw new lucidErrors.E_ROW_NOT_FOUND() +} export default class ArticlesController { + /** + * GET /articles — published articles, filters: ?tag= ?q= ?sort= ?page= + */ async index({ inertia, request }: HttpContext) { - const page = request.input('page', 1) - const articles = await Article.query() + const qs = request.qs() + const page = Math.max(1, Number.parseInt(String(qs.page ?? '1'), 10) || 1) + const search = typeof qs.q === 'string' ? qs.q.trim().slice(0, 100) : '' + const sort: ArticleSort = qs.sort === 'populaires' ? 'populaires' : 'recents' + const tagSlug = typeof qs.tag === 'string' ? qs.tag.trim().toLowerCase().slice(0, 60) : '' + const unfiltered = !tagSlug && !search && sort === 'recents' + + const [tags, featured] = await Promise.all([ + Tag.query() + .withCount('articles', (query) => { + query + .whereNotNull('articles.published_at') + .where('articles.published_at', '<=', DateTime.now().toSQL()!) + }) + .orderBy('name', 'asc'), + unfiltered + ? Article.query() + .withScopes((scopes) => scopes.published()) + .whereNotNull('featured_at') + .preload('author') + .preload('tags') + .withCount('likes') + .withCount('comments') + .orderBy('featured_at', 'desc') + .first() + : null, + ]) + + const query = Article.query() + .withScopes((scopes) => scopes.published()) .preload('author') - .where('is_published', true) - .orderBy('published_at', 'desc') - .paginate(page, 10) + .preload('tags') + .withCount('likes') + .withCount('comments') + + if (featured) query.whereNot('articles.id', featured.id) + if (tagSlug) query.whereHas('tags', (tagQuery) => tagQuery.where('tags.slug', tagSlug)) + if (search) { + const pattern = likePattern(search) + query.where((where) => where.whereILike('title', pattern).orWhereILike('excerpt', pattern)) + } + if (sort === 'populaires') { + query.orderBy('likes_count', 'desc').orderBy('views_count', 'desc') + } + query.orderBy('published_at', 'desc').orderBy('id', 'desc') + + const paginator = await query.paginate(page, PER_PAGE) + const indexedTags = tags + .filter((tag) => Number(tag.$extras.articles_count) > 0) + .sort((a, b) => Number(b.$extras.articles_count) - Number(a.$extras.articles_count)) + const activeTag = tagSlug ? (tags.find((tag) => tag.slug === tagSlug) ?? null) : null return inertia.render('articles/index', { - articles: articles.toJSON(), + articles: ArticleTransformer.paginate(paginator.all(), paginator.getMeta()), + featured: featured ? ArticleTransformer.transform(featured) : null, + total: paginator.total + (featured ? 1 : 0), + tags: TagTransformer.transform(indexedTags), + activeTag: activeTag ? TagTransformer.transform(activeTag) : null, + filters: { q: search, sort, tag: tagSlug || null }, }) } + /** + * GET /articles/:slug + */ + async show({ params, inertia, auth, session }: HttpContext) { + const viewer = auth.user + const article = await Article.query() + .where('slug', params.slug) + .preload('author') + .preload('tags', (query) => query.orderBy('name', 'asc')) + .withCount('likes') + .withCount('comments') + .firstOrFail() + + assertVisible(article, viewer) + if (viewer) await markSubjectRead(viewer.id, { articleId: article.id }) + + /** + * Count one view per session (likes and comments redirect back here), + * never the author's own visits, never drafts. + */ + if (article.isPublished && viewer?.id !== article.userId) { + const seen = session.get(SEEN_SESSION_KEY, []) as number[] + if (!seen.includes(article.id)) { + await Article.query().where('id', article.id).increment('views_count', 1) + article.viewsCount += 1 + session.put(SEEN_SESSION_KEY, [...seen.slice(-29), article.id]) + } + } + + // withReplyMeta is a query modifier (Lucid's .apply() runs scopes instead). + const commentsQuery = Reply.query().where('article_id', article.id) + withReplyMeta(viewer)(commentsQuery) + + const [comments, related, liked, authorTotals] = await Promise.all([ + commentsQuery, + relatedArticles(article), + viewer + ? Like.query().where('article_id', article.id).where('user_id', viewer.id).first() + : null, + db + .from('articles') + .where('user_id', article.userId) + .whereNotNull('published_at') + .where('published_at', '<=', DateTime.now().toSQL()!) + .count('* as total') + .first(), + ]) + + return inertia.render('articles/[slug]', { + article: ArticleTransformer.transform(article).useVariant('forDetail'), + author: UserTransformer.transform(article.author).useVariant('forProfile'), + authorArticlesCount: Number(authorTotals?.total ?? 0), + comments: ReplyTransformer.transform(comments), + related: ArticleTransformer.transform(related), + likedByMe: Boolean(liked), + canManage: Boolean(viewer && (await viewer.canManageContent(article.userId))), + }) + } + + /** + * GET /articles/nouveau + */ async create({ inertia }: HttpContext) { - return inertia.render('articles/create') + const tags = await Tag.query().orderBy('id', 'asc') + return inertia.render('articles/create', { tags: TagTransformer.transform(tags) }) } - async store({ request, auth, response }: HttpContext) { - const data = await articleValidator.validate(request.all()) + /** + * POST /articles + */ + async store({ request, auth, response, session }: HttpContext) { + const user = auth.user! + const data = await request.validateUsing(articleValidator) + const article = new Article() + article.userId = user.id + article.slug = await uniqueSlug('articles', data.title) + await fillArticle(article, data) + if (data.publish) article.publishedAt = DateTime.now() - article.title = data.title - article.content = data.content - article.excerpt = data.excerpt - article.isPublished = data.isPublished || false - article.authorId = auth.user!.id - if (data.isPublished) { + await saveWithTags(article, await existingTagIds(data.tags)) + + session.flash( + 'success', + data.publish + ? 'Article publié. Merci pour ce partage !' + : 'Brouillon enregistré. Il n’est visible que par vous.' + ) + return response.redirect().toPath(`/articles/${article.slug}`) + } + + /** + * GET /articles/:slug/modifier + */ + async edit({ params, inertia, auth, response, session }: HttpContext) { + const user = auth.user! + const article = await Article.query().where('slug', params.slug).preload('tags').firstOrFail() + assertVisible(article, user) + if (!(await user.canManageContent(article.userId))) { + session.flash('error', 'Seul l’auteur de cet article peut le modifier.') + return response.redirect().toPath(`/articles/${article.slug}`) + } + + const tags = await Tag.query().orderBy('id', 'asc') + return inertia.render('articles/edit', { + article: ArticleTransformer.transform(article).useVariant('forEdit'), + excerptIsAuto: article.excerpt === autoExcerpt(article.body), + tags: TagTransformer.transform(tags), + }) + } + + /** + * PUT /articles/:slug + */ + async update({ params, request, auth, response, session }: HttpContext) { + const user = auth.user! + const article = await Article.findByOrFail('slug', params.slug) + assertVisible(article, user) + if (!(await user.canManageContent(article.userId))) { + session.flash('error', 'Seul l’auteur de cet article peut le modifier.') + return response.redirect().toPath(`/articles/${article.slug}`) + } + + const data = await request.validateUsing(articleValidator) + const wasPublic = article.isPublished + + /** + * The URL only follows the title while nobody can have seen or shared + * it: never published (and never viewed, since views are only counted + * on published articles). + */ + const everPublic = wasPublic || article.viewsCount > 0 + if (data.title !== article.title && !everPublic) { + article.slug = await uniqueSlug('articles', data.title, article.id) + } + + await fillArticle(article, data) + if (data.publish && !wasPublic) { article.publishedAt = DateTime.now() + } else if (!data.publish && article.publishedAt) { + article.publishedAt = null + article.featuredAt = null } - await article.generateSlug() - await article.save() + await saveWithTags(article, await existingTagIds(data.tags)) - return response.redirect().toRoute('articles.show', { slug: article.slug }) + let message = 'Brouillon enregistré.' + if (data.publish) + message = wasPublic + ? 'Modifications enregistrées.' + : 'Article publié. Merci pour ce partage !' + else if (wasPublic) + message = 'Article repassé en brouillon : il n’est plus visible publiquement.' + session.flash('success', message) + return response.redirect().toPath(`/articles/${article.slug}`) } - async show({ inertia, params }: HttpContext) { - const article = await Article.query().where('slug', params.slug).preload('author').firstOrFail() + /** + * DELETE /articles/:slug — comments, likes and tag links cascade. + */ + async destroy({ params, auth, response, session }: HttpContext) { + const user = auth.user! + const article = await Article.findByOrFail('slug', params.slug) + assertVisible(article, user) + if (!(await user.canManageContent(article.userId))) { + session.flash('error', 'Vous ne pouvez pas supprimer cet article.') + return response.redirect().toPath(`/articles/${article.slug}`) + } - return inertia.render('articles/[slug]', { article }) + await article.delete() + session.flash('success', 'Article supprimé.') + return response.redirect().toPath('/articles') } } diff --git a/app/controllers/auth/github_controller.ts b/app/controllers/auth/github_controller.ts index 4a4d0bc..bf34366 100644 --- a/app/controllers/auth/github_controller.ts +++ b/app/controllers/auth/github_controller.ts @@ -1,62 +1,104 @@ -import { HttpContext } from '@adonisjs/core/http' +import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware' +import { DateTime } from 'luxon' +import string from '@adonisjs/core/helpers/string' +import type { HttpContext } from '@adonisjs/core/http' import User from '#models/user' -import type { GithubDriver } from '@adonisjs/ally/drivers/github' +import GithubOAuth from '#services/github_oauth' +import { githubEnabled } from '#config/ally' +import { RESERVED_USERNAMES } from '#validators/register_validator' export default class GithubController { - async redirect({ ally }: HttpContext) { - return (ally.use('github') as GithubDriver).redirect() + async redirect(ctx: HttpContext) { + if (!githubEnabled()) { + ctx.session.flash('error', 'La connexion avec GitHub n’est pas encore activée.') + return ctx.response.redirect().toRoute('login') + } + return ctx.response.redirect(new GithubOAuth(ctx).redirectUrl()) } - async callback({ ally, auth, response }: HttpContext) { - const github = ally.use('github') as GithubDriver + async callback(ctx: HttpContext) { + const { auth, response, session } = ctx + if (!githubEnabled()) return response.redirect().toRoute('login') - /** - * User has explicitly cancelled the login flow - */ - if (github.accessDenied()) { + const profile = await new GithubOAuth(ctx).user().catch(() => null) + if (!profile) { + session.flash('error', 'Connexion GitHub annulée ou expirée. Réessayez.') return response.redirect().toRoute('login') } - /** - * OAuth state verification failed. This happens when the - * CSRF cookie gets expired or request is forged - */ - if (github.stateMisMatch()) { - return response.redirect().toRoute('login') + let user = await User.findBy('githubId', profile.id) + + if (!user && profile.email) { + // Link the GitHub account to an existing account with the same e-mail. + const existing = await User.findBy('email', profile.email.toLowerCase()) + if (existing && !existing.emailVerifiedAt) { + // Local e-mails are not verified: auto-linking would let anyone who + // registered with someone else's address capture their GitHub login. + session.flash( + 'error', + 'Un compte existe déjà avec cette adresse e-mail. Connectez-vous avec votre mot de passe.' + ) + return response.redirect().toRoute('login') + } + if (existing) { + existing.githubId = profile.id + existing.githubUsername = profile.login + existing.avatarUrl = existing.avatarUrl ?? profile.avatarUrl + await existing.save() + user = existing + } } - /** - * GitHub responded with some error - */ - if (github.hasError()) { + if (!user) { + if (!profile.email) { + session.flash( + 'error', + 'Votre compte GitHub n’expose aucune adresse e-mail vérifiée. Créez un compte avec votre e-mail.' + ) + return response.redirect().toRoute('register') + } + user = await User.create({ + githubId: profile.id, + githubUsername: profile.login, + username: await this.availableUsername(profile.login), + name: profile.name, + email: profile.email.toLowerCase(), + avatarUrl: profile.avatarUrl, + bio: profile.bio?.slice(0, 280) ?? null, + location: profile.location?.slice(0, 100) ?? null, + websiteUrl: + profile.blog && /^https?:\/\//.test(profile.blog) ? profile.blog.slice(0, 255) : null, + twitterUsername: profile.twitterUsername, + password: null, + role: 'member', + // GitHub only returns verified addresses. + emailVerifiedAt: DateTime.now(), + }) + session.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`) + } else { + session.flash('success', `Bon retour, ${user.displayName} !`) + } + + if (user.isBanned) { + session.flash('error', 'Ce compte a été suspendu.') return response.redirect().toRoute('login') } - /** - * Get user details from GitHub - */ - const githubUser = await github.user() - - /** - * Find or create user by GitHub ID - */ - const user = await User.firstOrCreate( - { - githubId: githubUser.id, - }, - { - username: githubUser.nickName, - name: githubUser.name, - email: githubUser.email!, - avatar: githubUser.avatarUrl, - githubId: githubUser.id, - } - ) + await auth.use('web').login(user, true) + session.put(SESSION_VERSION_KEY, user.sessionVersion) + return response.redirect().toPath('/dashboard') + } - /** - * Login user using the web guard - */ - await auth.use('web').login(user) - return response.redirect().toRoute('dashboard') + private async availableUsername(login: string) { + const base = + login + .toLowerCase() + .replace(/[^a-z0-9_-]/g, '') + .slice(0, 24) || 'membre' + let candidate = RESERVED_USERNAMES.includes(base) ? `${base}-dev` : base + while (await User.findBy('username', candidate)) { + candidate = `${base}-${string.random(4).toLowerCase()}` + } + return candidate } } diff --git a/app/controllers/auth/login_controller.ts b/app/controllers/auth/login_controller.ts index 4778558..cceaf15 100644 --- a/app/controllers/auth/login_controller.ts +++ b/app/controllers/auth/login_controller.ts @@ -1,39 +1,45 @@ -import { loginValidator } from '#validators/login_validator' -import { HttpContext } from '@adonisjs/core/http' +import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware' import User from '#models/user' -import { errors } from '@adonisjs/auth' +import { loginValidator } from '#validators/login_validator' +import type { HttpContext } from '@adonisjs/core/http' +import { safeRedirectPath } from '#services/safe_redirect' export default class LoginController { - async show({ inertia }: HttpContext) { - return inertia.render('auth/login') + async show({ inertia, request }: HttpContext) { + return inertia.render('auth/login', { + redirect: safeRedirectPath(request.input('redirect'), ''), + }) } - async login({ request, auth, response, session }: HttpContext) { - try { - // Validate the request data - const data = await loginValidator.validate(request.all()) - - // Attempt to verify credentials - const user = await User.verifyCredentials(data.email, data.password) - - // Login the user - await auth.use('web').login(user, data.remember) + async store({ request, auth, response, session }: HttpContext) { + const { login, password, remember } = await request.validateUsing(loginValidator) - return response.redirect().toRoute('dashboard') - } catch (error) { - if (error instanceof errors.E_INVALID_CREDENTIALS) { - session.flash('errors', { form: 'Invalid credentials' }) - return response.redirect().back() - } + let user: User + try { + user = await User.verifyCredentials(login.toLowerCase(), password) + } catch { + session.flashExcept(['password']) + session.flash('inputErrorsBag', { login: ['Identifiants incorrects.'] }) + return response.redirect().back() + } - // Handle other errors - session.flash('errors', { form: 'An error occurred during login' }) + if (user.isBanned) { + session.flash( + 'error', + 'Ce compte a été suspendu. Contactez l’équipe si vous pensez à une erreur.' + ) return response.redirect().back() } + + await auth.use('web').login(user, Boolean(remember)) + session.put(SESSION_VERSION_KEY, user.sessionVersion) + session.flash('success', `Bon retour, ${user.displayName} !`) + return response.redirect().toPath(safeRedirectPath(request.input('redirect'))) } - async logout({ auth, response }: HttpContext) { + async destroy({ auth, response, session }: HttpContext) { await auth.use('web').logout() - return response.redirect().toRoute('login') + session.flash('success', 'Vous êtes déconnecté. À bientôt !') + return response.redirect().toRoute('home') } } diff --git a/app/controllers/auth/register_controller.ts b/app/controllers/auth/register_controller.ts index f6d4857..e2ac813 100644 --- a/app/controllers/auth/register_controller.ts +++ b/app/controllers/auth/register_controller.ts @@ -1,18 +1,20 @@ -import { HttpContext } from '@adonisjs/core/http' +import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware' import User from '#models/user' import { registerValidator } from '#validators/register_validator' +import type { HttpContext } from '@adonisjs/core/http' export default class RegisterController { async show({ inertia }: HttpContext) { - return inertia.render('auth/register') + return inertia.render('auth/register', {}) } - async store({ request, auth, response }: HttpContext) { - const data = await registerValidator.validate(request.all()) + async store({ request, response, auth, session }: HttpContext) { + const { name, username, email, password } = await request.validateUsing(registerValidator) + const user = await User.create({ name, username, email, password, role: 'member' }) - const user = await User.create(data) await auth.use('web').login(user) - - return response.redirect().toRoute('dashboard') + session.put(SESSION_VERSION_KEY, user.sessionVersion) + session.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`) + return response.redirect().toPath('/dashboard') } } diff --git a/app/controllers/dashboard_controller.ts b/app/controllers/dashboard_controller.ts new file mode 100644 index 0000000..91f1d38 --- /dev/null +++ b/app/controllers/dashboard_controller.ts @@ -0,0 +1,94 @@ +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' +import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Reply from '#models/reply' +import ArticleTransformer from '#transformers/article_transformer' +import ThreadTransformer from '#transformers/thread_transformer' +import DiscussionTransformer from '#transformers/discussion_transformer' +import { replySummary, withReplyParents } from '#controllers/profile_controller' + +export default class DashboardController { + /** + * GET /dashboard — the signed-in member's workspace. + */ + async index({ auth, inertia }: HttpContext) { + const user = auth.getUserOrFail() + + const [statsRow, articles, threads, discussions, activity] = await Promise.all([ + db + .rawQuery( + `select + (select count(*) from articles where user_id = :id and published_at is not null and published_at <= now()) as published, + (select count(*) from articles where user_id = :id and (published_at is null or published_at > now())) as drafts, + (select coalesce(sum(views_count), 0) from articles where user_id = :id) as views, + (select count(*) from threads where user_id = :id) as questions, + (select count(*) from threads where user_id = :id and solution_reply_id is null) as unsolved, + (select count(*) from discussions where user_id = :id) as discussions, + (select count(*) from replies where user_id = :id) as replies, + (select count(*) from likes l join articles a on a.id = l.article_id where a.user_id = :id) + + (select count(*) from likes l join replies r on r.id = l.reply_id where r.user_id = :id) as likes`, + { id: user.id } + ) + .then((result) => result.rows[0]), + + // Drafts first, then the latest publications. + Article.query() + .where('user_id', user.id) + .preload('tags') + .withCount('likes') + .withCount('comments') + .orderByRaw('(published_at is null or published_at > now()) desc') + .orderByRaw('coalesce(published_at, updated_at, created_at) desc') + .limit(8), + + // Questions still waiting for a solution come first. + Thread.query() + .where('user_id', user.id) + .preload('channel') + .orderByRaw('(solution_reply_id is null) desc') + .orderBy('last_activity_at', 'desc') + .limit(6), + + Discussion.query() + .where('user_id', user.id) + .preload('tags') + .orderBy('last_activity_at', 'desc') + .limit(5), + + // Latest replies written by others on my threads, discussions and articles. + withReplyParents(Reply.query()) + .preload('author') + .whereNot('user_id', user.id) + .where((query) => { + query + .whereIn('thread_id', db.from('threads').select('id').where('user_id', user.id)) + .orWhereIn( + 'discussion_id', + db.from('discussions').select('id').where('user_id', user.id) + ) + .orWhereIn('article_id', db.from('articles').select('id').where('user_id', user.id)) + }) + .orderBy('created_at', 'desc') + .limit(10), + ]) + + return inertia.render('dashboard/index', { + stats: { + published: Number(statsRow.published), + drafts: Number(statsRow.drafts), + views: Number(statsRow.views), + questions: Number(statsRow.questions), + unsolved: Number(statsRow.unsolved), + discussions: Number(statsRow.discussions), + replies: Number(statsRow.replies), + likes: Number(statsRow.likes), + }, + articles: ArticleTransformer.transform(articles), + threads: ThreadTransformer.transform(threads), + discussions: DiscussionTransformer.transform(discussions), + activity: activity.map((reply) => replySummary(reply, { withAuthor: true })), + }) + } +} diff --git a/app/controllers/discussion_actions_controller.ts b/app/controllers/discussion_actions_controller.ts new file mode 100644 index 0000000..2c06a43 --- /dev/null +++ b/app/controllers/discussion_actions_controller.ts @@ -0,0 +1,81 @@ +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' +import Discussion from '#models/discussion' +import { replyValidator } from '#validators/reply_validator' +import { createReply } from '#services/reply_service' +import { DISCUSSION_REPLIES_PER_PAGE } from '#controllers/discussions_controller' + +/** + * Replying to a discussion and moderation toggles (pin / lock). + */ +export default class DiscussionActionsController { + /** + * POST /discussions/:slug/replies + */ + async reply({ params, request, auth, response, session }: HttpContext) { + const user = auth.user! + const discussion = await Discussion.findByOrFail('slug', params.slug) + if (discussion.isLocked && !user.isModerator) { + session.flash( + 'error', + 'Cette discussion est verrouillée : elle n’accepte plus de nouvelles réponses.' + ) + return response.redirect().toPath(`/discussions/${discussion.slug}`) + } + + const { body } = await request.validateUsing(replyValidator) + const reply = await createReply({ type: 'discussion', id: discussion.id }, user, body) + + const total = discussion.repliesCount + 1 + const page = + total > DISCUSSION_REPLIES_PER_PAGE ? Math.ceil(total / DISCUSSION_REPLIES_PER_PAGE) : 1 + session.flash('success', 'Réponse publiée.') + return response + .redirect() + .toPath( + `/discussions/${discussion.slug}${page > 1 ? `?page=${page}` : ''}#reponse-${reply.id}` + ) + } + + /** + * POST /discussions/:slug/pin — moderators only, toggles. + */ + async togglePin({ params, auth, response, session }: HttpContext) { + const discussion = await Discussion.findByOrFail('slug', params.slug) + if (!auth.user!.isModerator) { + session.flash('error', 'Action réservée aux modérateurs.') + return response.redirect().back() + } + const pinned = discussion.pinnedAt === null + await db + .from('discussions') + .where('id', discussion.id) + .update({ pinned_at: pinned ? new Date() : null }) + session.flash( + 'success', + pinned ? 'Discussion épinglée en tête de liste.' : 'Discussion désépinglée.' + ) + return response.redirect().back() + } + + /** + * POST /discussions/:slug/lock — moderators only, toggles. + */ + async toggleLock({ params, auth, response, session }: HttpContext) { + const discussion = await Discussion.findByOrFail('slug', params.slug) + if (!auth.user!.isModerator) { + session.flash('error', 'Action réservée aux modérateurs.') + return response.redirect().back() + } + const locked = discussion.lockedAt === null + await db + .from('discussions') + .where('id', discussion.id) + .update({ locked_at: locked ? new Date() : null }) + session.flash( + 'success', + locked ? 'Discussion verrouillée : plus de nouvelles réponses.' : 'Discussion déverrouillée.' + ) + return response.redirect().back() + } +} diff --git a/app/controllers/discussions_controller.ts b/app/controllers/discussions_controller.ts new file mode 100644 index 0000000..2da155b --- /dev/null +++ b/app/controllers/discussions_controller.ts @@ -0,0 +1,363 @@ +import { markSubjectRead } from '#services/notifications' +import type { HttpContext } from '@adonisjs/core/http' +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import { errors as lucidErrors } from '@adonisjs/lucid' +import Discussion from '#models/discussion' +import Tag from '#models/tag' +import Reply from '#models/reply' +import User from '#models/user' +import DiscussionTransformer from '#transformers/discussion_transformer' +import TagTransformer from '#transformers/tag_transformer' +import ReplyTransformer from '#transformers/reply_transformer' +import UserTransformer from '#transformers/user_transformer' +import { discussionValidator } from '#validators/discussion_validator' +import { renderMarkdown } from '#services/markdown' +import { uniqueSlug } from '#services/slug' +import { withReplyMeta } from '#services/reply_service' + +const PER_PAGE = 20 +export const DISCUSSION_REPLIES_PER_PAGE = 50 + +const SORTS = ['recentes', 'populaires', 'sans-reponse'] as const +type Sort = (typeof SORTS)[number] + +function likePattern(term: string) { + return `%${term.replace(/[\\%_]/g, (char) => `\\${char}`)}%` +} + +function toPage(value: unknown) { + const page = Number.parseInt(String(value ?? '1'), 10) + return Number.isFinite(page) && page > 0 ? page : 1 +} + +/** + * One view per visitor session (see ThreadsController). + */ +function isFirstView(session: HttpContext['session'], key: string) { + const seen: string[] = session.get('seen_content', []) + if (seen.includes(key)) return false + session.put('seen_content', [...seen.slice(-39), key]) + return true +} + +function byName(tags: Tag[]) { + return tags.sort((a, b) => a.name.localeCompare(b.name, 'fr', { sensitivity: 'base' })) +} + +/** + * Attach the latest repliers (max 4, author excluded) and the number of + * distinct participants to each discussion, in two queries for the page. + */ +async function attachParticipants(discussions: Discussion[]) { + if (!discussions.length) return + const rows: { discussion_id: number; user_id: number }[] = await db + .from('replies') + .select('discussion_id', 'user_id') + .max('created_at as last_at') + .whereIn( + 'discussion_id', + discussions.map((d) => d.id) + ) + .groupBy('discussion_id', 'user_id') + .orderBy('last_at', 'desc') + + const authors = new Map(discussions.map((d) => [d.id, d.userId])) + const latest = new Map() + const counts = new Map() + for (const row of rows) { + const discussionId = Number(row.discussion_id) + const userId = Number(row.user_id) + if (userId === authors.get(discussionId)) continue + counts.set(discussionId, (counts.get(discussionId) ?? 0) + 1) + const list = latest.get(discussionId) ?? [] + if (list.length < 4) list.push(userId) + latest.set(discussionId, list) + } + + const userIds = [...new Set([...latest.values()].flat())] + const users = userIds.length ? await User.query().whereIn('id', userIds) : [] + const byId = new Map(users.map((u) => [u.id, u])) + + for (const discussion of discussions) { + discussion.$extras.participants = (latest.get(discussion.id) ?? []) + .map((id) => byId.get(id)) + .filter(Boolean) + // + 1: the author opened the conversation. + discussion.$extras.participants_count = (counts.get(discussion.id) ?? 0) + 1 + } +} + +export default class DiscussionsController { + /** + * GET /discussions — tag index, sort, search. + */ + async index({ request, inertia }: HttpContext) { + const qs = request.qs() + const q = typeof qs.q === 'string' ? qs.q.trim().slice(0, 120) : '' + const sort: Sort = SORTS.includes(qs.sort) ? qs.sort : 'recentes' + const page = toPage(qs.page) + + // Most discussed first, then alphabetical with a French collation + // (« Événements » sorts with the E, not after « Vue »). + const allTags = await Tag.query().withCount('discussions') + const tags = allTags.sort( + (a, b) => + Number(b.$extras.discussions_count) - Number(a.$extras.discussions_count) || + a.name.localeCompare(b.name, 'fr', { sensitivity: 'base' }) + ) + + let tag: Tag | null = null + if (typeof qs.tag === 'string' && qs.tag !== '') { + tag = tags.find((t) => t.slug === qs.tag) ?? null + if (!tag) throw new lucidErrors.E_ROW_NOT_FOUND(Tag) + } + + const query = Discussion.query().preload('author').preload('tags') + if (tag) { + const tagId = tag.id + query.whereIn('id', (sub) => + sub.from('discussion_tag').select('discussion_id').where('tag_id', tagId) + ) + } + if (q) { + const pattern = likePattern(q) + query.where((sub) => sub.whereILike('title', pattern).orWhereILike('body', pattern)) + } + + if (sort === 'populaires') { + query + .orderBy('replies_count', 'desc') + .orderBy('views_count', 'desc') + .orderBy('last_activity_at', 'desc') + } else if (sort === 'sans-reponse') { + query.where('replies_count', 0).orderBy('created_at', 'desc') + } else { + query.orderByRaw('pinned_at desc nulls last').orderBy('last_activity_at', 'desc') + } + query.orderBy('id', 'desc') + + const [discussions, totals] = await Promise.all([ + query.paginate(page, PER_PAGE), + db + .rawQuery( + `select + (select count(*) from discussions)::int as discussions, + (select count(*) from replies where discussion_id is not null and created_at > now() - interval '30 days')::int as replies_month, + (select count(distinct user_id) from replies where discussion_id is not null)::int as voices` + ) + .then( + (result) => + result.rows[0] as { discussions: number; replies_month: number; voices: number } + ), + ]) + await attachParticipants(discussions.all()) + + return inertia.render('discussions/index', { + discussions: DiscussionTransformer.paginate( + discussions.all(), + discussions.getMeta() + ).useVariant('forList'), + tags: TagTransformer.transform(tags), + filters: { tag: tag?.slug ?? null, sort, q }, + stats: { + discussions: Number(totals.discussions), + repliesThisMonth: Number(totals.replies_month), + voices: Number(totals.voices), + }, + }) + } + + /** + * GET /discussions/nouvelle + */ + async create({ request, inertia }: HttpContext) { + const tags = byName(await Tag.query()) + const preselected = tags.find((t) => t.slug === request.qs().tag) + return inertia.render('discussions/create', { + tags: TagTransformer.transform(tags), + defaultTagIds: preselected ? [preselected.id] : [], + }) + } + + /** + * POST /discussions + */ + async store({ request, auth, response, session }: HttpContext) { + const data = await request.validateUsing(discussionValidator) + const discussion = new Discussion() + discussion.userId = auth.user!.id + discussion.title = data.title + discussion.body = data.body + discussion.bodyHtml = await renderMarkdown(data.body) + discussion.slug = await uniqueSlug('discussions', data.title) + discussion.lastActivityAt = DateTime.now() + + await db.transaction(async (trx) => { + discussion.useTransaction(trx) + await discussion.save() + await discussion.related('tags').sync(data.tags ?? []) + }) + + session.flash('success', 'Discussion lancée. À vous la parole !') + return response.redirect().toPath(`/discussions/${discussion.slug}`) + } + + /** + * GET /discussions/:slug + */ + async show({ params, request, auth, inertia, session }: HttpContext) { + const viewer = auth.user ?? null + const discussion = await Discussion.query() + .where('slug', params.slug) + .preload('author') + .preload('tags') + .firstOrFail() + + if (viewer) await markSubjectRead(viewer.id, { discussionId: discussion.id }) + + if (viewer?.id !== discussion.userId && isFirstView(session, `d${discussion.id}`)) { + await db.from('discussions').where('id', discussion.id).increment('views_count', 1) + discussion.viewsCount += 1 + } + + const repliesQuery = Reply.query().where('discussion_id', discussion.id) + withReplyMeta(viewer)(repliesQuery) + repliesQuery.orderBy('id', 'asc') + + let replies: Reply[] + let repliesMeta: { + total: number + perPage: number + currentPage: number + lastPage: number + } | null = null + if (discussion.repliesCount > DISCUSSION_REPLIES_PER_PAGE) { + const paginator = await repliesQuery.paginate( + toPage(request.qs().page), + DISCUSSION_REPLIES_PER_PAGE + ) + replies = paginator.all() + const meta = paginator.getMeta() + repliesMeta = { + total: Number(meta.total), + perPage: Number(meta.perPage), + currentPage: Number(meta.currentPage), + lastPage: Number(meta.lastPage), + } + } else { + replies = await repliesQuery + } + + const tagIds = discussion.tags.map((t) => t.id) + const relatedQuery = Discussion.query().whereNot('id', discussion.id).preload('author') + if (tagIds.length) { + relatedQuery.whereIn('id', (sub) => + sub.from('discussion_tag').select('discussion_id').whereIn('tag_id', tagIds) + ) + } + + const [participantRows, tagRelated] = await Promise.all([ + db + .from('replies') + .select('user_id') + .count('* as replies') + .min('created_at as first_at') + .where('discussion_id', discussion.id) + .groupBy('user_id') + .orderBy('first_at', 'asc'), + relatedQuery.orderBy('last_activity_at', 'desc').limit(5), + ]) + + // Nothing shares a tag yet: fall back to the latest conversations. + const related = tagRelated.length + ? tagRelated + : await Discussion.query() + .whereNot('id', discussion.id) + .preload('author') + .orderBy('last_activity_at', 'desc') + .limit(5) + + // The author opens the conversation: first in the participants strip. + const participantIds: number[] = [ + discussion.userId, + ...participantRows.map((row) => Number(row.user_id)).filter((id) => id !== discussion.userId), + ] + const others = + participantIds.length > 1 ? await User.query().whereIn('id', participantIds.slice(1, 16)) : [] + const participants = [discussion.author, ...others].sort( + (a, b) => participantIds.indexOf(a.id) - participantIds.indexOf(b.id) + ) + + return inertia.render('discussions/show', { + discussion: DiscussionTransformer.transform(discussion).useVariant('forDetail'), + replies: ReplyTransformer.transform(replies), + repliesMeta, + participants: UserTransformer.transform(participants), + participantsCount: participantIds.length, + related: DiscussionTransformer.transform(related), + relatedByTags: tagRelated.length > 0, + can: { + manage: Boolean(viewer && (await viewer.canManageContent(discussion.userId))), + moderate: Boolean(viewer?.isModerator), + }, + }) + } + + /** + * GET /discussions/:slug/modifier + */ + async edit({ params, auth, inertia, response, session }: HttpContext) { + const discussion = await Discussion.query() + .where('slug', params.slug) + .preload('tags') + .firstOrFail() + if (!(await auth.user!.canManageContent(discussion.userId))) { + session.flash('error', 'Vous ne pouvez pas modifier cette discussion.') + return response.redirect().toPath(`/discussions/${discussion.slug}`) + } + const tags = byName(await Tag.query()) + return inertia.render('discussions/edit', { + discussion: DiscussionTransformer.transform(discussion).useVariant('forEdit'), + tags: TagTransformer.transform(tags), + }) + } + + /** + * PUT /discussions/:slug — the slug never changes. + */ + async update({ params, request, auth, response, session }: HttpContext) { + const discussion = await Discussion.findByOrFail('slug', params.slug) + if (!(await auth.user!.canManageContent(discussion.userId))) { + session.flash('error', 'Vous ne pouvez pas modifier cette discussion.') + return response.redirect().toPath(`/discussions/${discussion.slug}`) + } + const data = await request.validateUsing(discussionValidator) + discussion.title = data.title + discussion.body = data.body + discussion.bodyHtml = await renderMarkdown(data.body) + + await db.transaction(async (trx) => { + discussion.useTransaction(trx) + await discussion.save() + await discussion.related('tags').sync(data.tags ?? []) + }) + + session.flash('success', 'Discussion mise à jour.') + return response.redirect().toPath(`/discussions/${discussion.slug}`) + } + + /** + * DELETE /discussions/:slug + */ + async destroy({ params, auth, response, session }: HttpContext) { + const discussion = await Discussion.findByOrFail('slug', params.slug) + if (!(await auth.user!.canManageContent(discussion.userId))) { + session.flash('error', 'Vous ne pouvez pas supprimer cette discussion.') + return response.redirect().toPath(`/discussions/${discussion.slug}`) + } + await discussion.delete() + session.flash('success', 'La discussion a été supprimée.') + return response.redirect().toPath('/discussions') + } +} diff --git a/app/controllers/home_controller.ts b/app/controllers/home_controller.ts index b170eeb..cba213c 100644 --- a/app/controllers/home_controller.ts +++ b/app/controllers/home_controller.ts @@ -1,18 +1,62 @@ -import { HttpContext } from '@adonisjs/core/http' +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import User from '#models/user' +import ArticleTransformer from '#transformers/article_transformer' +import ThreadTransformer from '#transformers/thread_transformer' +import DiscussionTransformer from '#transformers/discussion_transformer' +import UserTransformer from '#transformers/user_transformer' export default class HomeController { async index({ inertia }: HttpContext) { - const articles = await Article.query().where('is_published', true).preload('author') + const [articles, threads, discussions, members, counts] = await Promise.all([ + Article.query() + .withScopes((s) => s.published()) + .preload('author') + .preload('tags') + .withCount('likes') + .withCount('comments') + .orderByRaw('featured_at desc nulls last') + .orderBy('published_at', 'desc') + .limit(5), + Thread.query() + .preload('author') + .preload('channel') + .orderBy('last_activity_at', 'desc') + .limit(6), + Discussion.query() + .preload('author') + .preload('tags') + .orderBy('last_activity_at', 'desc') + .limit(4), + User.query().whereNull('banned_at').orderBy('created_at', 'desc').limit(12), + db + .rawQuery( + `select + (select count(*) from users where banned_at is null) as members, + (select count(*) from articles where published_at is not null and published_at <= now()) as articles, + (select count(*) from threads) as threads, + (select count(*) from threads where solution_reply_id is not null) as solved, + (select count(*) from replies) as replies` + ) + .then((result) => result.rows[0]), + ]) + const threadsCount = Number(counts.threads) return inertia.render('home', { stats: { - members: 600, - developers: 50, - participation: 25, - githubStars: 10, + members: Number(counts.members), + articles: Number(counts.articles), + threads: threadsCount, + replies: Number(counts.replies), + solvedRate: threadsCount ? Math.round((Number(counts.solved) / threadsCount) * 100) : 0, }, - articles: articles, + articles: ArticleTransformer.transform(articles), + threads: ThreadTransformer.transform(threads), + discussions: DiscussionTransformer.transform(discussions), + members: UserTransformer.transform(members), }) } } diff --git a/app/controllers/markdown_controller.ts b/app/controllers/markdown_controller.ts new file mode 100644 index 0000000..80d3ba2 --- /dev/null +++ b/app/controllers/markdown_controller.ts @@ -0,0 +1,14 @@ +import vine from '@vinejs/vine' +import type { HttpContext } from '@adonisjs/core/http' +import { renderMarkdown } from '#services/markdown' + +const previewValidator = vine.create({ + body: vine.string().maxLength(60_000), +}) + +export default class MarkdownController { + async preview({ request }: HttpContext) { + const { body } = await request.validateUsing(previewValidator) + return { html: await renderMarkdown(body) } + } +} diff --git a/app/controllers/members_controller.ts b/app/controllers/members_controller.ts new file mode 100644 index 0000000..17290d9 --- /dev/null +++ b/app/controllers/members_controller.ts @@ -0,0 +1,72 @@ +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' +import User from '#models/user' +import UserTransformer from '#transformers/user_transformer' + +/** + * Per-member counters as correlated subqueries (one round trip, no N+1). + */ +export const MEMBER_COUNTERS = { + articles: `(select count(*) from articles where articles.user_id = users.id and articles.published_at is not null and articles.published_at <= now())`, + threads: `(select count(*) from threads where threads.user_id = users.id)`, + replies: `(select count(*) from replies where replies.user_id = users.id)`, +} + +/** + * Escape LIKE wildcards typed by the visitor ("100%" must not match everything). + */ +export function likePattern(value: string) { + return `%${value.replace(/[\\%_]/g, (char) => `\\${char}`)}%` +} + +export default class MembersController { + /** + * GET /membres — searchable directory of the community. + */ + async index({ request, inertia }: HttpContext) { + const q = String(request.input('q') ?? '') + .trim() + .slice(0, 60) + const sort: 'recents' | 'actifs' = request.input('sort') === 'actifs' ? 'actifs' : 'recents' + const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1) + + const query = User.query() + .whereNull('banned_at') + .select('users.*') + .select(db.raw(`${MEMBER_COUNTERS.articles} as articles_count`)) + .select(db.raw(`${MEMBER_COUNTERS.threads} as threads_count`)) + .select(db.raw(`${MEMBER_COUNTERS.replies} as replies_count`)) + + if (q) { + const pattern = likePattern(q.replace(/^@/, '')) + query.where((builder) => { + builder.whereILike('users.username', pattern).orWhereILike('users.name', pattern) + }) + } + + if (sort === 'actifs') { + query.orderByRaw( + `(${MEMBER_COUNTERS.articles} + ${MEMBER_COUNTERS.threads} + ${MEMBER_COUNTERS.replies}) desc` + ) + } + query.orderBy('users.created_at', 'desc').orderBy('users.id', 'desc') + + const [paginator, total] = await Promise.all([ + query.paginate(page, 30), + db + .from('users') + .whereNull('banned_at') + .count('* as total') + .first() + .then((row) => Number(row?.total ?? 0)), + ]) + + return inertia.render('members/index', { + members: UserTransformer.paginate(paginator.all(), paginator.getMeta()).useVariant( + 'forDirectory' + ), + filters: { q, sort }, + totalMembers: total, + }) + } +} diff --git a/app/controllers/notifications_controller.ts b/app/controllers/notifications_controller.ts new file mode 100644 index 0000000..c32cba9 --- /dev/null +++ b/app/controllers/notifications_controller.ts @@ -0,0 +1,210 @@ +import type { HttpContext } from '@adonisjs/core/http' +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import Notification from '#models/notification' +import NotificationTransformer from '#transformers/notification_transformer' +import { withReplyCounts } from '#services/notifications' +import { THREAD_REPLIES_PER_PAGE } from '#controllers/threads_controller' +import { DISCUSSION_REPLIES_PER_PAGE } from '#controllers/discussions_controller' + +const PER_PAGE = 30 + +const FILTERS = ['toutes', 'non-lues'] as const +type Filter = (typeof FILTERS)[number] + +function toPage(value: unknown) { + const page = Number.parseInt(String(value ?? '1'), 10) + return Number.isFinite(page) && page > 0 ? page : 1 +} + +/** + * The page of a paginated thread / discussion that shows a given reply + * (replies are listed by id, see ThreadsController#show). + */ +async function replyPage( + column: 'thread_id' | 'discussion_id', + parentId: number, + replyId: number, + repliesCount: number, + perPage: number +) { + if (repliesCount <= perPage) return 1 + const [{ n }] = await db + .from('replies') + .where(column, parentId) + .where('id', '<', replyId) + .count('* as n') + return Math.floor(Number(n) / perPage) + 1 +} + +/** + * Where a notification leads: the exact reply, on the right page. + */ +async function targetOf(notification: Notification) { + const anchor = notification.replyId ? `#reponse-${notification.replyId}` : '' + + if (notification.threadId !== null) { + const thread = await db + .from('threads') + .select('slug', 'replies_count') + .where('id', notification.threadId) + .first() + if (!thread) return null + const page = notification.replyId + ? await replyPage( + 'thread_id', + notification.threadId, + notification.replyId, + Number(thread.replies_count), + THREAD_REPLIES_PER_PAGE + ) + : 1 + return `/forum/${thread.slug}${page > 1 ? `?page=${page}` : ''}${anchor}` + } + + if (notification.discussionId !== null) { + const discussion = await db + .from('discussions') + .select('slug', 'replies_count') + .where('id', notification.discussionId) + .first() + if (!discussion) return null + const page = notification.replyId + ? await replyPage( + 'discussion_id', + notification.discussionId, + notification.replyId, + Number(discussion.replies_count), + DISCUSSION_REPLIES_PER_PAGE + ) + : 1 + return `/discussions/${discussion.slug}${page > 1 ? `?page=${page}` : ''}${anchor}` + } + + if (notification.articleId !== null) { + const article = await db + .from('articles') + .select('slug') + .where('id', notification.articleId) + .first() + return article ? `/articles/${article.slug}${anchor}` : null + } + + return null +} + +/** + * The signed-in member's notification center. Every action is scoped to + * the owner: someone else's notification is a 404. + */ +export default class NotificationsController { + /** + * GET /notifications — grouped by recency, "Toutes" / "Non lues". + */ + async index({ auth, request, inertia }: HttpContext) { + const user = auth.getUserOrFail() + const requested = request.input('filtre') + const filter: Filter = FILTERS.includes(requested) ? requested : 'toutes' + const page = toPage(request.input('page')) + + const query = Notification.query() + .where('user_id', user.id) + .preload('actor') + .preload('thread', (q) => q.select('id', 'slug', 'title', 'user_id')) + .preload('discussion', (q) => q.select('id', 'slug', 'title', 'user_id')) + .preload('article', (q) => q.select('id', 'slug', 'title', 'user_id')) + // plainExcerpt() only reads the first characters of the body. + .preload('reply', (q) => q.select('id', db.raw('left(body, 1200) as body'))) + .orderBy('created_at', 'desc') + .orderBy('id', 'desc') + if (filter === 'non-lues') query.whereNull('read_at') + + const [paginator, counts] = await Promise.all([ + query.paginate(page, PER_PAGE), + db + .from('notifications') + .where('user_id', user.id) + .select( + db.raw('count(*)::int as total'), + db.raw('count(*) filter (where read_at is null)::int as unread') + ) + .first(), + ]) + await withReplyCounts(paginator.all()) + + return inertia.render('notifications/index', { + notifications: NotificationTransformer.paginate(paginator.all(), paginator.getMeta()), + filter, + counts: { + toutes: Number(counts?.total ?? 0), + nonLues: Number(counts?.unread ?? 0), + }, + }) + } + + /** + * GET /notifications/:id — mark as read, then go to the reply. + * + * From an Inertia visit, a 409 + X-Inertia-Redirect makes the client visit + * the target itself, so the "#reponse-…" fragment survives (an XHR + * following a 302 would drop it). A plain request gets a regular redirect. + */ + async show({ params, auth, request, response, session }: HttpContext) { + const user = auth.getUserOrFail() + const notification = await Notification.query() + .where('id', params.id) + .where('user_id', user.id) + .firstOrFail() + + if (notification.readAt === null) { + notification.readAt = DateTime.now() + await notification.save() + } + + const target = await targetOf(notification) + if (!target) { + session.flash('error', 'Ce contenu n’est plus disponible.') + return response.redirect().toPath('/notifications') + } + + if (request.header('x-inertia')) { + response.header('X-Inertia-Redirect', target) + return response.status(409).send('') + } + return response.redirect().toPath(target) + } + + /** + * POST /notifications/:id/read + */ + async read({ params, auth, response }: HttpContext) { + const user = auth.getUserOrFail() + const notification = await Notification.query() + .where('id', params.id) + .where('user_id', user.id) + .firstOrFail() + + if (notification.readAt === null) { + notification.readAt = DateTime.now() + await notification.save() + } + return response.redirect().back() + } + + /** + * POST /notifications/read-all + */ + async readAll({ auth, response, session }: HttpContext) { + const user = auth.getUserOrFail() + const updated = await db + .from('notifications') + .where('user_id', user.id) + .whereNull('read_at') + .update({ read_at: new Date() }) + + if (Number(updated)) { + session.flash('success', 'Toutes vos notifications sont marquées comme lues.') + } + return response.redirect().back() + } +} diff --git a/app/controllers/profile_controller.ts b/app/controllers/profile_controller.ts index 451b7d4..a18d761 100644 --- a/app/controllers/profile_controller.ts +++ b/app/controllers/profile_controller.ts @@ -1,21 +1,199 @@ -import { HttpContext } from '@adonisjs/core/http' +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' import User from '#models/user' import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Reply from '#models/reply' +import ArticleTransformer from '#transformers/article_transformer' +import ThreadTransformer from '#transformers/thread_transformer' +import DiscussionTransformer from '#transformers/discussion_transformer' +import UserTransformer from '#transformers/user_transformer' +import { plainExcerpt } from '#services/markdown' +import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model' + +export const PROFILE_TABS = ['articles', 'questions', 'discussions', 'reponses'] as const +export type ProfileTab = (typeof PROFILE_TABS)[number] + +const PER_PAGE = 15 + +/** + * Compact representation of a reply, with the title and URL of the page + * it belongs to (thread, discussion or article). Relations "thread", + * "discussion" and "article" must be preloaded (id, slug, title), plus + * "author" when `withAuthor` is set. + */ +export function replySummary(reply: Reply, { withAuthor = false } = {}) { + const parent = reply.thread + ? { type: 'thread' as const, title: reply.thread.title, url: `/forum/${reply.thread.slug}` } + : reply.discussion + ? { + type: 'discussion' as const, + title: reply.discussion.title, + url: `/discussions/${reply.discussion.slug}`, + } + : reply.article + ? { + type: 'article' as const, + title: reply.article.title, + url: `/articles/${reply.article.slug}`, + } + : null + + return { + id: reply.id, + excerpt: plainExcerpt(reply.body, 220), + createdAt: reply.createdAt.toISO()!, + likesCount: Number(reply.$extras.likes_count ?? 0), + isSolution: Boolean(reply.thread && reply.thread.solutionReplyId === reply.id), + parent: parent ? { ...parent, anchor: `${parent.url}#reponse-${reply.id}` } : null, + author: withAuthor && reply.author ? new UserTransformer(reply.author).toObject() : null, + } +} + +export type ReplySummary = ReturnType + +/** + * Query modifier: the parents a reply summary needs (only light columns). + */ +export function withReplyParents(query: ModelQueryBuilderContract) { + return ( + query + // Comments on articles that went back to draft must not leak their title. + .where((q) => + q + .whereNull('replies.article_id') + .orWhereIn( + 'replies.article_id', + db + .from('articles') + .select('id') + .whereNotNull('published_at') + .where('published_at', '<=', db.raw('now()')) + ) + ) + .preload('thread', (q) => q.select('id', 'slug', 'title', 'solution_reply_id')) + .preload('discussion', (q) => q.select('id', 'slug', 'title')) + .preload('article', (q) => q.select('id', 'slug', 'title')) + ) +} export default class ProfileController { - async show({ params, inertia }: HttpContext) { - const user = await User.findByOrFail('username', params.username.replace('@', '')) - const articles = await Article.query() - .where('author_id', user.id) - .where('is_published', true) - .orderBy('created_at', 'desc') - .preload('author') + /** + * Public profile: /@username (see start/routes/members.ts). + */ + async show({ params, request, inertia, auth }: HttpContext) { + const viewer = auth.user + const username = String(params.username).toLowerCase() + + // Banned members disappear from the site, except for the staff. + const profile = await User.query() + .whereRaw('lower(username) = ?', [username]) + .if(!viewer?.isModerator, (q) => q.whereNull('banned_at')) + .firstOrFail() + + const statsRow = await db + .rawQuery( + `select + (select count(*) from articles where user_id = :id and published_at is not null and published_at <= now()) as articles, + (select count(*) from threads where user_id = :id) as questions, + (select count(*) from discussions where user_id = :id) as discussions, + (select count(*) from replies where user_id = :id) as replies, + (select count(*) from threads t join replies r on r.id = t.solution_reply_id where r.user_id = :id) as solutions, + (select count(*) from likes l join articles a on a.id = l.article_id where a.user_id = :id) + + (select count(*) from likes l join replies r on r.id = l.reply_id where r.user_id = :id) as likes`, + { id: profile.id } + ) + .then((result) => result.rows[0]) + + const stats = { + articles: Number(statsRow.articles), + questions: Number(statsRow.questions), + discussions: Number(statsRow.discussions), + replies: Number(statsRow.replies), + solutions: Number(statsRow.solutions), + likes: Number(statsRow.likes), + } + + const counts: Record = { + articles: stats.articles, + questions: stats.questions, + discussions: stats.discussions, + reponses: stats.replies, + } + + // Explicit tab from the URL, otherwise the first one with content. + const requested = request.input('tab') + const tab: ProfileTab = PROFILE_TABS.includes(requested) + ? requested + : (PROFILE_TABS.find((name) => counts[name] > 0) ?? 'articles') + const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1) + + const tabData = await this.tabData(profile, tab, page) return inertia.render('profile/show', { - profile: { - ...user.serialize(), - articles: articles, - }, + profile: UserTransformer.transform(profile).useVariant('forProfile'), + banned: profile.isBanned, + isOwner: viewer?.id === profile.id, + stats, + tab, + ...tabData, }) } + + private async tabData(profile: User, tab: ProfileTab, page: number) { + const empty = { articles: null, threads: null, discussions: null, replies: null } + + if (tab === 'articles') { + const paginator = await Article.query() + .where('user_id', profile.id) + .withScopes((s) => s.published()) + .preload('author') + .preload('tags') + .withCount('likes') + .withCount('comments') + .orderBy('published_at', 'desc') + .paginate(page, PER_PAGE) + return { + ...empty, + articles: ArticleTransformer.paginate(paginator.all(), paginator.getMeta()), + } + } + + if (tab === 'questions') { + const paginator = await Thread.query() + .where('user_id', profile.id) + .preload('author') + .preload('channel') + .orderBy('created_at', 'desc') + .paginate(page, PER_PAGE) + return { ...empty, threads: ThreadTransformer.paginate(paginator.all(), paginator.getMeta()) } + } + + if (tab === 'discussions') { + const paginator = await Discussion.query() + .where('user_id', profile.id) + .preload('author') + .preload('tags') + .orderBy('created_at', 'desc') + .paginate(page, PER_PAGE) + return { + ...empty, + discussions: DiscussionTransformer.paginate(paginator.all(), paginator.getMeta()), + } + } + + const paginator = await withReplyParents(Reply.query()) + .where('user_id', profile.id) + .withCount('likes') + .orderBy('created_at', 'desc') + .paginate(page, PER_PAGE) + return { + ...empty, + replies: { + data: paginator.all().map((reply) => replySummary(reply)), + metadata: paginator.getMeta(), + }, + } + } } diff --git a/app/controllers/replies_controller.ts b/app/controllers/replies_controller.ts new file mode 100644 index 0000000..e3b97bb --- /dev/null +++ b/app/controllers/replies_controller.ts @@ -0,0 +1,57 @@ +import type { HttpContext } from '@adonisjs/core/http' +import Reply from '#models/reply' +import Like from '#models/like' +import { replyValidator } from '#validators/reply_validator' +import { deleteReply, replyLocation, updateReply } from '#services/reply_service' + +/** + * Edit / delete / like any reply (forum, discussion or article comment). + * Creation lives with each parent (threads, discussions, articles). + */ +export default class RepliesController { + async update({ params, request, auth, response, session }: HttpContext) { + const reply = await Reply.findOrFail(params.id) + if (!(await auth.user!.canManageContent(reply.userId))) { + session.flash('error', 'Vous ne pouvez pas modifier cette réponse.') + return response.redirect().back() + } + const { body } = await request.validateUsing(replyValidator) + await updateReply(reply, body) + session.flash('success', 'Réponse mise à jour.') + return response.redirect().toPath(`${await replyLocation(reply)}#reponse-${reply.id}`) + } + + async destroy({ params, auth, response, session }: HttpContext) { + const reply = await Reply.findOrFail(params.id) + if (!(await auth.user!.canManageContent(reply.userId))) { + session.flash('error', 'Vous ne pouvez pas supprimer cette réponse.') + return response.redirect().back() + } + const location = await replyLocation(reply) + await deleteReply(reply) + session.flash('success', 'Réponse supprimée.') + return response.redirect().toPath(location) + } + + /** + * Toggle the viewer's like on a reply. + */ + async like({ params, auth, response }: HttpContext) { + const reply = await Reply.findOrFail(params.id) + const existing = await Like.query() + .where('user_id', auth.user!.id) + .where('reply_id', reply.id) + .first() + if (existing) { + await existing.delete() + } else if (reply.userId !== auth.user!.id) { + try { + await Like.create({ userId: auth.user!.id, replyId: reply.id }) + } catch (error) { + // Double click: the unique (user_id, reply_id) index already holds it. + if ((error as { code?: string }).code !== '23505') throw error + } + } + return response.redirect().back() + } +} diff --git a/app/controllers/reports_controller.ts b/app/controllers/reports_controller.ts new file mode 100644 index 0000000..ebf73e8 --- /dev/null +++ b/app/controllers/reports_controller.ts @@ -0,0 +1,121 @@ +import type { HttpContext } from '@adonisjs/core/http' +import { errors as lucidErrors } from '@adonisjs/lucid' +import db from '@adonisjs/lucid/services/db' +import Report from '#models/report' +import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Reply from '#models/reply' +import type User from '#models/user' +import { reportValidator, type ReportTarget } from '#validators/report_validator' + +const TARGET_ATTRIBUTE = { + article: 'articleId', + thread: 'threadId', + discussion: 'discussionId', + reply: 'replyId', +} as const satisfies Record + +/** + * Drafts stay invisible to everyone but their author and the staff. + */ +function assertArticleVisible(article: Article, viewer: User) { + if (article.isPublished || viewer.canSeeDraftsOf(article.userId)) return + throw new lucidErrors.E_ROW_NOT_FOUND() +} + +/** + * Owner and label (title, or the parent's title for a reply) of a piece of + * content the viewer is allowed to see. Missing or invisible content + * (someone else's draft, or a comment on it) is a 404. + */ +async function visibleTarget( + target: ReportTarget, + id: number, + viewer: User +): Promise<{ ownerId: number; label: string | null }> { + switch (target) { + case 'article': { + const article = await Article.findOrFail(id) + assertArticleVisible(article, viewer) + return { ownerId: article.userId, label: article.title } + } + case 'thread': { + const thread = await Thread.findOrFail(id) + return { ownerId: thread.userId, label: thread.title } + } + case 'discussion': { + const discussion = await Discussion.findOrFail(id) + return { ownerId: discussion.userId, label: discussion.title } + } + case 'reply': { + const reply = await Reply.query() + .where('id', id) + .preload('thread', (query) => query.select('id', 'title')) + .preload('discussion', (query) => query.select('id', 'title')) + .preload('article', (query) => query.select('id', 'title', 'user_id', 'published_at')) + .firstOrFail() + if (reply.article) assertArticleVisible(reply.article, viewer) + const parent = reply.thread ?? reply.discussion ?? reply.article + return { ownerId: reply.userId, label: parent?.title ?? null } + } + } +} + +/** + * The partial unique index "reports_open_unique" refused a second open + * report of the same member on the same content. + */ +function isDuplicateOpenReport(error: unknown) { + const { code, constraint } = error as { code?: string; constraint?: string } + return code === '23505' && constraint === 'reports_open_unique' +} + +/** + * Members flag content for the moderators ("Signaler"). + */ +export default class ReportsController { + /** + * POST /signalements { target, id, reason, details? } + */ + async store({ request, auth, response, session }: HttpContext) { + const user = auth.getUserOrFail() + const { target, id, reason, details } = await request.validateUsing(reportValidator) + + const { ownerId, label } = await visibleTarget(target, id, user) + if (ownerId === user.id) { + session.flash('error', 'Vous ne pouvez pas signaler votre propre contenu.') + return response.redirect().back() + } + + const report = new Report() + report.reporterId = user.id + report.targetType = target + report.targetId = id + report[TARGET_ATTRIBUTE[target]] = id + report.targetLabel = label ? label.slice(0, 200) : null + report.targetOwnerId = ownerId + report.reason = reason + report.details = details ?? null + report.status = 'open' + + // One open report per member and content, enforced by the database (no + // race between two clicks). The savepoint keeps an outer transaction usable. + try { + await db.transaction(async (trx) => { + report.useTransaction(trx) + await report.save() + }) + } catch (error) { + if (!isDuplicateOpenReport(error)) throw error + session.flash( + 'success', + 'Vous avez déjà signalé ce contenu : l’équipe de modération l’a bien dans sa file.' + ) + return response.redirect().back() + } + + session.flash('success', 'Merci, l’équipe de modération va examiner ce contenu.') + return response.redirect().back() + } +} diff --git a/app/controllers/search_controller.ts b/app/controllers/search_controller.ts new file mode 100644 index 0000000..bbda9ec --- /dev/null +++ b/app/controllers/search_controller.ts @@ -0,0 +1,267 @@ +import type { HttpContext } from '@adonisjs/core/http' +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Tag from '#models/tag' +import Channel from '#models/channel' +import ArticleTransformer from '#transformers/article_transformer' +import ThreadTransformer from '#transformers/thread_transformer' +import DiscussionTransformer from '#transformers/discussion_transformer' +import TagTransformer from '#transformers/tag_transformer' +import ChannelTransformer from '#transformers/channel_transformer' +import { searchMessages, searchValidator } from '#validators/search_validator' +import { + SEARCH_SECTIONS, + SEARCH_TYPES, + countAll, + exactQuery, + findHits, + prefixQuery, + type SearchCounts, + type SearchHit, + type SearchSection, + type SearchType, +} from '#services/search' + +/** Results per page on a filtered tab. */ +const PER_PAGE = 15 +/** Results per section on the "tout" tab. */ +const PREVIEW = 4 + +type Status = 'landing' | 'invalid' | 'throttled' | 'results' | 'empty' + +type Meta = { total: number; perPage: number; currentPage: number; lastPage: number } + +function toPage(value: unknown) { + const page = Number.parseInt(String(value ?? '1'), 10) + return Number.isFinite(page) && page > 0 ? Math.min(page, 1000) : 1 +} + +function meta(total: number, perPage: number, currentPage: number): Meta { + return { total, perPage, currentPage, lastPage: Math.max(1, Math.ceil(total / perPage)) } +} + +/** + * Lucid returns "whereIn" rows in any order: restore the ranking. + */ +function inRankOrder(hits: SearchHit[], rows: T[]) { + const byId = new Map(rows.map((row) => [row.id, row])) + return hits.map((hit) => byId.get(hit.id)).filter((row): row is T => Boolean(row)) +} + +const loaders = { + articles: (ids: number[]) => + Article.query().whereIn('id', ids).preload('author').preload('tags').withCount('comments'), + questions: (ids: number[]) => + Thread.query().whereIn('id', ids).preload('author').preload('channel'), + discussions: (ids: number[]) => + Discussion.query().whereIn('id', ids).preload('author').preload('tags'), +} + +/** + * Popular topics and forum channels, offered on the landing state and + * when nothing matches. + */ +async function suggestions() { + const [tags, channels] = await Promise.all([ + Tag.query().withCount('articles', (query) => { + query + .whereNotNull('articles.published_at') + .where('articles.published_at', '<=', DateTime.now().toSQL()!) + }), + Channel.query().withCount('threads').orderBy('position', 'asc'), + ]) + const popular = tags + .filter((tag) => Number(tag.$extras.articles_count) > 0) + .sort((a, b) => Number(b.$extras.articles_count) - Number(a.$extras.articles_count)) + .slice(0, 12) + return { + popularTags: TagTransformer.transform(popular), + channels: ChannelTransformer.transform(channels), + } +} + +/** + * Size of the searchable index (landing state), same visibility rules. + */ +async function indexSize(): Promise { + const visibleAuthor = (table: string) => + `not exists (select 1 from users where users.id = ${table}.user_id and users.banned_at is not null)` + const result = await db.rawQuery( + `select + (select count(*) from articles where published_at is not null and published_at <= now() and ${visibleAuthor('articles')}) as articles, + (select count(*) from threads where ${visibleAuthor('threads')}) as questions, + (select count(*) from discussions where ${visibleAuthor('discussions')}) as discussions` + ) + const row = result.rows[0] ?? {} + return { + articles: Number(row.articles ?? 0), + questions: Number(row.questions ?? 0), + discussions: Number(row.discussions ?? 0), + } +} + +const sum = (counts: SearchCounts) => counts.articles + counts.questions + counts.discussions + +export default class SearchController { + /** + * GET /recherche?q=&type=tout|articles|questions|discussions&page= + */ + async index(ctx: HttpContext) { + const qs = ctx.request.qs() + const rawQ = typeof qs.q === 'string' ? qs.q.trim() : '' + const type: SearchType = SEARCH_TYPES.includes(qs.type) ? qs.type : 'tout' + + if (!rawQ) return this.landing(ctx, { type }) + + const [error, input] = await searchValidator.tryValidate( + { q: rawQ, type, page: toPage(qs.page) }, + { messagesProvider: searchMessages } + ) + if (error) { + return this.landing(ctx, { + type, + q: rawQ.slice(0, 100), + status: 'invalid', + error: error.messages[0]?.message ?? 'Recherche invalide.', + }) + } + + const q = input.q + const page = input.page ?? 1 + + // Exact (websearch) query first; prefixes ("clos" → closures) only + // when it finds nothing at all. + let query = exactQuery(q) + let counts = await countAll(query) + if (sum(counts) === 0) { + const fallback = prefixQuery(q) + if (fallback) { + const fallbackCounts = await countAll(fallback) + if (sum(fallbackCounts) > 0) { + query = fallback + counts = fallbackCounts + } + } + } + + if (sum(counts) === 0) { + return ctx.inertia.render('search/index', { + ...this.emptyProps(type, q), + status: 'empty', + counts, + ...(await suggestions()), + }) + } + + const filtered = type !== 'tout' + const perPage = filtered ? PER_PAGE : PREVIEW + const currentPage = filtered ? page : 1 + const sections = SEARCH_SECTIONS.filter((section) => + filtered ? section === type : counts[section] > 0 + ) + + const results = await Promise.all( + sections.map(async (section) => { + const hits = counts[section] + ? await findHits(section, query, { limit: perPage, offset: (currentPage - 1) * perPage }) + : [] + const ids = hits.map((hit) => hit.id) + const rows = ids.length ? await loaders[section](ids) : [] + return { section, hits, rows: inRankOrder(hits, rows as { id: number }[]) } + }) + ) + + const highlights: Record = {} + for (const { section, hits } of results) { + for (const hit of hits) { + highlights[`${section}:${hit.id}`] = { + titleHtml: hit.titleHtml, + snippetHtml: hit.snippetHtml, + } + } + } + + const pick = (section: SearchSection) => results.find((result) => result.section === section) + const sectionMeta = (section: SearchSection) => meta(counts[section], perPage, currentPage) + const articles = pick('articles') + const questions = pick('questions') + const discussions = pick('discussions') + + return ctx.inertia.render('search/index', { + ...this.emptyProps(type, q), + status: 'results', + mode: query.mode, + counts, + highlights, + articles: articles + ? ArticleTransformer.paginate(articles.rows as Article[], sectionMeta('articles')) + : null, + questions: questions + ? ThreadTransformer.paginate(questions.rows as Thread[], sectionMeta('questions')) + : null, + discussions: discussions + ? DiscussionTransformer.paginate( + discussions.rows as Discussion[], + sectionMeta('discussions') + ) + : null, + }) + } + + /** + * Rendered by the search limiter (start/routes/search.ts) for Inertia + * visits instead of a bare "429" text response. No database query. + */ + async throttled(ctx: HttpContext, message: string) { + const qs = ctx.request.qs() + const type: SearchType = SEARCH_TYPES.includes(qs.type) ? qs.type : 'tout' + const q = typeof qs.q === 'string' ? qs.q.trim().slice(0, 100) : '' + const page = await ctx.inertia.render('search/index', { + ...this.emptyProps(type, q), + status: 'throttled', + error: message, + }) + // Called from an exception handler: the return value is not sent. + ctx.response.status(429).send(page) + } + + private emptyProps(type: SearchType, q: string) { + return { + q, + type, + status: 'landing' as Status, + error: null as string | null, + mode: null, + counts: null as SearchCounts | null, + index: null as SearchCounts | null, + highlights: {}, + articles: null, + questions: null, + discussions: null, + popularTags: null, + channels: null, + } + } + + private async landing( + ctx: HttpContext, + options: { + type: SearchType + q?: string + status?: Status + error?: string + } + ) { + const [hints, index] = await Promise.all([suggestions(), indexSize()]) + return ctx.inertia.render('search/index', { + ...this.emptyProps(options.type, options.q ?? ''), + status: options.status ?? 'landing', + error: options.error ?? null, + index, + ...hints, + }) + } +} diff --git a/app/controllers/seo_controller.ts b/app/controllers/seo_controller.ts new file mode 100644 index 0000000..2e4de28 --- /dev/null +++ b/app/controllers/seo_controller.ts @@ -0,0 +1,121 @@ +import type { HttpContext } from '@adonisjs/core/http' +import env from '#start/env' +import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import User from '#models/user' + +const PRODUCTION_HOST = 'javascript.cm' + +function escapeXml(value: string) { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, ''') +} + +export default class SeoController { + /** + * Only the production host is indexable: staging and previews are not. + */ + async robots({ response }: HttpContext) { + const appUrl = new URL(env.get('APP_URL')) + response.header('Content-Type', 'text/plain; charset=utf-8') + + if (appUrl.hostname !== PRODUCTION_HOST) { + return 'User-agent: *\nDisallow: /\n' + } + + return [ + 'User-agent: *', + 'Allow: /', + 'Disallow: /dashboard', + 'Disallow: /settings', + 'Disallow: /admin', + '', + `Sitemap: ${appUrl.origin}/sitemap.xml`, + '', + ].join('\n') + } + + async sitemap({ response }: HttpContext) { + const base = env.get('APP_URL') + const [articles, threads, discussions, users] = await Promise.all([ + Article.query() + .withScopes((s) => s.published()) + .select('slug', 'updated_at', 'published_at'), + Thread.query().select('slug', 'last_activity_at'), + Discussion.query().select('slug', 'last_activity_at'), + User.query().whereNull('banned_at').select('username', 'updated_at'), + ]) + + const urls: { loc: string; lastmod?: string; priority?: string }[] = [ + { loc: '/', priority: '1.0' }, + { loc: '/articles', priority: '0.9' }, + { loc: '/forum', priority: '0.9' }, + { loc: '/discussions', priority: '0.8' }, + { loc: '/membres', priority: '0.5' }, + ...articles.map((a) => ({ + loc: `/articles/${a.slug}`, + lastmod: (a.updatedAt ?? a.publishedAt)?.toISODate() ?? undefined, + priority: '0.8', + })), + ...threads.map((t) => ({ + loc: `/forum/${t.slug}`, + lastmod: t.lastActivityAt.toISODate() ?? undefined, + })), + ...discussions.map((d) => ({ + loc: `/discussions/${d.slug}`, + lastmod: d.lastActivityAt.toISODate() ?? undefined, + })), + ...users.map((u) => ({ loc: `/@${u.username}`, priority: '0.3' })), + ] + + const body = urls + .map( + (u) => + `${escapeXml(base + u.loc)}${u.lastmod ? `${u.lastmod}` : ''}${u.priority ? `${u.priority}` : ''}` + ) + .join('') + + response.header('Content-Type', 'application/xml; charset=utf-8') + return `${body}` + } + + async feed({ response }: HttpContext) { + const base = env.get('APP_URL') + const articles = await Article.query() + .withScopes((s) => s.published()) + .preload('author') + .orderBy('published_at', 'desc') + .limit(30) + + const items = articles + .map( + (a) => ` + ${escapeXml(a.title)} + ${escapeXml(`${base}/articles/${a.slug}`)} + ${escapeXml(`${base}/articles/${a.slug}`)} + ${a.publishedAt!.toRFC2822()} + ${escapeXml(a.author.displayName)} + ${escapeXml(a.excerpt ?? '')} +` + ) + .join('\n') + + response.header('Content-Type', 'application/rss+xml; charset=utf-8') + return ` + + + JavaScript Cameroun — Articles + ${escapeXml(base)} + + Les articles de la communauté des développeurs JavaScript du Cameroun. + fr +${items} + +` + } +} diff --git a/app/controllers/settings_controller.ts b/app/controllers/settings_controller.ts new file mode 100644 index 0000000..5ee14c0 --- /dev/null +++ b/app/controllers/settings_controller.ts @@ -0,0 +1,218 @@ +import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware' +import type { HttpContext } from '@adonisjs/core/http' +import hash from '@adonisjs/core/services/hash' +import db from '@adonisjs/lucid/services/db' +import { + deleteAccountValidator, + normalizeHandle, + passwordSettingsValidator, + profileSettingsValidator, +} from '#validators/settings_validator' + +/** + * Account settings of the signed-in member (profile, password, deletion). + * The forms read the current values from the shared `user` prop. + */ +export default class SettingsController { + async profile({ inertia }: HttpContext) { + return inertia.render('settings/profile', {}) + } + + async updateProfile({ request, auth, response, session }: HttpContext) { + const user = auth.getUserOrFail() + const input = request.only([ + 'name', + 'username', + 'email', + 'bio', + 'location', + 'websiteUrl', + 'avatarUrl', + 'githubUsername', + 'twitterUsername', + 'linkedinUsername', + ]) + + const data = await profileSettingsValidator.validate( + { + ...input, + githubUsername: normalizeHandle(input.githubUsername, 'github'), + twitterUsername: normalizeHandle(input.twitterUsername, 'twitter'), + linkedinUsername: normalizeHandle(input.linkedinUsername, 'linkedin'), + }, + { meta: { userId: user.id } } + ) + + const usernameChanged = data.username !== user.username + if (data.email !== user.email) { + // A new address is unverified until proven otherwise (GitHub sign-in + // only links accounts whose e-mail is verified). + user.emailVerifiedAt = null + } + user.merge({ + name: data.name, + username: data.username, + email: data.email, + bio: data.bio, + location: data.location, + websiteUrl: data.websiteUrl, + avatarUrl: data.avatarUrl, + githubUsername: data.githubUsername, + twitterUsername: data.twitterUsername, + linkedinUsername: data.linkedinUsername, + }) + await user.save() + + session.flash( + 'success', + usernameChanged + ? `Profil mis à jour. Votre nouvelle adresse : javascript.cm/@${user.username}` + : 'Profil mis à jour.' + ) + return response.redirect().toPath('/settings') + } + + async password({ inertia }: HttpContext) { + return inertia.render('settings/password', {}) + } + + async updatePassword({ request, auth, response, session }: HttpContext) { + const user = auth.getUserOrFail() + const { currentPassword, password } = await request.validateUsing(passwordSettingsValidator) + + if (user.password !== null) { + const valid = currentPassword ? await hash.verify(user.password, currentPassword) : false + if (!valid) { + session.flashExcept(['currentPassword', 'password', 'passwordConfirmation']) + session.flash('inputErrorsBag', { + currentPassword: [ + currentPassword + ? 'Mot de passe actuel incorrect.' + : 'Saisissez votre mot de passe actuel.', + ], + }) + return response.redirect().back() + } + } + + const hadPassword = user.password !== null + user.password = password // hashed by the AuthFinder mixin + user.sessionVersion = user.sessionVersion + 1 + await user.save() + + // Sign out the other devices: their sessions carry the previous version + // (see SilentAuthMiddleware) and their "remember me" tokens are revoked. + await db.from('remember_me_tokens').where('tokenable_id', user.id).delete() + session.put(SESSION_VERSION_KEY, user.sessionVersion) + + session.flash( + 'success', + hadPassword + ? 'Mot de passe modifié.' + : 'Mot de passe défini : vous pouvez aussi vous connecter avec votre e-mail.' + ) + return response.redirect().toPath('/settings/password') + } + + async account({ inertia, auth }: HttpContext) { + const user = auth.getUserOrFail() + const counts = await db + .rawQuery( + `select + (select count(*) from articles where user_id = :id) as articles, + (select count(*) from threads where user_id = :id) as threads, + (select count(*) from discussions where user_id = :id) as discussions, + (select count(*) from replies where user_id = :id) as replies`, + { id: user.id } + ) + .then((result) => result.rows[0]) + + return inertia.render('settings/account', { + githubLinked: user.githubId !== null, + content: { + articles: Number(counts.articles), + threads: Number(counts.threads), + discussions: Number(counts.discussions), + replies: Number(counts.replies), + }, + }) + } + + async destroyAccount({ request, auth, response, session }: HttpContext) { + const user = auth.getUserOrFail() + const { confirmation } = await request.validateUsing(deleteAccountValidator) + + if (confirmation.replace(/^@/, '').toLowerCase() !== user.username.toLowerCase()) { + session.flash('inputErrorsBag', { + confirmation: ['Saisissez exactement votre nom d’utilisateur pour confirmer.'], + }) + return response.redirect().back() + } + + if (user.isAdmin) { + const admins = await db + .from('users') + .where('role', 'admin') + .whereNull('banned_at') + .count('* as total') + .first() + if (Number(admins?.total ?? 0) <= 1) { + session.flash( + 'error', + 'Vous êtes le dernier administrateur : nommez un autre administrateur avant de supprimer votre compte.' + ) + return response.redirect().back() + } + } + + await db.transaction(async (trx) => { + // Threads and discussions of other members lose this member's replies + // through the cascade: keep their counters right. + const threadRows = await trx + .from('replies') + .select('thread_id') + .where('user_id', user.id) + .whereNotNull('thread_id') + const discussionRows = await trx + .from('replies') + .select('discussion_id') + .where('user_id', user.id) + .whereNotNull('discussion_id') + const touchedThreads = [...new Set(threadRows.map((row) => row.thread_id as number))] + const touchedDiscussions = [ + ...new Set(discussionRows.map((row) => row.discussion_id as number)), + ] + + user.useTransaction(trx) + await user.delete() + + if (touchedThreads.length) { + await trx + .from('threads') + .whereIn('id', touchedThreads) + .update({ + replies_count: trx.raw( + '(select count(*) from replies where replies.thread_id = threads.id)' + ), + }) + } + if (touchedDiscussions.length) { + await trx + .from('discussions') + .whereIn('id', touchedDiscussions) + .update({ + replies_count: trx.raw( + '(select count(*) from replies where replies.discussion_id = discussions.id)' + ), + }) + } + }) + + await auth.use('web').logout() + session.flash( + 'success', + 'Votre compte a été supprimé. Merci d’avoir fait partie de la communauté.' + ) + return response.redirect().toPath('/') + } +} diff --git a/app/controllers/thread_actions_controller.ts b/app/controllers/thread_actions_controller.ts new file mode 100644 index 0000000..f741087 --- /dev/null +++ b/app/controllers/thread_actions_controller.ts @@ -0,0 +1,122 @@ +import type { HttpContext } from '@adonisjs/core/http' +import db from '@adonisjs/lucid/services/db' +import Thread from '#models/thread' +import Reply from '#models/reply' +import { replyValidator } from '#validators/reply_validator' +import { solutionValidator } from '#validators/thread_validator' +import { createReply } from '#services/reply_service' +import { notifySolution } from '#services/notifications' +import { THREAD_REPLIES_PER_PAGE } from '#controllers/threads_controller' + +/** + * Everything that happens *on* a forum thread: replying, accepting a + * solution, and moderation toggles (pin / lock). + */ +export default class ThreadActionsController { + /** + * POST /forum/:slug/replies + */ + async reply({ params, request, auth, response, session }: HttpContext) { + const user = auth.user! + const thread = await Thread.findByOrFail('slug', params.slug) + if (thread.isLocked && !user.isModerator) { + session.flash('error', 'Ce sujet est verrouillé : il n’accepte plus de nouvelles réponses.') + return response.redirect().toPath(`/forum/${thread.slug}`) + } + + const { body } = await request.validateUsing(replyValidator) + const reply = await createReply({ type: 'thread', id: thread.id }, user, body) + + const total = thread.repliesCount + 1 + const page = total > THREAD_REPLIES_PER_PAGE ? Math.ceil(total / THREAD_REPLIES_PER_PAGE) : 1 + session.flash('success', 'Réponse publiée. Merci pour votre aide !') + return response + .redirect() + .toPath(`/forum/${thread.slug}${page > 1 ? `?page=${page}` : ''}#reponse-${reply.id}`) + } + + /** + * POST /forum/:slug/solution { replyId } — thread author or moderators, + * on a reply of this thread written by someone else. + */ + async markSolution({ params, request, auth, response, session }: HttpContext) { + const thread = await Thread.findByOrFail('slug', params.slug) + if (!(await auth.user!.canManageContent(thread.userId))) { + session.flash('error', 'Seul l’auteur de la question peut choisir la solution.') + return response.redirect().back() + } + + const { replyId } = await request.validateUsing(solutionValidator) + const reply = await Reply.query().where('id', replyId).where('thread_id', thread.id).first() + if (!reply) { + session.flash('error', 'Cette réponse n’appartient pas à cette question.') + return response.redirect().back() + } + if (reply.userId === thread.userId) { + session.flash('error', 'La solution doit venir d’une réponse d’un autre membre.') + return response.redirect().back() + } + + // Plain update: accepting an answer is not an edit of the question. + await db.from('threads').where('id', thread.id).update({ solution_reply_id: reply.id }) + await notifySolution(thread.id, reply, auth.user!.id) + session.flash('success', 'Réponse marquée comme solution.') + return response.redirect().back() + } + + /** + * DELETE /forum/:slug/solution + */ + async unmarkSolution({ params, auth, response, session }: HttpContext) { + const thread = await Thread.findByOrFail('slug', params.slug) + if (!(await auth.user!.canManageContent(thread.userId))) { + session.flash('error', 'Seul l’auteur de la question peut retirer la solution.') + return response.redirect().back() + } + await db.from('threads').where('id', thread.id).update({ solution_reply_id: null }) + session.flash('success', 'La solution a été retirée. La question est de nouveau ouverte.') + return response.redirect().back() + } + + /** + * POST /forum/:slug/pin — moderators only, toggles. + */ + async togglePin({ params, auth, response, session }: HttpContext) { + const thread = await Thread.findByOrFail('slug', params.slug) + if (!auth.user!.isModerator) { + session.flash('error', 'Action réservée aux modérateurs.') + return response.redirect().back() + } + const pinned = thread.pinnedAt === null + await db + .from('threads') + .where('id', thread.id) + .update({ pinned_at: pinned ? new Date() : null }) + session.flash( + 'success', + pinned ? 'Question épinglée en haut du forum.' : 'Question désépinglée.' + ) + return response.redirect().back() + } + + /** + * POST /forum/:slug/lock — moderators only, toggles. + */ + async toggleLock({ params, auth, response, session }: HttpContext) { + const thread = await Thread.findByOrFail('slug', params.slug) + if (!auth.user!.isModerator) { + session.flash('error', 'Action réservée aux modérateurs.') + return response.redirect().back() + } + const locked = thread.lockedAt === null + await db + .from('threads') + .where('id', thread.id) + .update({ locked_at: locked ? new Date() : null }) + session.flash( + 'success', + locked ? 'Sujet verrouillé : plus de nouvelles réponses.' : 'Sujet déverrouillé.' + ) + return response.redirect().back() + } +} diff --git a/app/controllers/threads_controller.ts b/app/controllers/threads_controller.ts new file mode 100644 index 0000000..20260d5 --- /dev/null +++ b/app/controllers/threads_controller.ts @@ -0,0 +1,304 @@ +import { markSubjectRead } from '#services/notifications' +import type { HttpContext } from '@adonisjs/core/http' +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import { errors as lucidErrors } from '@adonisjs/lucid' +import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model' +import Thread from '#models/thread' +import Channel from '#models/channel' +import Reply from '#models/reply' +import User from '#models/user' +import ThreadTransformer from '#transformers/thread_transformer' +import ChannelTransformer from '#transformers/channel_transformer' +import ReplyTransformer from '#transformers/reply_transformer' +import UserTransformer from '#transformers/user_transformer' +import { threadValidator } from '#validators/thread_validator' +import { plainExcerpt, renderMarkdown } from '#services/markdown' +import { uniqueSlug } from '#services/slug' +import { withReplyMeta } from '#services/reply_service' + +const PER_PAGE = 20 +export const THREAD_REPLIES_PER_PAGE = 50 + +const FILTERS = ['sans-reponse', 'non-resolues', 'resolues'] as const +type Filter = (typeof FILTERS)[number] + +/** + * "%term%" for ILIKE, with the LIKE wildcards of the term escaped. + */ +function likePattern(term: string) { + return `%${term.replace(/[\\%_]/g, (char) => `\\${char}`)}%` +} + +function toPage(value: unknown) { + const page = Number.parseInt(String(value ?? '1'), 10) + return Number.isFinite(page) && page > 0 ? page : 1 +} + +/** + * Count one view per visitor session (replying, accepting a solution or + * reloading the page must not inflate the counter). + */ +function isFirstView(session: HttpContext['session'], key: string) { + const seen: string[] = session.get('seen_content', []) + if (seen.includes(key)) return false + session.put('seen_content', [...seen.slice(-39), key]) + return true +} + +export default class ThreadsController { + /** + * GET /forum — channel index, status filters, search. + */ + async index({ request, inertia }: HttpContext) { + const qs = request.qs() + const q = typeof qs.q === 'string' ? qs.q.trim().slice(0, 120) : '' + const filter: Filter | null = FILTERS.includes(qs.filter) ? qs.filter : null + const page = toPage(qs.page) + + const channels = await Channel.query().withCount('threads').orderBy('position', 'asc') + + let channel: Channel | null = null + if (typeof qs.channel === 'string' && qs.channel !== '') { + channel = channels.find((c) => c.slug === qs.channel) ?? null + if (!channel) throw new lucidErrors.E_ROW_NOT_FOUND(Channel) + } + + // The current selection (channel + search), shared by the list and the stats. + const selection = (query: ModelQueryBuilderContract) => { + if (channel) query.where('channel_id', channel.id) + if (q) { + const pattern = likePattern(q) + query.where((sub) => sub.whereILike('title', pattern).orWhereILike('body', pattern)) + } + return query + } + + const listQuery = selection(Thread.query().preload('author').preload('channel')) + if (filter === 'sans-reponse') listQuery.where('replies_count', 0) + if (filter === 'non-resolues') listQuery.whereNull('solution_reply_id') + if (filter === 'resolues') listQuery.whereNotNull('solution_reply_id') + + const [threads, statsRows] = await Promise.all([ + listQuery + .orderByRaw('pinned_at desc nulls last') + .orderBy('last_activity_at', 'desc') + .orderBy('id', 'desc') + .paginate(page, PER_PAGE), + selection(Thread.query()) + .select( + db.raw('count(*)::int as total'), + db.raw('count(*) filter (where solution_reply_id is not null)::int as solved'), + db.raw('count(*) filter (where replies_count = 0)::int as unanswered') + ) + .pojo<{ total: number; solved: number; unanswered: number }>(), + ]) + + const total = Number(statsRows[0]?.total ?? 0) + const solved = Number(statsRows[0]?.solved ?? 0) + const unanswered = Number(statsRows[0]?.unanswered ?? 0) + + return inertia.render('forum/index', { + threads: ThreadTransformer.paginate(threads.all(), threads.getMeta()).useVariant('forList'), + channels: ChannelTransformer.transform(channels), + filters: { channel: channel?.slug ?? null, filter, q }, + stats: { + total, + solved, + unanswered, + unsolved: total - solved, + solvedRate: total ? Math.round((solved / total) * 100) : 0, + allThreads: channels.reduce((sum, c) => sum + Number(c.$extras.threads_count ?? 0), 0), + }, + }) + } + + /** + * GET /forum/nouveau + */ + async create({ request, inertia }: HttpContext) { + const channels = await Channel.query().orderBy('position', 'asc') + const preselected = channels.find((c) => c.slug === request.qs().channel) + return inertia.render('forum/create', { + channels: ChannelTransformer.transform(channels), + defaultChannelId: preselected?.id ?? null, + }) + } + + /** + * POST /forum + */ + async store({ request, auth, response, session }: HttpContext) { + const data = await request.validateUsing(threadValidator) + const thread = new Thread() + thread.userId = auth.user!.id + thread.channelId = data.channelId + thread.title = data.title + thread.body = data.body + thread.bodyHtml = await renderMarkdown(data.body) + thread.slug = await uniqueSlug('threads', data.title) + thread.lastActivityAt = DateTime.now() + await thread.save() + + session.flash('success', 'Votre question est publiée. La communauté va pouvoir vous répondre.') + return response.redirect().toPath(`/forum/${thread.slug}`) + } + + /** + * GET /forum/:slug + */ + async show({ params, request, auth, inertia, session }: HttpContext) { + const viewer = auth.user ?? null + const thread = await Thread.query() + .where('slug', params.slug) + .preload('author') + .preload('channel') + .firstOrFail() + + if (viewer) await markSubjectRead(viewer.id, { threadId: thread.id }) + + if (viewer?.id !== thread.userId && isFirstView(session, `t${thread.id}`)) { + await db.from('threads').where('id', thread.id).increment('views_count', 1) + thread.viewsCount += 1 + } + + // Replies: everything on one page, unless the thread is very long. + const repliesQuery = Reply.query().where('thread_id', thread.id) + withReplyMeta(viewer)(repliesQuery) + repliesQuery.orderBy('id', 'asc') + + const paginated = thread.repliesCount > THREAD_REPLIES_PER_PAGE + let replies: Reply[] + let repliesMeta: { + total: number + perPage: number + currentPage: number + lastPage: number + } | null = null + if (paginated) { + const paginator = await repliesQuery.paginate( + toPage(request.qs().page), + THREAD_REPLIES_PER_PAGE + ) + replies = paginator.all() + const meta = paginator.getMeta() + repliesMeta = { + total: Number(meta.total), + perPage: Number(meta.perPage), + currentPage: Number(meta.currentPage), + lastPage: Number(meta.lastPage), + } + } else { + replies = await repliesQuery + } + + // The accepted answer may live on another page of replies. + let solution: Reply | null = null + let solutionHref: string | null = null + if (thread.solutionReplyId) { + solution = + replies.find((reply) => reply.id === thread.solutionReplyId) ?? + (await Reply.query().where('id', thread.solutionReplyId).preload('author').first()) + if (solution) { + let solutionPage = 1 + if (paginated) { + const [{ n }] = await db + .from('replies') + .where('thread_id', thread.id) + .where('id', '<', solution.id) + .count('* as n') + solutionPage = Math.floor(Number(n) / THREAD_REPLIES_PER_PAGE) + 1 + } + solutionHref = `${solutionPage > 1 ? `?page=${solutionPage}` : ''}#reponse-${solution.id}` + } + } + + const [participantRows, similar] = await Promise.all([ + db + .from('replies') + .select('user_id') + .min('created_at as first_at') + .where('thread_id', thread.id) + .groupBy('user_id') + .orderBy('first_at', 'asc'), + Thread.query() + .where('channel_id', thread.channelId) + .whereNot('id', thread.id) + .orderByRaw('solution_reply_id is null') + .orderBy('last_activity_at', 'desc') + .limit(5), + ]) + + const participantIds: number[] = participantRows.map((row) => Number(row.user_id)) + const participantUsers = participantIds.length + ? await User.query().whereIn('id', participantIds.slice(0, 16)) + : [] + participantUsers.sort((a, b) => participantIds.indexOf(a.id) - participantIds.indexOf(b.id)) + + return inertia.render('forum/show', { + thread: ThreadTransformer.transform(thread).useVariant('forDetail'), + replies: ReplyTransformer.transform(replies), + repliesMeta, + solution: solution ? ReplyTransformer.transform(solution) : null, + solutionExcerpt: solution ? plainExcerpt(solution.body, 260) : null, + solutionHref, + participants: UserTransformer.transform(participantUsers), + participantsCount: participantIds.length, + similar: ThreadTransformer.transform(similar), + can: { + manage: Boolean(viewer && (await viewer.canManageContent(thread.userId))), + moderate: Boolean(viewer?.isModerator), + }, + }) + } + + /** + * GET /forum/:slug/modifier + */ + async edit({ params, auth, inertia, response, session }: HttpContext) { + const thread = await Thread.query().where('slug', params.slug).preload('channel').firstOrFail() + if (!(await auth.user!.canManageContent(thread.userId))) { + session.flash('error', 'Vous ne pouvez pas modifier cette question.') + return response.redirect().toPath(`/forum/${thread.slug}`) + } + const channels = await Channel.query().orderBy('position', 'asc') + return inertia.render('forum/edit', { + thread: ThreadTransformer.transform(thread).useVariant('forEdit'), + channels: ChannelTransformer.transform(channels), + }) + } + + /** + * PUT /forum/:slug — the slug never changes (links stay valid). + */ + async update({ params, request, auth, response, session }: HttpContext) { + const thread = await Thread.findByOrFail('slug', params.slug) + if (!(await auth.user!.canManageContent(thread.userId))) { + session.flash('error', 'Vous ne pouvez pas modifier cette question.') + return response.redirect().toPath(`/forum/${thread.slug}`) + } + const data = await request.validateUsing(threadValidator) + thread.title = data.title + thread.channelId = data.channelId + thread.body = data.body + thread.bodyHtml = await renderMarkdown(data.body) + await thread.save() + + session.flash('success', 'Question mise à jour.') + return response.redirect().toPath(`/forum/${thread.slug}`) + } + + /** + * DELETE /forum/:slug — replies go with it (FK cascade). + */ + async destroy({ params, auth, response, session }: HttpContext) { + const thread = await Thread.findByOrFail('slug', params.slug) + if (!(await auth.user!.canManageContent(thread.userId))) { + session.flash('error', 'Vous ne pouvez pas supprimer cette question.') + return response.redirect().toPath(`/forum/${thread.slug}`) + } + await thread.delete() + session.flash('success', 'La question a été supprimée.') + return response.redirect().toPath('/forum') + } +} diff --git a/app/exceptions/handler.ts b/app/exceptions/handler.ts index 0ab9d3b..75d7d9e 100644 --- a/app/exceptions/handler.ts +++ b/app/exceptions/handler.ts @@ -1,5 +1,5 @@ import app from '@adonisjs/core/services/app' -import { HttpContext, ExceptionHandler } from '@adonisjs/core/http' +import { type HttpContext, ExceptionHandler } from '@adonisjs/core/http' import type { StatusPageRange, StatusPageRenderer } from '@adonisjs/core/types/http' export default class HttpExceptionHandler extends ExceptionHandler { @@ -21,8 +21,8 @@ export default class HttpExceptionHandler extends ExceptionHandler { * to return the HTML contents to send as a response. */ protected statusPages: Record = { - '404': (error, { inertia }) => inertia.render('errors/not_found', { error }), - '500..599': (error, { inertia }) => inertia.render('errors/server_error', { error }), + '404': (_, { inertia }) => inertia.render('errors/not_found', {}), + '500..599': (_, { inertia }) => inertia.render('errors/server_error', {}), } /** diff --git a/app/exceptions/markdown_too_complex_exception.ts b/app/exceptions/markdown_too_complex_exception.ts new file mode 100644 index 0000000..0e3e65d --- /dev/null +++ b/app/exceptions/markdown_too_complex_exception.ts @@ -0,0 +1,22 @@ +import { Exception } from '@adonisjs/core/exceptions' +import type { HttpContext } from '@adonisjs/core/http' + +/** + * Raised when markdown takes too long to render (pathological input). + * Sends the member back to the form with an explanation instead of a 500. + */ +export default class MarkdownTooComplexException extends Exception { + static status = 422 + static code = 'E_MARKDOWN_TOO_COMPLEX' + static message = + 'Ce contenu est trop complexe à mettre en forme. Simplifiez la mise en forme (gras, italique, liens imbriqués) puis réessayez.' + + async handle(error: this, ctx: HttpContext) { + if (ctx.request.accepts(['html', 'json']) === 'json' && !ctx.request.header('x-inertia')) { + return ctx.response.status(error.status).send({ message: error.message }) + } + ctx.session.flashExcept(['password', 'passwordConfirmation']) + ctx.session.flash('error', error.message) + return ctx.response.redirect().back() + } +} diff --git a/app/middleware/auth_middleware.ts b/app/middleware/auth_middleware.ts index f5a2ba3..75eb64e 100644 --- a/app/middleware/auth_middleware.ts +++ b/app/middleware/auth_middleware.ts @@ -4,12 +4,10 @@ import type { Authenticators } from '@adonisjs/auth/types' /** * Auth middleware is used authenticate HTTP requests and deny - * access to unauthenticated users. + * access to unauthenticated users. GET requests are sent back to the + * page they asked for after login. */ export default class AuthMiddleware { - /** - * The URL to redirect to, when authentication fails - */ redirectTo = '/login' async handle( @@ -19,7 +17,19 @@ export default class AuthMiddleware { guards?: (keyof Authenticators)[] } = {} ) { - await ctx.auth.authenticateUsing(options.guards, { loginRoute: this.redirectTo }) + const loginRoute = + ctx.request.method() === 'GET' + ? `${this.redirectTo}?redirect=${encodeURIComponent(ctx.request.url(true))}` + : this.redirectTo + + await ctx.auth.authenticateUsing(options.guards, { loginRoute }) + + if (ctx.auth.user?.bannedAt) { + await ctx.auth.use('web').logout() + ctx.session.flash('error', 'Ce compte a été suspendu.') + return ctx.response.redirect(this.redirectTo) + } + return next() } } diff --git a/app/middleware/container_bindings_middleware.ts b/app/middleware/container_bindings_middleware.ts index bbe5a07..8f5322b 100644 --- a/app/middleware/container_bindings_middleware.ts +++ b/app/middleware/container_bindings_middleware.ts @@ -1,6 +1,6 @@ import { Logger } from '@adonisjs/core/logger' import { HttpContext } from '@adonisjs/core/http' -import { NextFn } from '@adonisjs/core/types/http' +import { type NextFn } from '@adonisjs/core/types/http' /** * The container bindings middleware binds classes to their request @@ -13,6 +13,7 @@ export default class ContainerBindingsMiddleware { handle(ctx: HttpContext, next: NextFn) { ctx.containerResolver.bindValue(HttpContext, ctx) ctx.containerResolver.bindValue(Logger, ctx.logger) + return next() } } diff --git a/app/middleware/guest_middleware.ts b/app/middleware/guest_middleware.ts index 15b2ddc..d032760 100644 --- a/app/middleware/guest_middleware.ts +++ b/app/middleware/guest_middleware.ts @@ -22,9 +22,11 @@ export default class GuestMiddleware { ) { for (let guard of options.guards || [ctx.auth.defaultGuard]) { if (await ctx.auth.use(guard).check()) { + ctx.session.reflash() return ctx.response.redirect(this.redirectTo, true) } } + return next() } } diff --git a/app/middleware/inertia_middleware.ts b/app/middleware/inertia_middleware.ts new file mode 100644 index 0000000..c8bdb26 --- /dev/null +++ b/app/middleware/inertia_middleware.ts @@ -0,0 +1,88 @@ +import type { HttpContext } from '@adonisjs/core/http' +import type { NextFn } from '@adonisjs/core/types/http' +import UserTransformer from '#transformers/user_transformer' +import BaseInertiaMiddleware from '@adonisjs/inertia/inertia_middleware' +import { githubEnabled } from '#config/ally' +import env from '#start/env' +import db from '@adonisjs/lucid/services/db' +import { reportQueueCounts } from '#controllers/admin/reports_controller' + +export type ThemePreference = 'light' | 'dark' | 'system' + +export default class InertiaMiddleware extends BaseInertiaMiddleware { + async share(ctx: HttpContext) { + /** + * The share method is called everytime an Inertia page is rendered. In + * certain cases, a page may get rendered before the session middleware + * or the auth middleware are executed. For example: During a 404 request. + * + * In that case, we must always assume that HttpContext is not fully hydrated + * with all the properties + */ + const { auth, request } = ctx as Partial + + const cookie = request?.plainCookie('app_theme', { encoded: false }) + const theme: ThemePreference = cookie === 'light' || cookie === 'dark' ? cookie : 'system' + + let unreadNotifications = 0 + if (auth?.user) { + const [row] = await db + .from('notifications') + .where('user_id', auth.user.id) + .whereNull('read_at') + .count('* as total') + unreadNotifications = Number(row?.total ?? 0) + } + + // Moderation queue badge (staff only: no query for regular members). + let reportQueueCount = 0 + if (auth?.user?.isModerator) { + const counts = await reportQueueCounts() + reportQueueCount = counts.open + } + + /** + * Data shared with all Inertia pages. Make sure you are using + * transformers for rich data-types like Models. + */ + return { + errors: ctx.inertia.always(this.getValidationErrors(ctx)), + user: ctx.inertia.always( + auth?.user ? UserTransformer.transform(auth.user).useVariant('forSession') : undefined + ), + preferences: ctx.inertia.always({ theme }), + features: ctx.inertia.always({ github: githubEnabled() }), + site: ctx.inertia.always({ url: env.get('APP_URL') }), + unreadNotifications: ctx.inertia.always(unreadNotifications), + reportQueueCount: ctx.inertia.always(reportQueueCount), + } + } + + flash(ctx: HttpContext) { + /** + * Flash messages travel in the dedicated `flash` field of the page + * object instead of props, and the client strips them from history + * state so they never reappear when navigating back. + */ + const { session } = ctx as Partial + + const success: string | undefined = session?.flashMessages.get('success') + const error: string | undefined = session?.flashMessages.get('error') + + return { success, error } + } + + async handle(ctx: HttpContext, next: NextFn) { + await this.init(ctx) + + const output = await next() + this.dispose(ctx) + + return output + } +} + +declare module '@adonisjs/inertia/types' { + type MiddlewareSharedProps = InferSharedProps + export interface SharedProps extends MiddlewareSharedProps {} +} diff --git a/app/middleware/role_middleware.ts b/app/middleware/role_middleware.ts new file mode 100644 index 0000000..bce8ba4 --- /dev/null +++ b/app/middleware/role_middleware.ts @@ -0,0 +1,48 @@ +import type { HttpContext } from '@adonisjs/core/http' +import type { NextFn } from '@adonisjs/core/types/http' + +export type RequiredRole = 'moderator' | 'admin' + +/** + * Restricts a route to the staff. Must run after the "auth" middleware. + * + * - `middleware.role()` or `middleware.role({ role: 'moderator' })`: moderators and admins + * - `middleware.role({ role: 'admin' })`: admins only + * + * Forbidden GET requests are sent to the dashboard, other requests back to + * the previous page, both with a flash message (Inertia friendly). + */ +export default class RoleMiddleware { + async handle(ctx: HttpContext, next: NextFn, options: { role?: RequiredRole } = {}) { + const role = options.role ?? 'moderator' + const user = ctx.auth.user + + if (!user) { + return ctx.response + .redirect() + .toPath(`/login?redirect=${encodeURIComponent(ctx.request.url(true))}`) + } + + const allowed = role === 'admin' ? user.isAdmin : user.isModerator + if (allowed) { + return next() + } + + const message = + role === 'admin' + ? 'Cette action est réservée aux administrateurs.' + : 'Cet espace est réservé à l’équipe de modération.' + + const wantsJson = + !ctx.request.header('x-inertia') && ctx.request.accepts(['html', 'json']) === 'json' + if (wantsJson) { + return ctx.response.forbidden({ message }) + } + + ctx.session.flash('error', message) + if (ctx.request.method() === 'GET') { + return ctx.response.redirect().toPath('/dashboard') + } + return ctx.response.redirect().back() + } +} diff --git a/app/middleware/silent_auth_middleware.ts b/app/middleware/silent_auth_middleware.ts index 869411a..5c3a154 100644 --- a/app/middleware/silent_auth_middleware.ts +++ b/app/middleware/silent_auth_middleware.ts @@ -1,16 +1,40 @@ import type { HttpContext } from '@adonisjs/core/http' import type { NextFn } from '@adonisjs/core/types/http' +/** + * Session key holding the user's session version at sign-in time. + */ +export const SESSION_VERSION_KEY = 'session_version' + /** * Silent auth middleware can be used as a global middleware to silent check - * if the user is logged-in or not. + * if the user is logged-in or not. It also signs out, whatever the page: + * - banned members; + * - sessions opened before a password change (stale session version). * * The request continues as usual, even when the user is not logged-in. */ export default class SilentAuthMiddleware { async handle(ctx: HttpContext, next: NextFn) { - // Check authentication without redirecting await ctx.auth.check() + const user = ctx.auth.user + if (!user) return next() + + if (user.bannedAt) { + await ctx.auth.use('web').logout() + ctx.session.flash('error', 'Ce compte a été suspendu.') + return next() + } + + const stamp = ctx.session.get(SESSION_VERSION_KEY) + if (stamp === undefined) { + // Fresh sign-in (or a session restored from a valid remember-me token). + ctx.session.put(SESSION_VERSION_KEY, user.sessionVersion) + } else if (stamp !== user.sessionVersion) { + await ctx.auth.use('web').logout() + ctx.session.forget(SESSION_VERSION_KEY) + ctx.session.flash('error', 'Votre mot de passe a été modifié : reconnectez-vous.') + } return next() } diff --git a/app/models/article.ts b/app/models/article.ts index 766ff19..12bcf4f 100644 --- a/app/models/article.ts +++ b/app/models/article.ts @@ -1,45 +1,30 @@ import { DateTime } from 'luxon' -import { BaseModel, belongsTo, column } from '@adonisjs/lucid/orm' -import type { BelongsTo } from '@adonisjs/lucid/types/relations' -import string from '@adonisjs/core/helpers/string' +import { ArticleSchema } from '#database/schema' +import { belongsTo, hasMany, manyToMany, scope } from '@adonisjs/lucid/orm' +import type { BelongsTo, HasMany, ManyToMany } from '@adonisjs/lucid/types/relations' import User from '#models/user' +import Tag from '#models/tag' +import Reply from '#models/reply' +import Like from '#models/like' -export default class Article extends BaseModel { - @column({ isPrimary: true }) - declare id: number - - @column() - declare title: string - - @column() - declare slug: string - - @column() - declare content: string - - @column() - declare excerpt: string - - @column() - declare isPublished: boolean - - @column() - declare authorId: number - - @belongsTo(() => User, { foreignKey: 'authorId' }) +export default class Article extends ArticleSchema { + @belongsTo(() => User) declare author: BelongsTo - @column.dateTime({ autoCreate: true }) - declare createdAt: DateTime + @manyToMany(() => Tag, { pivotTable: 'article_tag' }) + declare tags: ManyToMany + + @hasMany(() => Reply) + declare comments: HasMany - @column.dateTime({ autoCreate: true, autoUpdate: true }) - declare updatedAt: DateTime + @hasMany(() => Like) + declare likes: HasMany - @column.dateTime() - declare publishedAt: DateTime | null + static published = scope((query) => { + query.whereNotNull('published_at').where('published_at', '<=', DateTime.now().toSQL()!) + }) - // Generate slug before saving - public async generateSlug() { - this.slug = string.slug(this.title) + get isPublished() { + return this.publishedAt !== null && this.publishedAt <= DateTime.now() } } diff --git a/app/models/channel.ts b/app/models/channel.ts new file mode 100644 index 0000000..76b0af7 --- /dev/null +++ b/app/models/channel.ts @@ -0,0 +1,9 @@ +import { ChannelSchema } from '#database/schema' +import { hasMany } from '@adonisjs/lucid/orm' +import type { HasMany } from '@adonisjs/lucid/types/relations' +import Thread from '#models/thread' + +export default class Channel extends ChannelSchema { + @hasMany(() => Thread) + declare threads: HasMany +} diff --git a/app/models/discussion.ts b/app/models/discussion.ts new file mode 100644 index 0000000..e359114 --- /dev/null +++ b/app/models/discussion.ts @@ -0,0 +1,21 @@ +import { DiscussionSchema } from '#database/schema' +import { belongsTo, hasMany, manyToMany } from '@adonisjs/lucid/orm' +import type { BelongsTo, HasMany, ManyToMany } from '@adonisjs/lucid/types/relations' +import User from '#models/user' +import Tag from '#models/tag' +import Reply from '#models/reply' + +export default class Discussion extends DiscussionSchema { + @belongsTo(() => User) + declare author: BelongsTo + + @manyToMany(() => Tag, { pivotTable: 'discussion_tag' }) + declare tags: ManyToMany + + @hasMany(() => Reply) + declare replies: HasMany + + get isLocked() { + return this.lockedAt !== null + } +} diff --git a/app/models/like.ts b/app/models/like.ts new file mode 100644 index 0000000..f141bac --- /dev/null +++ b/app/models/like.ts @@ -0,0 +1,9 @@ +import { LikeSchema } from '#database/schema' +import { belongsTo } from '@adonisjs/lucid/orm' +import type { BelongsTo } from '@adonisjs/lucid/types/relations' +import User from '#models/user' + +export default class Like extends LikeSchema { + @belongsTo(() => User) + declare user: BelongsTo +} diff --git a/app/models/notification.ts b/app/models/notification.ts new file mode 100644 index 0000000..cfa64cb --- /dev/null +++ b/app/models/notification.ts @@ -0,0 +1,34 @@ +import { NotificationSchema } from '#database/schema' +import { belongsTo } from '@adonisjs/lucid/orm' +import type { BelongsTo } from '@adonisjs/lucid/types/relations' +import User from '#models/user' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Article from '#models/article' +import Reply from '#models/reply' + +export type NotificationType = Notification['type'] + +export default class Notification extends NotificationSchema { + @belongsTo(() => User) + declare user: BelongsTo + + @belongsTo(() => User, { foreignKey: 'actorId' }) + declare actor: BelongsTo + + @belongsTo(() => Thread) + declare thread: BelongsTo + + @belongsTo(() => Discussion) + declare discussion: BelongsTo + + @belongsTo(() => Article) + declare article: BelongsTo + + @belongsTo(() => Reply) + declare reply: BelongsTo + + get isRead() { + return this.readAt !== null + } +} diff --git a/app/models/reply.ts b/app/models/reply.ts new file mode 100644 index 0000000..a4bc964 --- /dev/null +++ b/app/models/reply.ts @@ -0,0 +1,30 @@ +import { ReplySchema } from '#database/schema' +import { belongsTo, hasMany } from '@adonisjs/lucid/orm' +import type { BelongsTo, HasMany } from '@adonisjs/lucid/types/relations' +import User from '#models/user' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Article from '#models/article' +import Like from '#models/like' + +/** + * A reply to a forum thread, a discussion, or a comment on an article. + * Exactly one of threadId / discussionId / articleId is set (enforced by a + * CHECK constraint in the database). + */ +export default class Reply extends ReplySchema { + @belongsTo(() => User) + declare author: BelongsTo + + @belongsTo(() => Thread) + declare thread: BelongsTo + + @belongsTo(() => Discussion) + declare discussion: BelongsTo + + @belongsTo(() => Article) + declare article: BelongsTo + + @hasMany(() => Like) + declare likes: HasMany +} diff --git a/app/models/report.ts b/app/models/report.ts new file mode 100644 index 0000000..86abae0 --- /dev/null +++ b/app/models/report.ts @@ -0,0 +1,31 @@ +import { ReportSchema } from '#database/schema' +import { belongsTo } from '@adonisjs/lucid/orm' +import type { BelongsTo } from '@adonisjs/lucid/types/relations' +import User from '#models/user' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Article from '#models/article' +import Reply from '#models/reply' + +export type ReportReason = Report['reason'] +export type ReportStatus = Report['status'] + +export default class Report extends ReportSchema { + @belongsTo(() => User, { foreignKey: 'reporterId' }) + declare reporter: BelongsTo + + @belongsTo(() => User, { foreignKey: 'resolvedById' }) + declare resolvedBy: BelongsTo + + @belongsTo(() => Article) + declare article: BelongsTo + + @belongsTo(() => Thread) + declare thread: BelongsTo + + @belongsTo(() => Discussion) + declare discussion: BelongsTo + + @belongsTo(() => Reply) + declare reply: BelongsTo +} diff --git a/app/models/tag.ts b/app/models/tag.ts new file mode 100644 index 0000000..25a0dba --- /dev/null +++ b/app/models/tag.ts @@ -0,0 +1,13 @@ +import { TagSchema } from '#database/schema' +import { manyToMany } from '@adonisjs/lucid/orm' +import type { ManyToMany } from '@adonisjs/lucid/types/relations' +import Article from '#models/article' +import Discussion from '#models/discussion' + +export default class Tag extends TagSchema { + @manyToMany(() => Article, { pivotTable: 'article_tag' }) + declare articles: ManyToMany + + @manyToMany(() => Discussion, { pivotTable: 'discussion_tag' }) + declare discussions: ManyToMany +} diff --git a/app/models/thread.ts b/app/models/thread.ts new file mode 100644 index 0000000..5bb7f08 --- /dev/null +++ b/app/models/thread.ts @@ -0,0 +1,28 @@ +import { ThreadSchema } from '#database/schema' +import { belongsTo, hasMany } from '@adonisjs/lucid/orm' +import type { BelongsTo, HasMany } from '@adonisjs/lucid/types/relations' +import User from '#models/user' +import Channel from '#models/channel' +import Reply from '#models/reply' + +export default class Thread extends ThreadSchema { + @belongsTo(() => User) + declare author: BelongsTo + + @belongsTo(() => Channel) + declare channel: BelongsTo + + @hasMany(() => Reply) + declare replies: HasMany + + @belongsTo(() => Reply, { foreignKey: 'solutionReplyId' }) + declare solution: BelongsTo + + get isSolved() { + return this.solutionReplyId !== null + } + + get isLocked() { + return this.lockedAt !== null + } +} diff --git a/app/models/user.ts b/app/models/user.ts index b39d318..448ba97 100644 --- a/app/models/user.ts +++ b/app/models/user.ts @@ -1,77 +1,73 @@ -import { DateTime } from 'luxon' -import { BaseModel, column, hasMany } from '@adonisjs/lucid/orm' -import { compose } from '@adonisjs/core/helpers' +import { UserSchema } from '#database/schema' import hash from '@adonisjs/core/services/hash' -import { withAuthFinder } from '@adonisjs/auth/mixins/lucid' +import { compose } from '@adonisjs/core/helpers' +import { hasMany } from '@adonisjs/lucid/orm' import type { HasMany } from '@adonisjs/lucid/types/relations' -import Article from '#models/article' +import { withAuthFinder } from '@adonisjs/auth/mixins/lucid' import { DbRememberMeTokensProvider } from '@adonisjs/auth/session' +import Article from '#models/article' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import Reply from '#models/reply' + +export default class User extends compose( + UserSchema, + withAuthFinder(hash, { uids: ['email', 'username'], passwordColumnName: 'password' }) +) { + static rememberMeTokens = DbRememberMeTokensProvider.forModel(User) -const AuthFinder = withAuthFinder(() => hash.use('scrypt'), { - uids: ['email'], - passwordColumnName: 'password', -}) - -export default class User extends compose(BaseModel, AuthFinder) { - @column({ isPrimary: true }) - declare id: number - - @column() - declare username: string - - @column() - declare name: string | null - - @column() - declare email: string - - @column({ serializeAs: null }) - declare password: string - - @column() - declare avatar: string | null - - @column() - declare githubId: string | null + @hasMany(() => Article) + declare articles: HasMany - @column() - declare twitterId: string | null + @hasMany(() => Thread) + declare threads: HasMany - @column() - declare isAdmin: boolean + @hasMany(() => Discussion) + declare discussions: HasMany - @column() - declare isSponsor: boolean + @hasMany(() => Reply) + declare replies: HasMany - @column.dateTime() - declare emailVerifiedAt: DateTime | null + get displayName() { + return this.name || this.username + } - @column() - declare rememberMeToken: string | null + get initials() { + const parts = this.displayName.trim().split(/\s+/) + const [first, last] = parts + if (first && last) { + return `${first.charAt(0)}${last.charAt(0)}`.toUpperCase() + } + return this.displayName.slice(0, 2).toUpperCase() + } - @column.dateTime({ autoCreate: true }) - declare createdAt: DateTime + get isAdmin() { + return this.role === 'admin' + } - @column.dateTime({ autoCreate: true, autoUpdate: true }) - declare updatedAt: DateTime + get isModerator() { + return this.role === 'admin' || this.role === 'moderator' + } - @hasMany(() => Article) - declare articles: HasMany + get isBanned() { + return this.bannedAt !== null + } - static rememberMeTokens = DbRememberMeTokensProvider.forModel(User) + /** + * Drafts and other non-public content: visible to their owner and staff. + */ + canSeeDraftsOf(ownerId: number) { + return this.id === ownerId || this.isModerator + } /** - * Serialize the model for Inertia + * Edit/delete rights on content owned by "ownerId": the owner, admins, + * and moderators on regular members' content (never on other staff's). */ - serialize() { - return { - id: this.id, - username: this.username, - name: this.name, - email: this.email, - avatar: this.avatar, - isAdmin: this.isAdmin, - isSponsor: this.isSponsor, - } + async canManageContent(ownerId: number) { + if (this.id === ownerId || this.isAdmin) return true + if (!this.isModerator) return false + const owner = await User.query().select('role').where('id', ownerId).first() + return owner?.role === 'member' } } diff --git a/app/services/github_oauth.ts b/app/services/github_oauth.ts new file mode 100644 index 0000000..e93ad47 --- /dev/null +++ b/app/services/github_oauth.ts @@ -0,0 +1,110 @@ +import string from '@adonisjs/core/helpers/string' +import type { HttpContext } from '@adonisjs/core/http' +import socialConfig from '#config/ally' +import env from '#start/env' + +const STATE_COOKIE = 'gh_oauth_state' + +export type GithubProfile = { + id: string + login: string + name: string | null + email: string | null + avatarUrl: string | null + bio: string | null + location: string | null + blog: string | null + twitterUsername: string | null +} + +function callbackUrl() { + return new URL(socialConfig.github.callbackPath, env.get('APP_URL')).toString() +} + +/** + * Minimal GitHub OAuth (authorization code flow) with CSRF state cookie. + */ +export default class GithubOAuth { + constructor(private ctx: HttpContext) {} + + redirectUrl() { + const state = string.random(32) + this.ctx.response.encryptedCookie(STATE_COOKIE, state, { + maxAge: '10m', + httpOnly: true, + sameSite: 'lax', + }) + + const url = new URL('https://github.com/login/oauth/authorize') + url.searchParams.set('client_id', socialConfig.github.clientId!) + url.searchParams.set('redirect_uri', callbackUrl()) + url.searchParams.set('scope', socialConfig.github.scopes.join(' ')) + url.searchParams.set('state', state) + url.searchParams.set('allow_signup', 'true') + return url.toString() + } + + /** + * Validate the callback and fetch the GitHub profile. Returns null when + * the user denied access or the state does not match. + */ + async user(): Promise { + const { request, response } = this.ctx + const expectedState = request.encryptedCookie(STATE_COOKIE) + response.clearCookie(STATE_COOKIE) + + const code = request.input('code') + const state = request.input('state') + if (!code || !state || !expectedState || state !== expectedState) { + return null + } + + const tokenResponse = await fetch('https://github.com/login/oauth/access_token', { + method: 'POST', + headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify({ + client_id: socialConfig.github.clientId, + client_secret: socialConfig.github.clientSecret, + code, + redirect_uri: callbackUrl(), + }), + }) + const token = (await tokenResponse.json()) as { access_token?: string } + if (!token.access_token) return null + + const headers = { + 'Accept': 'application/vnd.github+json', + 'Authorization': `Bearer ${token.access_token}`, + 'User-Agent': 'javascript.cm', + } + + const profileResponse = await fetch('https://api.github.com/user', { headers }) + if (!profileResponse.ok) return null + const profile = (await profileResponse.json()) as Record + + let email: string | null = profile.email ?? null + if (!email) { + const emailsResponse = await fetch('https://api.github.com/user/emails', { headers }) + if (emailsResponse.ok) { + const emails = (await emailsResponse.json()) as { + email: string + primary: boolean + verified: boolean + }[] + email = emails.find((e) => e.primary && e.verified)?.email ?? null + } + } + + return { + id: String(profile.id), + login: profile.login, + name: profile.name ?? null, + email, + avatarUrl: profile.avatar_url ?? null, + bio: profile.bio ?? null, + location: profile.location ?? null, + blog: profile.blog || null, + twitterUsername: profile.twitter_username ?? null, + } + } +} diff --git a/app/services/markdown.ts b/app/services/markdown.ts new file mode 100644 index 0000000..041ce21 --- /dev/null +++ b/app/services/markdown.ts @@ -0,0 +1,187 @@ +import { Worker } from 'node:worker_threads' +import app from '@adonisjs/core/services/app' +import MarkdownTooComplexException from '#exceptions/markdown_too_complex_exception' + +/** + * Markdown is rendered in a dedicated worker thread with a time budget. + * Some inputs make CommonMark parsers quadratic (e.g. thousands of "*_"): + * here they cost one worker restart instead of freezing the whole server. + */ +const RENDER_TIMEOUT_MS = 5_000 + +type Job = { + id: number + source: string + resolve: (html: string) => void + reject: (error: Error) => void + timer?: NodeJS.Timeout +} + +// Pathname, not the raw URL: hot-hook appends a version query in development. +const isTypeScript = new URL(import.meta.url).pathname.endsWith('.ts') +const workerEntry = new URL(`./markdown_worker${isTypeScript ? '.ts' : '.js'}`, import.meta.url) + +/** + * In development the TypeScript loader hook lives in the main thread only, + * so the worker registers it before importing its (TypeScript) entry. + */ +const BOOTSTRAP = ` +const { workerData } = require('node:worker_threads') +;(async () => { + if (workerData.typescript) await import('@poppinss/ts-exec') + await import(workerData.entry) +})() +` + +class MarkdownRenderer { + #worker?: Worker + #jobs = new Map() + #nextId = 1 + + render(source: string) { + return new Promise((resolve, reject) => { + const job: Job = { id: this.#nextId++, source, resolve, reject } + this.#jobs.set(job.id, job) + this.#dispatch(job) + }) + } + + #dispatch(job: Job) { + job.timer = setTimeout(() => this.#timeout(job), RENDER_TIMEOUT_MS) + this.#getWorker().postMessage({ id: job.id, source: job.source }) + } + + #getWorker() { + if (!this.#worker) { + const worker = new Worker(BOOTSTRAP, { + eval: true, + workerData: { entry: workerEntry.href, typescript: isTypeScript }, + }) + worker.unref() + worker.on('message', ({ id, html, error }: { id: number; html?: string; error?: string }) => { + const job = this.#jobs.get(id) + if (!job) return + clearTimeout(job.timer) + this.#jobs.delete(id) + if (error !== undefined) job.reject(new Error(error)) + else job.resolve(html!) + }) + worker.on('error', (error: Error) => this.#restart(error)) + worker.on('exit', (code) => { + if (this.#worker === worker && code !== 0) + this.#restart(new Error(`Markdown worker exited (${code})`)) + }) + this.#worker = worker + } + return this.#worker + } + + /** + * The job that ran out of time is rejected; the others are replayed on + * a fresh worker. + */ + #timeout(job: Job) { + this.#jobs.delete(job.id) + job.reject(new MarkdownTooComplexException()) + this.#restart() + } + + /** + * Stop the worker (application shutdown). + */ + async close() { + const worker = this.#worker + this.#worker = undefined + for (const job of this.#jobs.values()) { + clearTimeout(job.timer) + job.reject(new Error('Markdown renderer closed')) + } + this.#jobs.clear() + await worker?.terminate() + } + + #restart(error?: Error) { + const worker = this.#worker + this.#worker = undefined + worker?.terminate().catch(() => {}) + for (const pending of this.#jobs.values()) { + clearTimeout(pending.timer) + if (error) { + this.#jobs.delete(pending.id) + pending.reject(error) + } else { + this.#dispatch(pending) + } + } + } +} + +const renderer = new MarkdownRenderer() +app.terminating(() => renderer.close()) + +/** + * Emphasis markers outside code are what make CommonMark parsing + * quadratic. Real prose uses a few dozen; reject absurd counts up front. + */ +const MAX_EMPHASIS_MARKERS = 2_000 + +function emphasisMarkers(source: string) { + const prose = withoutCodeBlocks(source).replace(/`[^`\n]*`/g, '') + let count = 0 + for (const char of prose) { + if (char === '*' || char === '_') count++ + } + return count +} + +/** + * Render member-written markdown to safe HTML (with syntax highlighting). + * Throws MarkdownTooComplexException when the time budget is exceeded. + */ +export async function renderMarkdown(source: string): Promise { + if (emphasisMarkers(source) > MAX_EMPHASIS_MARKERS) { + throw new MarkdownTooComplexException() + } + return renderer.render(source) +} + +/** + * Remove fenced code blocks in one linear pass (no backtracking regex). + */ +function withoutCodeBlocks(source: string) { + let inFence = false + const lines: string[] = [] + for (const line of source.split('\n')) { + if (/^\s{0,3}(```|~~~)/.test(line)) { + inFence = !inFence + continue + } + if (!inFence) lines.push(line) + } + return lines.join('\n') +} + +/** + * Estimated reading time in minutes (~220 words per minute). + */ +export function readingMinutes(source: string): number { + const words = withoutCodeBlocks(source).split(/\s+/).filter(Boolean).length + return Math.max(1, Math.round(words / 220)) +} + +/** + * Plain-text excerpt from markdown, used for meta descriptions and + * listings. Runs on every page view: the input is truncated first and the + * patterns are bounded, so the cost stays linear whatever the body. + */ +export function plainExcerpt(source: string, length = 180): string { + const text = withoutCodeBlocks(source.slice(0, length * 8)) + .replace(/^#{1,6}\s.*$/gm, ' ') + .replace(/`([^`\n]{0,200})`/g, '$1') + .replace(/!\[[^\]\n]{0,300}\]\([^)\n]{0,500}\)/g, ' ') + .replace(/\[([^\]\n]{0,300})\]\([^)\n]{0,500}\)/g, '$1') + .replace(/[*_~>#|-]+/g, ' ') + .replace(/\s+/g, ' ') + .trim() + return text.length > length ? `${text.slice(0, length - 1).trimEnd()}…` : text +} diff --git a/app/services/markdown_core.ts b/app/services/markdown_core.ts new file mode 100644 index 0000000..51d7a95 --- /dev/null +++ b/app/services/markdown_core.ts @@ -0,0 +1,84 @@ +/** + * Markdown → HTML pipeline (GFM, sanitized, Shiki dual theme). + * Imported by the worker thread only: keep it free of app imports. + */ +import { unified, type Processor } from 'unified' +import remarkParse from 'remark-parse' +import remarkGfm from 'remark-gfm' +import remarkRehype from 'remark-rehype' +import rehypeSanitize, { defaultSchema } from 'rehype-sanitize' +import rehypeShiki from '@shikijs/rehype' +import rehypeStringify from 'rehype-stringify' +import type { Root, Element, ElementContent, RootContent } from 'hast' + +/** + * Sanitization schema: GitHub-like defaults (raw HTML is never rendered, + * since remark-rehype runs without "allowDangerousHtml"), plus the + * "language-*" class on code blocks so Shiki can pick the grammar. + */ +const schema: typeof defaultSchema = { + ...defaultSchema, + clobberPrefix: 'md-', + attributes: { + ...defaultSchema.attributes, + code: [...(defaultSchema.attributes?.code ?? []), ['className', /^language-[\w-]+$/]], + }, +} + +/** + * Links written by members open in a new tab and never pass SEO juice. + */ +function rehypeExternalLinks() { + const walk = (nodes: (RootContent | ElementContent)[]) => { + for (const node of nodes) { + if (node.type !== 'element') continue + const el = node as Element + if (el.tagName === 'a' && typeof el.properties.href === 'string') { + const href = el.properties.href + if (/^https?:\/\//i.test(href)) { + el.properties.target = '_blank' + el.properties.rel = ['nofollow', 'ugc', 'noopener', 'noreferrer'] + } + } + if (el.tagName === 'img') { + el.properties.loading = 'lazy' + el.properties.decoding = 'async' + } + walk(el.children) + } + } + return (tree: Root) => walk(tree.children) +} + +let processor: Processor | undefined + +function getProcessor() { + if (!processor) { + processor = unified() + .use(remarkParse) + .use(remarkGfm) + .use(remarkRehype) + .use(rehypeSanitize, schema) + .use(rehypeExternalLinks) + .use(rehypeShiki, { + themes: { light: 'github-light', dark: 'vitesse-dark' }, + defaultColor: false, + lazy: true, + fallbackLanguage: 'text', + langs: ['javascript', 'typescript', 'jsx', 'tsx', 'json', 'bash', 'html', 'css'], + langAlias: { js: 'javascript', ts: 'typescript', sh: 'bash', shell: 'bash' }, + }) + .use(rehypeStringify) as any + } + return processor! +} + +/** + * Render member-written markdown to safe HTML (with syntax highlighting). + * Runs inside the markdown worker (see markdown.ts): parsing pathological + * input can be slow, and must never block the HTTP server's thread. + */ +export async function renderMarkdownInProcess(source: string): Promise { + const file = await getProcessor().process(source) + return String(file) +} diff --git a/app/services/markdown_worker.ts b/app/services/markdown_worker.ts new file mode 100644 index 0000000..9f17877 --- /dev/null +++ b/app/services/markdown_worker.ts @@ -0,0 +1,13 @@ +import { parentPort } from 'node:worker_threads' +import { renderMarkdownInProcess } from './markdown_core.js' + +/** + * Worker thread: renders markdown jobs sent by app/services/markdown.ts. + */ +parentPort!.on('message', async ({ id, source }: { id: number; source: string }) => { + try { + parentPort!.postMessage({ id, html: await renderMarkdownInProcess(source) }) + } catch (error) { + parentPort!.postMessage({ id, error: error instanceof Error ? error.message : String(error) }) + } +}) diff --git a/app/services/notifications.ts b/app/services/notifications.ts new file mode 100644 index 0000000..f5a1a09 --- /dev/null +++ b/app/services/notifications.ts @@ -0,0 +1,290 @@ +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import logger from '@adonisjs/core/services/logger' +import type { TransactionClientContract } from '@adonisjs/lucid/types/database' +import type Notification from '#models/notification' +import type { NotificationType } from '#models/notification' +import type { ReplyParent } from '#services/reply_service' + +/** + * In-app notifications. + * + * Write side: `notifyReply` (a reply was posted on a thread, a discussion or + * an article) and `notifySolution` (an answer was accepted). Both are called + * once the content is committed, and never throw: a notification failure is + * logged, it must not break posting a reply. + * + * Coalescing: one UNREAD row per recipient and subject. A new reply bumps the + * existing unread row (latest reply, latest actor, fresh created_at) instead + * of piling up rows; once the row is read, the next reply starts a new one. + * How many replies an unread row stands for is computed at read time + * (`withReplyCounts`). + */ + +type SubjectColumn = 'thread_id' | 'discussion_id' | 'article_id' + +const SUBJECTS = { + thread: { table: 'threads', column: 'thread_id', type: 'thread_reply', lock: 1 }, + discussion: { table: 'discussions', column: 'discussion_id', type: 'discussion_reply', lock: 2 }, + article: { table: 'articles', column: 'article_id', type: 'article_comment', lock: 3 }, +} as const satisfies Record< + ReplyParent['type'], + { table: string; column: SubjectColumn; type: NotificationType; lock: number } +> + +const SOLUTION_LOCK = 4 + +/** + * The community lives in Cameroon: "today" and "this week" are WAT days, + * whatever the server time zone. + */ +const COMMUNITY_ZONE = 'Africa/Douala' + +/** + * Serialize concurrent fan-outs on the same subject (two replies posted at + * the same instant must not both insert an unread row for the same person). + * Transaction-scoped: released on commit/rollback. + */ +async function lockSubject(trx: TransactionClientContract, kind: number, id: number) { + await trx.rawQuery('select pg_advisory_xact_lock(?, ?)', [0x6e0 + kind, id]) +} + +type Delivery = { + type: NotificationType + column: SubjectColumn + subjectId: number + replyId: number + actorId: number +} + +/** + * Bump the recipients' unread notification on this subject, insert one for + * everybody else (single batched insert). + */ +async function deliver(trx: TransactionClientContract, recipients: number[], delivery: Delivery) { + if (!recipients.length) return + const now = new Date() + + const bumped: { user_id: number }[] = await trx + .from('notifications') + .whereIn('user_id', recipients) + .where('type', delivery.type) + .where(delivery.column, delivery.subjectId) + .whereNull('read_at') + .update({ actor_id: delivery.actorId, reply_id: delivery.replyId, created_at: now }, [ + 'user_id', + ]) + + const done = new Set(bumped.map((row) => Number(row.user_id))) + const fresh = recipients.filter((id) => !done.has(id)) + if (!fresh.length) return + + await trx.table('notifications').multiInsert( + fresh.map((userId) => ({ + user_id: userId, + actor_id: delivery.actorId, + type: delivery.type, + [delivery.column]: delivery.subjectId, + reply_id: delivery.replyId, + created_at: now, + })) + ) +} + +/** + * A reply was posted: notify the author of the thread / discussion / article + * and everyone who replied before. Never the replier, never banned members. + */ +export async function notifyReply(parent: ReplyParent, reply: { id: number; userId: number }) { + const subject = SUBJECTS[parent.type] + try { + await db.transaction(async (trx) => { + await lockSubject(trx, subject.lock, parent.id) + + const rows: { id: number }[] = await trx + .from('users') + .select('id') + .whereNull('banned_at') + .whereNot('id', reply.userId) + .where((query) => { + query + .whereIn('id', (sub) => + sub.from(subject.table).select('user_id').where('id', parent.id) + ) + .orWhereIn('id', (sub) => + sub.from('replies').select('user_id').where(subject.column, parent.id) + ) + }) + + await deliver( + trx, + rows.map((row) => Number(row.id)), + { + type: subject.type, + column: subject.column, + subjectId: parent.id, + replyId: reply.id, + actorId: reply.userId, + } + ) + }) + } catch (error) { + logger.error( + { err: error, replyId: reply.id, parent }, + 'notifications: could not notify a new reply' + ) + } +} + +/** + * An answer was accepted as the solution of a thread: tell its author. + * Accepting, removing then accepting the same answer again notifies once. + */ +export async function notifySolution( + threadId: number, + reply: { id: number; userId: number }, + actorId: number +) { + if (reply.userId === actorId) return + try { + await db.transaction(async (trx) => { + await lockSubject(trx, SOLUTION_LOCK, threadId) + + const recipient = await trx + .from('users') + .select('id') + .where('id', reply.userId) + .whereNull('banned_at') + .first() + if (!recipient) return + + const already = await trx + .from('notifications') + .select('id') + .where('user_id', reply.userId) + .where('type', 'solution_accepted') + .where('reply_id', reply.id) + .first() + if (already) return + + await deliver(trx, [reply.userId], { + type: 'solution_accepted', + column: 'thread_id', + subjectId: threadId, + replyId: reply.id, + actorId, + }) + }) + } catch (error) { + logger.error( + { err: error, replyId: reply.id, threadId }, + 'notifications: could not notify an accepted solution' + ) + } +} + +/** + * Same subject as the notification "n" (exactly one subject column is set, + * so the comparisons on the two NULL columns are simply never true). + */ +const SAME_SUBJECT = (alias: string) => + `(${alias}.thread_id = n.thread_id or ${alias}.discussion_id = n.discussion_id or ${alias}.article_id = n.article_id)` + +/** + * For the UNREAD reply notifications of a page: how many replies each one + * stands for ($extras.new_replies) and how many people wrote them + * ($extras.actors_count). The recipient "last saw" the subject when they + * last replied to it or read a notification about it: every reply by + * someone else since then is new. One query for the whole page. + */ +export async function withReplyCounts(notifications: Notification[]) { + const unread = notifications.filter( + (notification) => notification.readAt === null && notification.type !== 'solution_accepted' + ) + if (!unread.length) return + + const result = await db.rawQuery( + `select n.id, count(r.id)::int as new_replies, count(distinct r.user_id)::int as actors_count + from notifications n + join replies r + on ${SAME_SUBJECT('r')} + and r.user_id <> n.user_id + and r.created_at <= n.created_at + and r.created_at > coalesce( + greatest( + (select max(o.created_at) from replies o + where o.user_id = n.user_id and ${SAME_SUBJECT('o')}), + (select max(p.read_at) from notifications p + where p.user_id = n.user_id and p.type = n.type and p.read_at is not null + and ${SAME_SUBJECT('p')}) + ), + '-infinity'::timestamptz + ) + where n.id in (${unread.map(() => '?').join(', ')}) + group by n.id`, + unread.map((notification) => notification.id) + ) + + const counts = new Map( + result.rows.map((row: { id: number; new_replies: number; actors_count: number }) => [ + Number(row.id), + row, + ]) + ) + for (const notification of unread) { + const row = counts.get(notification.id) + notification.$extras.new_replies = Number(row?.new_replies ?? 1) + notification.$extras.actors_count = Number(row?.actors_count ?? 1) + } +} + +export type RecencyGroup = 'today' | 'week' | 'older' + +/** + * "Aujourd’hui" (same WAT calendar day), "Cette semaine" (the 6 days + * before), "Plus ancien". + */ +export function recencyGroup(date: DateTime, now: DateTime = DateTime.now()): RecencyGroup { + const today = now.setZone(COMMUNITY_ZONE).startOf('day') + const local = date.setZone(COMMUNITY_ZONE) + if (local >= today) return 'today' + if (local >= today.minus({ days: 6 })) return 'week' + return 'older' +} + +/** + * Retention: delete READ notifications older than `days` days. Unread ones + * are kept whatever their age. Returns the number of deleted rows. + */ +export async function pruneReadNotifications(days: number) { + const cutoff = DateTime.now().minus({ days }).toJSDate() + const deleted = await db + .from('notifications') + .whereNotNull('read_at') + .where('created_at', '<', cutoff) + .delete() + return Number(deleted) +} + +/** + * Opening a thread, discussion or article reads its notifications: the + * member has seen the new replies, the bell should not keep counting them. + */ +export async function markSubjectRead( + userId: number, + subject: { threadId: number } | { discussionId: number } | { articleId: number } +) { + const [column, id] = + 'threadId' in subject + ? ['thread_id', subject.threadId] + : 'discussionId' in subject + ? ['discussion_id', subject.discussionId] + : ['article_id', subject.articleId] + + await db + .from('notifications') + .where('user_id', userId) + .where(column, id) + .whereNull('read_at') + .update({ read_at: DateTime.now().toSQL() }) +} diff --git a/app/services/reply_service.ts b/app/services/reply_service.ts new file mode 100644 index 0000000..7feec48 --- /dev/null +++ b/app/services/reply_service.ts @@ -0,0 +1,116 @@ +import { DateTime } from 'luxon' +import db from '@adonisjs/lucid/services/db' +import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model' +import Reply from '#models/reply' +import Thread from '#models/thread' +import Discussion from '#models/discussion' +import type User from '#models/user' +import { renderMarkdown } from '#services/markdown' +import { notifyReply } from '#services/notifications' + +export type ReplyParent = + | { type: 'thread'; id: number } + | { type: 'discussion'; id: number } + | { type: 'article'; id: number } + +const COLUMN = { thread: 'threadId', discussion: 'discussionId', article: 'articleId' } as const + +/** + * Create a reply, keep the parent's counters / activity timestamp in sync. + */ +export async function createReply(parent: ReplyParent, author: User, body: string) { + // Render first: never hold a transaction open while markdown renders. + const bodyHtml = await renderMarkdown(body) + const created = await db.transaction(async (trx) => { + const reply = new Reply().useTransaction(trx) + reply.userId = author.id + reply[COLUMN[parent.type]] = parent.id + reply.body = body + reply.bodyHtml = bodyHtml + await reply.save() + + if (parent.type === 'thread' || parent.type === 'discussion') { + await trx + .from(parent.type === 'thread' ? 'threads' : 'discussions') + .where('id', parent.id) + .update({ + replies_count: trx.raw('replies_count + 1'), + last_activity_at: DateTime.now().toSQL(), + }) + } + return reply + }) + + // Once committed: notify the author and previous participants (never throws). + await notifyReply(parent, created) + return created +} + +export async function updateReply(reply: Reply, body: string) { + reply.body = body + reply.bodyHtml = await renderMarkdown(body) + await reply.save() + return reply +} + +/** + * Delete a reply and decrement the parent counter. A thread's solution + * pointing at it is cleared by the FK (ON DELETE SET NULL). + */ +export async function deleteReply(reply: Reply) { + await db.transaction(async (trx) => { + // Two concurrent deletes: only the one that removed the row decrements. + const deleted = await trx.from('replies').where('id', reply.id).delete() + if (!Number(deleted)) return + const parent = reply.threadId + ? { table: 'threads', id: reply.threadId } + : reply.discussionId + ? { table: 'discussions', id: reply.discussionId } + : null + if (parent) { + await trx + .from(parent.table) + .where('id', parent.id) + .where('replies_count', '>', 0) + .decrement('replies_count', 1) + } + }) +} + +/** + * Query modifier: preload author, count likes and flag the viewer's likes. + * Usage: withReplyMeta(user)(Reply.query().where('thread_id', id)) + * or inside preload: .preload('replies', (q) => withReplyMeta(user)(q)) + */ +export function withReplyMeta(viewer?: User | null) { + return (query: ModelQueryBuilderContract) => { + query.preload('author').withCount('likes').orderBy('created_at', 'asc') + if (viewer) { + query + .select('replies.*') + .select( + db.raw( + 'exists(select 1 from likes where likes.reply_id = replies.id and likes.user_id = ?) as liked_by_me', + [viewer.id] + ) + ) + } + } +} + +/** + * The URL of the page that shows a reply (for redirects after edit/delete). + */ +export async function replyLocation(reply: Reply) { + if (reply.threadId) { + const thread = await Thread.findOrFail(reply.threadId) + return `/forum/${thread.slug}` + } + if (reply.discussionId) { + const discussion = await Discussion.findOrFail(reply.discussionId) + return `/discussions/${discussion.slug}` + } + const { default: Article } = await import('#models/article') + const article = await Article.findOrFail(reply.articleId!) + return `/articles/${article.slug}` +} diff --git a/app/services/safe_redirect.ts b/app/services/safe_redirect.ts new file mode 100644 index 0000000..08c6449 --- /dev/null +++ b/app/services/safe_redirect.ts @@ -0,0 +1,9 @@ +/** + * Only allow same-site relative paths ("/forum/x"), never "//evil.com" + * or absolute URLs, to prevent open redirects. + */ +export function safeRedirectPath(value: unknown, fallback = '/dashboard') { + if (typeof value !== 'string') return fallback + if (!value.startsWith('/') || value.startsWith('//') || value.startsWith('/\\')) return fallback + return value +} diff --git a/app/services/search.ts b/app/services/search.ts new file mode 100644 index 0000000..94222b5 --- /dev/null +++ b/app/services/search.ts @@ -0,0 +1,308 @@ +import db from '@adonisjs/lucid/services/db' +import { SEARCH_CONFIG, SEARCH_DOCUMENTS } from '#services/search_documents' + +/** + * Site-wide full-text search (PostgreSQL, French stemming). + * + * Every condition uses the exact document expressions of + * `#services/search_documents`, so the planner can answer `@@` with the + * GIN indexes "_search_idx". Only public content is searchable: + * published articles, threads and discussions, never anything written by + * a banned member. + */ + +export const SEARCH_TYPES = ['tout', 'articles', 'questions', 'discussions'] as const +export type SearchType = (typeof SEARCH_TYPES)[number] +export type SearchSection = Exclude +export const SEARCH_SECTIONS: SearchSection[] = ['articles', 'questions', 'discussions'] + +export type SearchMode = 'exact' | 'prefix' +export type SearchCounts = Record + +/** + * A text-search query ready to be bound: user syntax through + * `websearch_to_tsquery` ("phrase", -exclusion, OR) or the prefix fallback. + */ +export type TextQuery = { + mode: SearchMode + fn: 'websearch_to_tsquery' | 'to_tsquery' + value: string +} + +export type SearchHit = { + id: number + score: number + /** Escaped HTML, matches wrapped in . */ + titleHtml: string + /** Escaped plain text (markdown stripped), matches wrapped in . */ + snippetHtml: string +} + +type SectionConfig = { + table: 'articles' | 'threads' | 'discussions' + document: string + /** Extra visibility condition (drafts and scheduled articles stay private). */ + visible: string + /** Date used for the recency boost. */ + freshness: string + /** Multiplier on the score (solved questions are worth a little more). */ + boost: string +} + +const SECTIONS: Record = { + articles: { + table: 'articles', + document: SEARCH_DOCUMENTS.articles, + visible: 'published_at is not null and published_at <= now()', + freshness: 'published_at', + boost: '1', + }, + questions: { + table: 'threads', + document: SEARCH_DOCUMENTS.threads, + visible: 'true', + freshness: 'last_activity_at', + boost: 'case when solution_reply_id is not null then 1.1 else 1 end', + }, + discussions: { + table: 'discussions', + document: SEARCH_DOCUMENTS.discussions, + visible: 'true', + freshness: 'last_activity_at', + boost: '1', + }, +} + +/** + * Sentinels for ts_headline: control characters that never survive in the + * final text, so the whole headline can be HTML-escaped before they are + * turned into tags. + */ +const START = '\u0001' +const STOP = '\u0002' + +const TITLE_HEADLINE = `StartSel=${START},StopSel=${STOP},HighlightAll=true` +const SNIPPET_HEADLINE = `StartSel=${START},StopSel=${STOP},MaxFragments=2,MaxWords=28,MinWords=12,FragmentDelimiter=" … "` + +/** + * Recency boost: up to +30 % for brand-new content, halved after ~90 days, + * fading towards +0 % (hyperbolic decay: no exp() underflow on old rows). + */ +const RECENCY_SECONDS = 90 * 24 * 3600 + +function filters(section: SearchSection, query: TextQuery) { + const config = SECTIONS[section] + return `${config.document} @@ ${query.fn}('${SEARCH_CONFIG}', :query) + and ${config.visible} + and not exists ( + select 1 from users + where users.id = ${config.table}.user_id and users.banned_at is not null + )` +} + +/** + * Query typed by the user (websearch syntax). + */ +export function exactQuery(q: string): TextQuery { + return { mode: 'exact', fn: 'websearch_to_tsquery', value: q } +} + +/** + * Fallback for short or partial words ("clos" → closures): every kept + * word becomes a "word:*" prefix. Words are reduced to letters and digits, + * so the to_tsquery syntax can never be injected; excluded words (-mot) + * and the OR keyword are dropped. + */ +export function prefixQuery(q: string): TextQuery | null { + const words = q + .split(/\s+/) + .filter((token) => token && !token.startsWith('-') && token !== 'OR') + .flatMap((token) => token.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []) + .filter((word) => word.length >= 2) + + const unique = [...new Set(words)].slice(0, 6) + if (!unique.length) return null + return { mode: 'prefix', fn: 'to_tsquery', value: unique.map((w) => `${w}:*`).join(' & ') } +} + +/** + * Number of matches for one section (one aggregate query on the index). + */ +export async function countMatches(section: SearchSection, query: TextQuery) { + const { table } = SECTIONS[section] + const result = await db.rawQuery( + `select count(*) as total from ${table} where ${filters(section, query)}`, + { query: query.value } + ) + return Number(result.rows[0]?.total ?? 0) +} + +export async function countAll(query: TextQuery): Promise { + const [articles, questions, discussions] = await Promise.all( + SEARCH_SECTIONS.map((section) => countMatches(section, query)) + ) + return { articles, questions, discussions } +} + +/** + * Ranked page of matches with highlighted title and snippet. Headlines + * are only computed for the rows of the page (outer query). + */ +export async function findHits( + section: SearchSection, + query: TextQuery, + { limit, offset = 0 }: { limit: number; offset?: number } +): Promise { + const config = SECTIONS[section] + const tsquery = `${query.fn}('${SEARCH_CONFIG}', :query)` + const clean = (column: string) => `translate(${column}, :sentinels, '')` + + const result = await db.rawQuery( + `with hits as ( + select id, + ts_rank_cd(${config.document}, ${tsquery}, 32) + * ${config.boost} + * (1 + 0.3 / (1 + greatest(extract(epoch from (now() - ${config.freshness})), 0) / ${RECENCY_SECONDS})) as score + from ${config.table} + where ${filters(section, query)} + order by score desc, id desc + limit :limit offset :offset + ) + select hits.id, hits.score, doc.title, + ts_headline('${SEARCH_CONFIG}', ${clean('doc.title')}, ${tsquery}, :titleOptions) as title_headline, + ts_headline('${SEARCH_CONFIG}', ${clean('doc.body')}, ${tsquery}, :snippetOptions) as body_headline, + ${ + section === 'articles' + ? `ts_headline('${SEARCH_CONFIG}', ${clean("coalesce(doc.excerpt, '')")}, ${tsquery}, :titleOptions)` + : `''` + } as excerpt_headline + from hits + join ${config.table} as doc on doc.id = hits.id + order by hits.score desc, hits.id desc`, + { + query: query.value, + limit, + offset, + sentinels: `${START}${STOP}`, + titleOptions: TITLE_HEADLINE, + snippetOptions: SNIPPET_HEADLINE, + } + ) + + return result.rows.map( + (row: { + id: number + score: number + title: string + title_headline: string + body_headline: string + excerpt_headline: string + }) => ({ + id: Number(row.id), + score: Number(row.score), + titleHtml: titleToHtml(row.title, row.title_headline), + snippetHtml: snippetToHtml(row.body_headline, row.excerpt_headline), + }) + ) +} + +/* -------------------------------------------------------------------------- + Headline → safe HTML + -------------------------------------------------------------------------- */ + +const ESCAPES: Record = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', +} + +export function escapeHtml(text: string) { + return text.replace(/[&<>"']/g, (char) => ESCAPES[char]) +} + +// Control characters other than the sentinels (tab/newline are whitespace): +// matching them is the point here. +// eslint-disable-next-line no-control-regex +const CONTROL_CHARS = /[\u0000\u0003-\u0008\u000B\u000C\u000E-\u001F\u007F]/g + +/** + * Escape everything, then turn the (balanced) sentinels into tags. + * The only markup that can ever come out of this function is . + */ +export function markersToHtml(text: string) { + const escaped = escapeHtml(text.replace(CONTROL_CHARS, '')) + let html = '' + let open = false + for (const char of escaped) { + if (char === START) { + if (!open) html += '' + open = true + } else if (char === STOP) { + if (open) html += '' + open = false + } else { + html += char + } + } + if (open) html += '' + return html.replace(/(\s*)<\/mark>/g, '$1') +} + +const hasMatch = (headline: string) => headline.includes(START) +const withoutMarkers = (text: string) => text.replaceAll(START, '').replaceAll(STOP, '') +const squash = (text: string) => text.replace(/\s+/g, ' ').trim() + +/** + * ts_headline drops what its parser takes for HTML tags ("
"): if the + * headline no longer spells the title, show the exact title unhighlighted. + */ +export function titleToHtml(title: string, headline: string) { + const faithful = squash(withoutMarkers(headline)) === squash(title) + return markersToHtml(squash(faithful ? headline : title)) +} + +/** + * Body excerpt around the matches. When the body does not contain them + * (title-only match), an article shows its summary rather than the first + * words of the body. + */ +export function snippetToHtml(bodyHeadline: string, excerptHeadline = '') { + const useExcerpt = !hasMatch(bodyHeadline) && withoutMarkers(excerptHeadline).trim().length > 0 + return markersToHtml(stripMarkdown(useExcerpt ? excerptHeadline : bodyHeadline)) +} + +/** + * Remove the markdown syntax noise from a headline fragment (it is plain + * text: the result is escaped afterwards). Sentinels are left in place. + */ +export function stripMarkdown(text: string) { + return ( + text + // Code fences (with their language) and horizontal rules + .replace(/^[ \t]*(```|~~~)[^\n]*$/gm, ' ') + .replace(/^[ \t]*([-*_][ \t]*){3,}$/gm, ' ') + // Table separator rows + .replace(/^[ \t]*\|?([ \t]*:?-{3,}:?[ \t]*\|?)+[ \t]*$/gm, ' ') + // Headings, blockquotes, list markers and task boxes + .replace(/^[ \t]{0,3}#{1,6}[ \t]+/gm, '') + .replace(/^[ \t]{0,3}(>[ \t]?)+/gm, '') + .replace(/^[ \t]*([-*+]|\d{1,3}[.)])[ \t]+(\[[ xX]\][ \t]+)?/gm, '') + // Link definitions, images and links → their text + .replace(/^[ \t]*\[[^\]\n]+\]:[ \t]*\S+.*$/gm, ' ') + .replace(/!\[([^\]\n]*)\]\([^)\n]*\)/g, '$1') + .replace(/\[([^\]\n]+)\]\([^)\n]*\)/g, '$1') + .replace(/\[([^\]\n]+)\]\[[^\]\n]*\]/g, '$1') + // A link cut by the fragment boundary: "[texte](https://exam…" + .replace(/\]\(\S*/g, ' ') + .replace(/<(https?:\/\/[^>\s]+)>/g, '$1') + // Emphasis, strikethrough, inline code + .replace(/\*\*|__|~~/g, '') + .replace(/(^|[^\p{L}\p{N}*])\*(?=\S)([^*\n]*?\S)\*(?![\p{L}\p{N}*])/gu, '$1$2') + .replace(/(^|[^\p{L}\p{N}_])_(?=\S)([^_\n]*?\S)_(?![\p{L}\p{N}_])/gu, '$1$2') + .replace(/`+/g, '') + .replace(/\s+/g, ' ') + .trim() + ) +} diff --git a/app/services/search_documents.ts b/app/services/search_documents.ts new file mode 100644 index 0000000..4328fa8 --- /dev/null +++ b/app/services/search_documents.ts @@ -0,0 +1,18 @@ +/** + * Full-text search configuration: French stemming + accent folding + * ("evenement" finds "événement"), created by migration 1760000000830. + */ +export const SEARCH_CONFIG = 'french_unaccent' + +/** + * Full-text "documents" indexed by GIN indexes. Search queries must use + * these exact expressions for PostgreSQL to use the index. + * Title words weigh more (A) than the body (B/C). + */ +export const SEARCH_DOCUMENTS = { + articles: `(setweight(to_tsvector('${SEARCH_CONFIG}', coalesce(title, '')), 'A') || setweight(to_tsvector('${SEARCH_CONFIG}', coalesce(excerpt, '')), 'B') || setweight(to_tsvector('${SEARCH_CONFIG}', body), 'C'))`, + threads: `(setweight(to_tsvector('${SEARCH_CONFIG}', coalesce(title, '')), 'A') || setweight(to_tsvector('${SEARCH_CONFIG}', body), 'C'))`, + discussions: `(setweight(to_tsvector('${SEARCH_CONFIG}', coalesce(title, '')), 'A') || setweight(to_tsvector('${SEARCH_CONFIG}', body), 'C'))`, +} as const + +export type SearchableTable = keyof typeof SEARCH_DOCUMENTS diff --git a/app/services/slug.ts b/app/services/slug.ts new file mode 100644 index 0000000..ee81f7f --- /dev/null +++ b/app/services/slug.ts @@ -0,0 +1,20 @@ +import string from '@adonisjs/core/helpers/string' +import db from '@adonisjs/lucid/services/db' + +/** + * Generate a URL slug for "title" that is unique within "table". When + * the base slug is taken, a short random suffix is appended. + */ +export async function uniqueSlug(table: string, title: string, ignoreId?: number) { + const base = string.slug(title, { lower: true, strict: true }).slice(0, 180) || 'sujet' + + for (let attempt = 0; attempt < 5; attempt++) { + const candidate = attempt === 0 ? base : `${base}-${string.random(6).toLowerCase()}` + const query = db.from(table).where('slug', candidate) + if (ignoreId) query.whereNot('id', ignoreId) + const taken = await query.first() + if (!taken) return candidate + } + + return `${base}-${Date.now().toString(36)}` +} diff --git a/app/transformers/article_transformer.ts b/app/transformers/article_transformer.ts new file mode 100644 index 0000000..cac7ef5 --- /dev/null +++ b/app/transformers/article_transformer.ts @@ -0,0 +1,52 @@ +import type Article from '#models/article' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' +import TagTransformer from '#transformers/tag_transformer' + +export default class ArticleTransformer extends BaseTransformer
{ + /** + * Listing representation (cards, rows). + */ + toObject() { + return { + ...this.pick(this.resource, [ + 'id', + 'title', + 'slug', + 'excerpt', + 'coverUrl', + 'readingMinutes', + 'viewsCount', + 'publishedAt', + 'featuredAt', + 'createdAt', + 'updatedAt', + ]), + isPublished: this.resource.isPublished, + likesCount: Number(this.resource.$extras.likes_count ?? 0), + commentsCount: Number(this.resource.$extras.comments_count ?? 0), + author: UserTransformer.transform(this.whenLoaded(this.resource.author)), + tags: TagTransformer.transform(this.whenLoaded(this.resource.tags)), + } + } + + /** + * Article page: rendered HTML body. + */ + forDetail() { + return { + ...this.toObject(), + bodyHtml: this.resource.bodyHtml, + } + } + + /** + * Edit form: raw markdown body. + */ + forEdit() { + return { + ...this.toObject(), + body: this.resource.body, + } + } +} diff --git a/app/transformers/channel_transformer.ts b/app/transformers/channel_transformer.ts new file mode 100644 index 0000000..c3ef559 --- /dev/null +++ b/app/transformers/channel_transformer.ts @@ -0,0 +1,11 @@ +import type Channel from '#models/channel' +import { BaseTransformer } from '@adonisjs/core/transformers' + +export default class ChannelTransformer extends BaseTransformer { + toObject() { + return { + ...this.pick(this.resource, ['id', 'name', 'slug', 'description']), + threadsCount: Number(this.resource.$extras.threads_count ?? 0), + } + } +} diff --git a/app/transformers/discussion_transformer.ts b/app/transformers/discussion_transformer.ts new file mode 100644 index 0000000..64396e7 --- /dev/null +++ b/app/transformers/discussion_transformer.ts @@ -0,0 +1,56 @@ +import type Discussion from '#models/discussion' +import type User from '#models/user' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' +import TagTransformer from '#transformers/tag_transformer' +import { plainExcerpt } from '#services/markdown' + +export default class DiscussionTransformer extends BaseTransformer { + toObject() { + return { + ...this.pick(this.resource, [ + 'id', + 'title', + 'slug', + 'viewsCount', + 'repliesCount', + 'pinnedAt', + 'lockedAt', + 'lastActivityAt', + 'createdAt', + 'updatedAt', + ]), + author: UserTransformer.transform(this.whenLoaded(this.resource.author)), + tags: TagTransformer.transform(this.whenLoaded(this.resource.tags)), + } + } + + /** + * Discussions index rows: excerpt + the latest people who replied + * (attached by the controller in `$extras.participants`, batched). + */ + forList() { + const participants = (this.resource.$extras.participants ?? []) as User[] + return { + ...this.toObject(), + excerpt: plainExcerpt(this.resource.body, 200), + participants: UserTransformer.transform(participants), + participantsCount: Number(this.resource.$extras.participants_count ?? 1), + } + } + + forDetail() { + return { + ...this.toObject(), + bodyHtml: this.resource.bodyHtml, + excerpt: plainExcerpt(this.resource.body, 160), + } + } + + forEdit() { + return { + ...this.toObject(), + body: this.resource.body, + } + } +} diff --git a/app/transformers/notification_transformer.ts b/app/transformers/notification_transformer.ts new file mode 100644 index 0000000..876ffcf --- /dev/null +++ b/app/transformers/notification_transformer.ts @@ -0,0 +1,66 @@ +import type Notification from '#models/notification' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' +import { plainExcerpt } from '#services/markdown' +import { recencyGroup } from '#services/notifications' + +type SubjectKind = 'thread' | 'discussion' | 'article' + +type Subject = { + kind: SubjectKind + title: string + slug: string + /** The recipient wrote it ("votre question" vs "la question"). */ + isMine: boolean + /** The latest actor wrote it ("a répondu à sa question"). */ + byActor: boolean +} + +/** + * What the notification is about. Relations must be preloaded; a subject + * that vanished in the meantime yields null. + */ +function subjectOf(notification: Notification): Subject | null { + const content: { title: string; slug: string; userId: number } | null | undefined = + notification.threadId !== null + ? notification.thread + : notification.discussionId !== null + ? notification.discussion + : notification.article + if (!content) return null + const kind: SubjectKind = + notification.threadId !== null + ? 'thread' + : notification.discussionId !== null + ? 'discussion' + : 'article' + return { + kind, + title: content.title, + slug: content.slug, + isMine: content.userId === notification.userId, + byActor: content.userId === notification.actorId, + } +} + +export default class NotificationTransformer extends BaseTransformer { + /** + * Notification center row. Counters ($extras) come from + * `withReplyCounts()`; they are only computed for unread reply rows. + */ + toObject() { + const notification = this.resource + const reply = notification.reply + return { + ...this.pick(notification, ['id', 'type', 'replyId', 'readAt', 'createdAt']), + isRead: notification.isRead, + group: recencyGroup(notification.createdAt), + href: `/notifications/${notification.id}`, + actor: UserTransformer.transform(this.whenLoaded(notification.actor)), + subject: subjectOf(notification), + excerpt: reply ? plainExcerpt(reply.body, 140) || null : null, + newReplies: Number(notification.$extras.new_replies ?? 1), + actorsCount: Number(notification.$extras.actors_count ?? 1), + } + } +} diff --git a/app/transformers/reply_transformer.ts b/app/transformers/reply_transformer.ts new file mode 100644 index 0000000..db612a4 --- /dev/null +++ b/app/transformers/reply_transformer.ts @@ -0,0 +1,23 @@ +import type Reply from '#models/reply' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' + +export default class ReplyTransformer extends BaseTransformer { + toObject() { + return { + ...this.pick(this.resource, [ + 'id', + 'body', + 'bodyHtml', + 'threadId', + 'discussionId', + 'articleId', + 'createdAt', + 'updatedAt', + ]), + likesCount: Number(this.resource.$extras.likes_count ?? 0), + likedByMe: Boolean(this.resource.$extras.liked_by_me), + author: UserTransformer.transform(this.whenLoaded(this.resource.author)), + } + } +} diff --git a/app/transformers/report_transformer.ts b/app/transformers/report_transformer.ts new file mode 100644 index 0000000..caf207c --- /dev/null +++ b/app/transformers/report_transformer.ts @@ -0,0 +1,67 @@ +import type Report from '#models/report' +import type User from '#models/user' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' +import type { ReportTarget } from '#validators/report_validator' + +/** + * The reported content, as the moderation queue shows it. Titles and + * excerpts are plain text (never HTML). Once the content is deleted, the + * row comes from the snapshot stored on the reports (no link, no excerpt). + */ +export type ReportQueueTarget = { + type: ReportTarget + id: number + /** Title of the article / thread / discussion, or the reply's excerpt ('' once deleted). */ + title: string + /** For replies: where the reply lives (type unknown once the reply is deleted). */ + parent: { type: 'article' | 'thread' | 'discussion' | null; title: string } | null + /** Link to the content (replies point at their "#reponse-" anchor); null once deleted. */ + href: string | null + isDraft: boolean + deleted: boolean +} + +/** + * Attached by AdminReportsController to the latest report of each row + * (report.$extras.queue) before serializing the moderation queue. + */ +export type ReportQueueExtras = { + target: ReportQueueTarget + owner: User | null + /** Every report of the row (same content, same status), newest first. */ + reports: Report[] + /** Mirrors User.canManageContent; false once the content is deleted. */ + canDelete: boolean +} + +export default class ReportTransformer extends BaseTransformer { + toObject() { + return { + ...this.pick(this.resource, ['id', 'reason', 'details', 'status', 'createdAt', 'resolvedAt']), + reporter: UserTransformer.transform(this.whenLoaded(this.resource.reporter)), + resolvedBy: UserTransformer.transform(this.whenLoaded(this.resource.resolvedBy)), + } + } + + /** + * One row of the moderation queue: a piece of content and all the + * reports it received (several reports on the same content = one row). + */ + forQueue() { + const queue = this.resource.$extras.queue as ReportQueueExtras + const reasons = [...new Set(queue.reports.map((report) => report.reason))] + return { + ...this.toObject(), + key: `${queue.target.type}-${queue.target.id}`, + target: queue.target, + owner: UserTransformer.transform(queue.owner), + reasons, + reportsCount: queue.reports.length, + firstReportedAt: queue.reports[queue.reports.length - 1]?.createdAt ?? null, + canDelete: queue.canDelete, + // Depth counts from the top: row → reports → reporter. + reports: ReportTransformer.transform(queue.reports).depth(2), + } + } +} diff --git a/app/transformers/tag_transformer.ts b/app/transformers/tag_transformer.ts new file mode 100644 index 0000000..ae1713e --- /dev/null +++ b/app/transformers/tag_transformer.ts @@ -0,0 +1,12 @@ +import type Tag from '#models/tag' +import { BaseTransformer } from '@adonisjs/core/transformers' + +export default class TagTransformer extends BaseTransformer { + toObject() { + return { + ...this.pick(this.resource, ['id', 'name', 'slug', 'description']), + articlesCount: Number(this.resource.$extras.articles_count ?? 0), + discussionsCount: Number(this.resource.$extras.discussions_count ?? 0), + } + } +} diff --git a/app/transformers/thread_transformer.ts b/app/transformers/thread_transformer.ts new file mode 100644 index 0000000..5b6ec4a --- /dev/null +++ b/app/transformers/thread_transformer.ts @@ -0,0 +1,54 @@ +import type Thread from '#models/thread' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' +import ChannelTransformer from '#transformers/channel_transformer' +import { plainExcerpt } from '#services/markdown' + +export default class ThreadTransformer extends BaseTransformer { + toObject() { + return { + ...this.pick(this.resource, [ + 'id', + 'title', + 'slug', + 'viewsCount', + 'repliesCount', + 'solutionReplyId', + 'pinnedAt', + 'lockedAt', + 'lastActivityAt', + 'createdAt', + 'updatedAt', + ]), + isSolved: this.resource.isSolved, + author: UserTransformer.transform(this.whenLoaded(this.resource.author)), + channel: ChannelTransformer.transform(this.whenLoaded(this.resource.channel)), + } + } + + /** + * Forum index rows: adds a short plain-text excerpt of the question. + */ + forList() { + return { + ...this.toObject(), + excerpt: plainExcerpt(this.resource.body, 170), + } + } + + forDetail() { + return { + ...this.toObject(), + bodyHtml: this.resource.bodyHtml, + excerpt: plainExcerpt(this.resource.body, 160), + } + } + + forEdit() { + return { + ...this.toObject(), + body: this.resource.body, + channelId: this.resource.channelId, + } + } +} diff --git a/app/transformers/user_transformer.ts b/app/transformers/user_transformer.ts new file mode 100644 index 0000000..5899dfa --- /dev/null +++ b/app/transformers/user_transformer.ts @@ -0,0 +1,81 @@ +import type User from '#models/user' +import { BaseTransformer } from '@adonisjs/core/transformers' + +export default class UserTransformer extends BaseTransformer { + /** + * Public, minimal representation (author bylines, avatars). + */ + toObject() { + return { + ...this.pick(this.resource, ['id', 'username', 'name', 'avatarUrl', 'role']), + displayName: this.resource.displayName, + initials: this.resource.initials, + } + } + + /** + * Public profile page. + */ + forProfile() { + return { + ...this.toObject(), + ...this.pick(this.resource, [ + 'bio', + 'location', + 'websiteUrl', + 'githubUsername', + 'twitterUsername', + 'linkedinUsername', + 'createdAt', + ]), + } + } + + /** + * The signed-in user (shared with every page). Includes private fields. + */ + forSession() { + return { + ...this.forProfile(), + email: this.resource.email, + hasPassword: this.resource.password !== null, + isAdmin: this.resource.isAdmin, + isModerator: this.resource.isModerator, + } + } + + /** + * Members directory row. Counters come from subqueries selected as + * "articles_count", "threads_count" and "replies_count". + */ + forDirectory() { + return { + ...this.toObject(), + ...this.pick(this.resource, ['bio', 'location', 'createdAt']), + articlesCount: Number(this.resource.$extras.articles_count ?? 0), + threadsCount: Number(this.resource.$extras.threads_count ?? 0), + repliesCount: Number(this.resource.$extras.replies_count ?? 0), + } + } + + /** + * Back-office row for moderators (no private contact data). + */ + forModeration() { + return { + ...this.forDirectory(), + bannedAt: this.resource.bannedAt, + isBanned: this.resource.isBanned, + } + } + + /** + * Back-office row for administrators: adds the e-mail address. + */ + forAdmin() { + return { + ...this.forModeration(), + email: this.resource.email, + } + } +} diff --git a/app/validators/admin_validator.ts b/app/validators/admin_validator.ts new file mode 100644 index 0000000..8ff6c7c --- /dev/null +++ b/app/validators/admin_validator.ts @@ -0,0 +1,72 @@ +import vine from '@vinejs/vine' +import { withMessages } from '#validators/settings_validator' + +const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ + +const slugMessages = { + 'slug.regex': 'Lettres minuscules, chiffres et tirets uniquement (ex. : react-native).', + 'slug.database.unique': 'Ce slug est déjà utilisé.', +} + +/** + * Tag create / update. The slug is generated from the name when left blank. + */ +export const tagValidator = withMessages( + vine.withMetaData<{ id?: number }>().create({ + name: vine.string().trim().minLength(2).maxLength(40), + slug: vine + .string() + .trim() + .toLowerCase() + .maxLength(50) + .regex(SLUG) + .unique({ + table: 'tags', + column: 'slug', + filter: (db, _value, field) => { + if (field.meta.id) db.whereNot('id', field.meta.id) + }, + }) + .nullable(), + description: vine.string().trim().maxLength(255).nullable(), + }), + slugMessages +) + +/** + * Forum channel create / update. + */ +export const channelValidator = withMessages( + vine.withMetaData<{ id?: number }>().create({ + name: vine.string().trim().minLength(2).maxLength(60), + slug: vine + .string() + .trim() + .toLowerCase() + .maxLength(70) + .regex(SLUG) + .unique({ + table: 'channels', + column: 'slug', + filter: (db, _value, field) => { + if (field.meta.id) db.whereNot('id', field.meta.id) + }, + }) + .nullable(), + description: vine.string().trim().maxLength(255).nullable(), + position: vine.number().withoutDecimals().min(0).max(999), + }), + { + ...slugMessages, + 'position.withoutDecimals': 'Un nombre entier, s’il vous plaît.', + 'position.min': 'La position est un nombre entre 0 et 999.', + 'position.max': 'La position est un nombre entre 0 et 999.', + } +) + +/** + * Role change (admins only). + */ +export const roleValidator = vine.create({ + role: vine.enum(['member', 'moderator', 'admin'] as const), +}) diff --git a/app/validators/article_validator.ts b/app/validators/article_validator.ts index b263745..d099355 100644 --- a/app/validators/article_validator.ts +++ b/app/validators/article_validator.ts @@ -1,11 +1,84 @@ -import vine from '@vinejs/vine' - -export const articleValidator = vine.compile( - vine.object({ - title: vine.string().minLength(10).maxLength(255), - content: vine.string().minLength(100), - excerpt: vine.string().minLength(50).maxLength(160), - tags: vine.array(vine.string()), - isPublished: vine.boolean().optional(), - }) -) +import vine, { SimpleMessagesProvider } from '@vinejs/vine' +import type { FieldContext, MessagesProviderContact } from '@vinejs/vine/types' + +/** + * Treat blank strings as "not provided" (optional fields sent by forms). + */ +const blankToNull = (value: unknown) => + typeof value === 'string' && value.trim() === '' ? null : value + +export const ARTICLE_LIMITS = { + titleMin: 10, + titleMax: 160, + excerptMax: 300, + bodyMin: 100, + bodyMax: 100_000, + tagsMax: 4, +} as const + +/** + * Create / update an article. `publish` is the submit intent: + * true = published (first publication sets the date), false = draft. + */ +export const articleValidator = vine.create({ + title: vine.string().trim().minLength(ARTICLE_LIMITS.titleMin).maxLength(ARTICLE_LIMITS.titleMax), + excerpt: vine + .string() + .parse(blankToNull) + .trim() + .maxLength(ARTICLE_LIMITS.excerptMax) + .nullable() + .optional(), + coverUrl: vine + .string() + .parse(blankToNull) + .trim() + .url({ protocols: ['https'], require_protocol: true, require_valid_protocol: true }) + .maxLength(500) + .nullable() + .optional(), + tags: vine + .array(vine.number().withoutDecimals().positive()) + .maxLength(ARTICLE_LIMITS.tagsMax) + .optional(), + body: vine.string().trim().minLength(ARTICLE_LIMITS.bodyMin).maxLength(ARTICLE_LIMITS.bodyMax), + publish: vine.boolean(), +}) + +/** + * Field-specific French messages, falling back to the global provider + * (start/validator.ts) for everything else. + */ +const ARTICLE_MESSAGES: Record = { + 'title.required': 'Donnez un titre à votre article.', + 'title.minLength': 'Un titre explicite fait au moins {{ min }} caractères.', + 'title.maxLength': 'Le titre ne doit pas dépasser {{ max }} caractères.', + 'excerpt.maxLength': 'Le chapô ne doit pas dépasser {{ max }} caractères.', + 'coverUrl.url': 'L’image de couverture doit être une adresse https://… valide.', + 'coverUrl.maxLength': 'Cette adresse d’image est trop longue (500 caractères au plus).', + 'tags.array.maxLength': 'Choisissez au plus {{ max }} tags.', + 'tags.*.number': 'Tag inconnu.', + 'tags.*.withoutDecimals': 'Tag inconnu.', + 'tags.*.positive': 'Tag inconnu.', + 'body.required': 'L’article est vide.', + 'body.minLength': 'Développez encore un peu : au moins {{ min }} caractères.', + 'body.maxLength': 'L’article est trop long ({{ max }} caractères au plus).', +} + +const articleMessages = new SimpleMessagesProvider(ARTICLE_MESSAGES) + +class ArticleMessagesProvider implements MessagesProviderContact { + getMessage(rawMessage: string, rule: string, field: FieldContext, args?: Record) { + const hasSpecific = + `${field.getFieldPath()}.${rule}` in ARTICLE_MESSAGES || + `${field.wildCardPath}.${rule}` in ARTICLE_MESSAGES + return (hasSpecific ? articleMessages : vine.messagesProvider).getMessage( + rawMessage, + rule, + field, + args + ) + } +} + +articleValidator.messagesProvider = new ArticleMessagesProvider() diff --git a/app/validators/discussion_validator.ts b/app/validators/discussion_validator.ts new file mode 100644 index 0000000..5d4c097 --- /dev/null +++ b/app/validators/discussion_validator.ts @@ -0,0 +1,14 @@ +import vine from '@vinejs/vine' + +/** + * Create / edit a discussion. Up to three tags (ids), all existing. + */ +export const discussionValidator = vine.create({ + title: vine.string().trim().minLength(10).maxLength(160), + body: vine.string().trim().minLength(20).maxLength(40_000), + tags: vine + .array(vine.number().withoutDecimals().exists({ table: 'tags', column: 'id' })) + .maxLength(3) + .distinct() + .optional(), +}) diff --git a/app/validators/login_validator.ts b/app/validators/login_validator.ts index e942320..b6b548e 100644 --- a/app/validators/login_validator.ts +++ b/app/validators/login_validator.ts @@ -1,12 +1,10 @@ import vine from '@vinejs/vine' /** - * Validates the login action + * Login with e-mail or username. */ -export const loginValidator = vine.compile( - vine.object({ - email: vine.string().email(), - password: vine.string().minLength(6), - remember: vine.boolean().optional(), - }) -) +export const loginValidator = vine.create({ + login: vine.string().trim().minLength(2).maxLength(254), + password: vine.string().minLength(1).maxLength(128), + remember: vine.boolean().optional(), +}) diff --git a/app/validators/register_validator.ts b/app/validators/register_validator.ts index 023bfd0..6006001 100644 --- a/app/validators/register_validator.ts +++ b/app/validators/register_validator.ts @@ -1,13 +1,49 @@ import vine from '@vinejs/vine' /** - * Validates the register action + * Usernames that would collide with routes or impersonate the staff. */ -export const registerValidator = vine.compile( - vine.object({ - username: vine.string(), - name: vine.string(), - email: vine.string().email(), - password: vine.string().minLength(6), - }) -) +export const RESERVED_USERNAMES = [ + 'admin', + 'administrateur', + 'moderateur', + 'root', + 'api', + 'articles', + 'forum', + 'discussions', + 'membres', + 'login', + 'logout', + 'register', + 'settings', + 'dashboard', + 'javascript', + 'javascriptcm', + 'support', + 'staff', +] + +export const usernameRule = () => + vine + .string() + .trim() + .toLowerCase() + .minLength(3) + .maxLength(30) + .regex(/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/) + .notIn(RESERVED_USERNAMES) + +export const registerValidator = vine.create({ + name: vine.string().trim().minLength(2).maxLength(120), + username: usernameRule().unique({ table: 'users', column: 'username' }), + email: vine + .string() + .trim() + .toLowerCase() + .email() + .maxLength(254) + .unique({ table: 'users', column: 'email' }), + password: vine.string().minLength(8).maxLength(128), + passwordConfirmation: vine.string().sameAs('password'), +}) diff --git a/app/validators/reply_validator.ts b/app/validators/reply_validator.ts new file mode 100644 index 0000000..58e1828 --- /dev/null +++ b/app/validators/reply_validator.ts @@ -0,0 +1,5 @@ +import vine from '@vinejs/vine' + +export const replyValidator = vine.create({ + body: vine.string().trim().minLength(2).maxLength(20_000), +}) diff --git a/app/validators/report_validator.ts b/app/validators/report_validator.ts new file mode 100644 index 0000000..7f00c2b --- /dev/null +++ b/app/validators/report_validator.ts @@ -0,0 +1,35 @@ +import vine from '@vinejs/vine' +import { withMessages } from '#validators/settings_validator' + +/** + * What members can report (reports.target_type). + */ +export const REPORT_TARGETS = ['article', 'thread', 'discussion', 'reply'] as const +export type ReportTarget = (typeof REPORT_TARGETS)[number] + +export const REPORT_REASONS = ['spam', 'abuse', 'off_topic', 'other'] as const + +/** + * POST /signalements — details are optional, except for "other". + */ +export const reportValidator = withMessages( + vine.create({ + target: vine.enum(REPORT_TARGETS), + id: vine.number().withoutDecimals().positive(), + reason: vine.enum(REPORT_REASONS), + details: vine + .string() + .trim() + .minLength(3) + .maxLength(500) + .optional() + .requiredWhen('reason', '=', 'other'), + }), + { + 'reason.required': 'Choisissez un motif.', + 'reason.enum': 'Choisissez un motif.', + 'details.required': 'Précisez en quelques mots ce qui pose problème.', + 'details.minLength': 'Quelques mots de plus, s’il vous plaît.', + 'details.maxLength': '500 caractères au maximum.', + } +) diff --git a/app/validators/search_validator.ts b/app/validators/search_validator.ts new file mode 100644 index 0000000..383eebe --- /dev/null +++ b/app/validators/search_validator.ts @@ -0,0 +1,29 @@ +import vine, { SimpleMessagesProvider } from '@vinejs/vine' +import { SEARCH_TYPES } from '#services/search' + +/** + * GET /recherche — query string. An empty "q" never reaches the validator + * (it shows the landing state instead). + */ +export const searchValidator = vine.create({ + q: vine + .string() + .trim() + .minLength(2) + .maxLength(100) + // French keyboards and autocorrect type « » or “ ”: same as "phrase". + .transform((value) => + value + .replace(/[«»“”„]/g, '"') + .replace(/"\s*([^"]*?)\s*"/g, '"$1"') + .replace(/\s+/g, ' ') + ), + type: vine.enum(SEARCH_TYPES).optional(), + page: vine.number().withoutDecimals().min(1).max(1000).optional(), +}) + +export const searchMessages = new SimpleMessagesProvider({ + 'q.minLength': 'Saisissez au moins 2 caractères.', + 'q.maxLength': 'Votre recherche dépasse 100 caractères : raccourcissez-la.', + 'q.string': 'Recherche invalide.', +}) diff --git a/app/validators/settings_validator.ts b/app/validators/settings_validator.ts new file mode 100644 index 0000000..6e4ef53 --- /dev/null +++ b/app/validators/settings_validator.ts @@ -0,0 +1,151 @@ +import vine from '@vinejs/vine' +import type { FieldContext, MessagesProviderContact } from '@vinejs/vine/types' +import { usernameRule } from '#validators/register_validator' + +/** + * Field-specific French messages ("githubUsername.regex") layered on top of + * the global messages provider (start/validator.ts). + */ +export function withMessages( + validator: V, + overrides: Record +): V { + const fallback = validator.messagesProvider + validator.messagesProvider = { + getMessage( + defaultMessage: string, + rule: string, + field: FieldContext, + args?: Record + ) { + return ( + overrides[`${field.wildCardPath}.${rule}`] ?? + fallback.getMessage(defaultMessage, rule, field, args) + ) + }, + } + return validator +} + +type SocialNetwork = 'github' | 'twitter' | 'linkedin' + +/** + * Hosts (and path prefixes) members tend to paste instead of a plain handle. + */ +const PROFILE_URL_PREFIXES: Record = { + github: /^(?:[a-z0-9-]+\.)?github\.com\//i, + twitter: /^(?:(?:mobile|www)\.)?(?:twitter|x)\.com\//i, + linkedin: /^(?:[a-z]{2,3}\.)?linkedin\.com\/(?:in|pub)\//i, +} + +/** + * Turn "@foo", "https://github.com/foo/", "x.com/foo?s=21" into "foo". + * Returns null for blank values. + */ +export function normalizeHandle(value: unknown, network: SocialNetwork): string | null { + if (typeof value !== 'string') return null + let handle = value.trim() + if (!handle) return null + handle = handle.replace(/^https?:\/\//i, '').replace(/^www\./i, '') + handle = handle.replace(PROFILE_URL_PREFIXES[network], '') + handle = handle.replace(/^@+/, '') + handle = handle.split(/[/?#\s]/)[0] ?? '' + try { + handle = decodeURIComponent(handle) + } catch { + // keep the raw value, the format rule will reject it + } + return handle || null +} + +const httpsUrl = (maxLength: number) => + vine + .string() + .trim() + .maxLength(maxLength) + .url({ protocols: ['https'], require_protocol: true, require_valid_protocol: true }) + +/** + * Public profile settings. Social handles are normalized by the controller + * (see normalizeHandle) before validation. Empty inputs arrive as null + * (bodyparser "convertEmptyStringsToNull"). + */ +export const profileSettingsValidator = withMessages( + vine.withMetaData<{ userId: number }>().create({ + name: vine.string().trim().minLength(2).maxLength(120), + username: usernameRule().unique({ + table: 'users', + column: 'username', + caseInsensitive: true, + filter: (db, _value, field) => { + db.whereNot('id', field.meta.userId) + }, + }), + email: vine + .string() + .trim() + .toLowerCase() + .email() + .maxLength(254) + .unique({ + table: 'users', + column: 'email', + caseInsensitive: true, + filter: (db, _value, field) => { + db.whereNot('id', field.meta.userId) + }, + }), + bio: vine.string().trim().maxLength(280).nullable(), + location: vine.string().trim().maxLength(100).nullable(), + websiteUrl: httpsUrl(255).nullable(), + avatarUrl: httpsUrl(500).nullable(), + githubUsername: vine + .string() + .regex(/^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/i) + .nullable(), + twitterUsername: vine + .string() + .regex(/^\w{1,15}$/) + .nullable(), + linkedinUsername: vine + .string() + .maxLength(100) + .regex(/^[\p{L}\p{N}_-]{3,100}$/u) + .nullable(), + }), + { + 'username.regex': 'Lettres minuscules, chiffres, - et _ uniquement (sans espace).', + 'username.notIn': 'Ce nom d’utilisateur est réservé.', + 'username.database.unique': 'Ce nom d’utilisateur est déjà pris.', + 'email.database.unique': 'Cette adresse e-mail est déjà utilisée par un autre compte.', + 'githubUsername.regex': 'Nom d’utilisateur GitHub invalide.', + 'twitterUsername.regex': 'Identifiant X invalide (15 caractères max : lettres, chiffres, _).', + 'linkedinUsername.regex': 'Identifiant LinkedIn invalide (la partie après linkedin.com/in/).', + 'linkedinUsername.maxLength': 'Identifiant LinkedIn trop long.', + 'avatarUrl.url': 'Adresse d’image invalide (elle doit commencer par https://).', + } +) + +/** + * Password change. "currentPassword" is checked by the controller when the + * member already has a password (GitHub-only accounts can set a first one). + */ +export const passwordSettingsValidator = withMessages( + vine.create({ + currentPassword: vine.string().maxLength(128).optional(), + password: vine.string().minLength(8).maxLength(128), + passwordConfirmation: vine.string().sameAs('password'), + }), + { + 'password.minLength': 'Le mot de passe doit contenir au moins 8 caractères.', + 'passwordConfirmation.sameAs': 'Les deux mots de passe ne correspondent pas.', + 'passwordConfirmation.required': 'Confirmez le nouveau mot de passe.', + } +) + +/** + * Account deletion: the member types their username to confirm. + */ +export const deleteAccountValidator = vine.create({ + confirmation: vine.string().trim(), +}) diff --git a/app/validators/thread_validator.ts b/app/validators/thread_validator.ts new file mode 100644 index 0000000..44b7172 --- /dev/null +++ b/app/validators/thread_validator.ts @@ -0,0 +1,17 @@ +import vine from '@vinejs/vine' + +/** + * Create / edit a forum question. + */ +export const threadValidator = vine.create({ + title: vine.string().trim().minLength(15).maxLength(160), + channelId: vine.number().withoutDecimals().exists({ table: 'channels', column: 'id' }), + body: vine.string().trim().minLength(30).maxLength(40_000), +}) + +/** + * Accept a reply as the solution of a thread. + */ +export const solutionValidator = vine.create({ + replyId: vine.number().withoutDecimals().positive(), +}) diff --git a/bin/console.ts b/bin/console.ts index 4b102ee..23f042f 100644 --- a/bin/console.ts +++ b/bin/console.ts @@ -11,8 +11,8 @@ | */ -import 'reflect-metadata' -import { Ignitor, prettyPrintError } from '@adonisjs/core' +await import('reflect-metadata') +const { Ignitor, prettyPrintError } = await import('@adonisjs/core/ignitor') /** * URL to the application root. AdonisJS need it to resolve diff --git a/bin/server.ts b/bin/server.ts index fe0fefb..0556b1d 100644 --- a/bin/server.ts +++ b/bin/server.ts @@ -9,8 +9,8 @@ | */ -import 'reflect-metadata' -import { Ignitor, prettyPrintError } from '@adonisjs/core' +await import('reflect-metadata') +const { Ignitor, prettyPrintError } = await import('@adonisjs/core/ignitor') /** * URL to the application root. AdonisJS need it to resolve diff --git a/bin/test.ts b/bin/test.ts index d759efe..3b82dd6 100644 --- a/bin/test.ts +++ b/bin/test.ts @@ -13,7 +13,7 @@ process.env.NODE_ENV = 'test' import 'reflect-metadata' -import { Ignitor, prettyPrintError } from '@adonisjs/core' +import { Ignitor, prettyPrintError } from '@adonisjs/core/ignitor' import { configure, processCLIArgs, run } from '@japa/runner' /** diff --git a/commands/promote_user.ts b/commands/promote_user.ts new file mode 100644 index 0000000..d1259a9 --- /dev/null +++ b/commands/promote_user.ts @@ -0,0 +1,45 @@ +import { BaseCommand, args, flags } from '@adonisjs/core/ace' +import type { CommandOptions } from '@adonisjs/core/types/ace' + +/** + * Give a member the "admin" or "moderator" role: + * node ace user:promote brightky --role=admin + */ +export default class PromoteUser extends BaseCommand { + static commandName = 'user:promote' + static description = 'Change the role of a member (admin, moderator or member)' + + static options: CommandOptions = { + startApp: true, + } + + @args.string({ description: 'Username or e-mail of the member' }) + declare user: string + + @flags.string({ description: 'Role to assign', default: 'admin' }) + declare role: string + + async run() { + const { default: User } = await import('#models/user') + if (!['admin', 'moderator', 'member'].includes(this.role)) { + this.logger.error('Role must be one of: admin, moderator, member') + this.exitCode = 1 + return + } + + const user = await User.query() + .where('username', this.user.toLowerCase()) + .orWhere('email', this.user.toLowerCase()) + .first() + + if (!user) { + this.logger.error(`No member found for "${this.user}"`) + this.exitCode = 1 + return + } + + user.role = this.role as 'admin' | 'moderator' | 'member' + await user.save() + this.logger.success(`@${user.username} is now ${this.role}`) + } +} diff --git a/commands/prune_notifications.ts b/commands/prune_notifications.ts new file mode 100644 index 0000000..73d6c62 --- /dev/null +++ b/commands/prune_notifications.ts @@ -0,0 +1,34 @@ +import { BaseCommand, flags } from '@adonisjs/core/ace' +import type { CommandOptions } from '@adonisjs/core/types/ace' + +/** + * Retention of in-app notifications: delete the READ ones older than N days + * (unread notifications are always kept). Meant for a daily cron: + * node ace notifications:prune --days=90 + */ +export default class PruneNotifications extends BaseCommand { + static commandName = 'notifications:prune' + static description = 'Delete read notifications older than N days (default 90)' + + static options: CommandOptions = { + startApp: true, + } + + @flags.number({ description: 'Age (in days) beyond which read notifications are deleted' }) + declare days?: number + + async run() { + const days = this.days ?? 90 + if (!Number.isInteger(days) || days < 1) { + this.logger.error('--days must be a positive whole number') + this.exitCode = 1 + return + } + + const { pruneReadNotifications } = await import('#services/notifications') + const deleted = await pruneReadNotifications(days) + this.logger.success( + `${deleted} read notification${deleted === 1 ? '' : 's'} older than ${days} days deleted` + ) + } +} diff --git a/config/ally.ts b/config/ally.ts index 15bdca9..0f5fcf0 100644 --- a/config/ally.ts +++ b/config/ally.ts @@ -1,12 +1,23 @@ import env from '#start/env' -import { defineConfig, services } from '@adonisjs/ally' -const allyConfig = defineConfig({ - github: services.github({ +/** + * Social authentication providers. GitHub OAuth is implemented by + * "app/services/github_oauth.ts" (no third-party dependency). + * + * The provider is considered disabled when its credentials are missing, + * which hides the "Continuer avec GitHub" button in the UI. + */ +const socialConfig = { + github: { clientId: env.get('GITHUB_CLIENT_ID'), clientSecret: env.get('GITHUB_CLIENT_SECRET'), - callbackUrl: env.get('GITHUB_CALLBACK_URL'), - }), -}) + callbackPath: '/auth/github/callback', + scopes: ['read:user', 'user:email'], + }, +} -export default allyConfig +export function githubEnabled() { + return Boolean(socialConfig.github.clientId && socialConfig.github.clientSecret) +} + +export default socialConfig diff --git a/config/app.ts b/config/app.ts index 1292af7..000bd37 100644 --- a/config/app.ts +++ b/config/app.ts @@ -1,22 +1,30 @@ import env from '#start/env' import app from '@adonisjs/core/services/app' -import { Secret } from '@adonisjs/core/helpers' +import proxyAddr from 'proxy-addr' import { defineConfig } from '@adonisjs/core/http' /** - * The app key is used for encrypting cookies, generating signed URLs, - * and by the "encryption" module. - * - * The encryption module will fail to decrypt data if the key is lost or - * changed. Therefore it is recommended to keep the app key secure. + * The app URL can be used in various places where you want to create absolute + * URLs to your application. For example, when sending emails, images should + * use absolute URLs. */ -export const appKey = new Secret(env.get('APP_KEY')) +export const appUrl = env.get('APP_URL') /** * The configuration settings used by the HTTP server */ export const http = defineConfig({ + /** + * Generate a unique request id for each incoming request. + * Useful to correlate logs and debug a request flow. + */ generateRequestId: true, + + /** + * Allow HTTP method spoofing via the "_method" form/query parameter. + * This lets HTML forms target PUT/PATCH/DELETE routes while still + * submitting with POST. + */ allowMethodSpoofing: false, /** @@ -25,16 +33,64 @@ export const http = defineConfig({ */ useAsyncLocalStorage: false, + /** + * The app only listens behind Caddy (host) and Docker's port proxy, so + * loopback and private-network hops are trusted. request.ip() then + * returns the real client IP (needed by the rate limiter). + */ + trustProxy: proxyAddr.compile(['loopback', 'uniquelocal']), + + router: { + matcher: 'tree', + }, + + /** + * Redirect configuration controls the behavior of + * response.redirect().back() and query string forwarding. + */ + redirect: { + /** + * When enabled, all redirects automatically carry over the current + * request's query string parameters to the redirect destination. + * Use withQs(false) to opt out for a specific redirect. + */ + forwardQueryString: true, + }, + /** * Manage cookies configuration. The settings for the session id cookie are * defined inside the "config/session.ts" file. */ cookie: { + /** + * Restrict the cookie to a specific domain. + * Keep empty to use the current host. + */ domain: '', + + /** + * Restrict the cookie to a URL path. '/' means all routes. + */ path: '/', + + /** + * Default lifetime for cookies managed by the HTTP layer. + */ maxAge: '2h', + + /** + * Prevent JavaScript access to the cookie in the browser. + */ httpOnly: true, + + /** + * Send cookies only over HTTPS in production. + */ secure: app.inProduction, + + /** + * Cross-site policy for cookie sending. + */ sameSite: 'lax', }, }) diff --git a/config/auth.ts b/config/auth.ts index d3e0b6d..1f36597 100644 --- a/config/auth.ts +++ b/config/auth.ts @@ -3,11 +3,22 @@ import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session' import type { InferAuthenticators, InferAuthEvents, Authenticators } from '@adonisjs/auth/types' const authConfig = defineConfig({ + /** + * Default guard used when no guard is explicitly specified. + */ default: 'web', + guards: { + /** + * Session-based guard for browser authentication. + */ web: sessionGuard({ + /** + * Enable persistent login using remember-me tokens. + */ useRememberMeTokens: true, - rememberMeTokensAge: '1 year', + rememberMeTokensAge: '30 days', + provider: sessionUserProvider({ model: () => import('#models/user'), }), diff --git a/config/bodyparser.ts b/config/bodyparser.ts index f3d1ead..652c34d 100644 --- a/config/bodyparser.ts +++ b/config/bodyparser.ts @@ -2,25 +2,39 @@ import { defineConfig } from '@adonisjs/core/bodyparser' const bodyParserConfig = defineConfig({ /** - * The bodyparser middleware will parse the request body - * for the following HTTP methods. + * Parse request bodies for these HTTP methods. + * Keep this aligned with methods that receive payloads in your routes. */ allowedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'], /** * Config for the "application/x-www-form-urlencoded" - * content-type parser + * content-type parser. */ form: { + /** + * Normalize empty string values to null. + */ convertEmptyStringsToNull: true, + + /** + * Content types handled by the form parser. + */ types: ['application/x-www-form-urlencoded'], }, /** - * Config for the JSON parser + * Config for the JSON parser. */ json: { + /** + * Normalize empty string values to null. + */ convertEmptyStringsToNull: true, + + /** + * Content types handled by the JSON parser. + */ types: [ 'application/json', 'application/json-patch+json', @@ -35,19 +49,29 @@ const bodyParserConfig = defineConfig({ */ multipart: { /** - * Enabling auto process allows bodyparser middleware to - * move all uploaded files inside the tmp folder of your - * operating system + * The site has no file upload: never write multipart bodies to disk + * (they would be stored before CSRF validation and never cleaned up). + */ + autoProcess: false, + + /** + * Normalize empty string values to null. */ - autoProcess: true, convertEmptyStringsToNull: true, + + /** + * Routes where multipart processing is handled manually. + */ processManually: [], /** - * Maximum limit of data to parse including all files - * and fields + * Maximum accepted payload size for multipart requests. */ limit: '20mb', + + /** + * Content types handled by the multipart parser. + */ types: ['multipart/form-data'], }, }) diff --git a/config/cors.ts b/config/cors.ts index dd79007..c47fc66 100644 --- a/config/cors.ts +++ b/config/cors.ts @@ -1,3 +1,4 @@ +import app from '@adonisjs/core/services/app' import { defineConfig } from '@adonisjs/cors' /** @@ -7,12 +8,42 @@ import { defineConfig } from '@adonisjs/cors' * https://docs.adonisjs.com/guides/security/cors */ const corsConfig = defineConfig({ + /** + * Enable or disable CORS handling globally. + */ enabled: true, - origin: [], + + /** + * In development, allow every origin to simplify local front/backend setup. + * In production, keep an explicit allowlist (empty by default, so no + * cross-origin browser access is allowed until configured). + */ + origin: app.inDev ? true : [], + + /** + * HTTP methods accepted for cross-origin requests. + */ methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'], + + /** + * Reflect request headers by default. Use a string array to restrict + * allowed headers. + */ headers: true, + + /** + * Response headers exposed to the browser. + */ exposeHeaders: [], + + /** + * Allow cookies/authorization headers on cross-origin requests. + */ credentials: true, + + /** + * Cache CORS preflight response for N seconds. + */ maxAge: 90, }) diff --git a/config/database.ts b/config/database.ts index bdf0a21..1279193 100644 --- a/config/database.ts +++ b/config/database.ts @@ -1,11 +1,16 @@ import env from '#start/env' +import app from '@adonisjs/core/services/app' import { defineConfig } from '@adonisjs/lucid' const dbConfig = defineConfig({ - connection: 'mysql', + /** + * Default connection used for all queries. + */ + connection: 'pg', + connections: { - mysql: { - client: 'mysql2', + pg: { + client: 'pg', connection: { host: env.get('DB_HOST'), port: env.get('DB_PORT'), @@ -17,8 +22,13 @@ const dbConfig = defineConfig({ naturalSort: true, paths: ['database/migrations'], }, + schemaGeneration: { + enabled: true, + rulesPaths: ['./database/schema_rules.js'], + }, + debug: app.inDev && env.get('DB_DEBUG', false), }, }, }) -export default dbConfig \ No newline at end of file +export default dbConfig diff --git a/config/encryption.ts b/config/encryption.ts new file mode 100644 index 0000000..1bb3dc5 --- /dev/null +++ b/config/encryption.ts @@ -0,0 +1,34 @@ +import env from '#start/env' +import { defineConfig, drivers } from '@adonisjs/core/encryption' + +const encryptionConfig = defineConfig({ + /** + * Default encryption driver used by the application. + */ + default: 'gcm', + + list: { + gcm: drivers.aes256gcm({ + /** + * Keys used for encryption/decryption. + * First key encrypts, all keys are tried for decryption. + */ + keys: [env.get('APP_KEY')], + + /** + * Stable identifier for this driver. + */ + id: 'gcm', + }), + }, +}) + +export default encryptionConfig + +/** + * Inferring types for the list of encryptors you have configured + * in your application. + */ +declare module '@adonisjs/core/types' { + export interface EncryptorsList extends InferEncryptors {} +} diff --git a/config/hash.ts b/config/hash.ts index ab10300..a54c086 100644 --- a/config/hash.ts +++ b/config/hash.ts @@ -1,13 +1,64 @@ import { defineConfig, drivers } from '@adonisjs/core/hash' +/** + * Hashing configuration. + * + * This starter uses Node.js scrypt under the hood. + * Node.js reference: https://nodejs.org/api/crypto.html#cryptoscryptpassword-salt-keylen-options-callback + */ const hashConfig = defineConfig({ + /** + * Default hasher used by the application. + */ default: 'scrypt', list: { + /** + * Scrypt is memory-hard, which makes brute-force attacks more expensive. + */ scrypt: drivers.scrypt({ + /** + * Work factor (Node alias: N / cost). + * Higher values increase security and CPU+memory usage. + * + * Tuning guideline: + * - Start with 16384. + * - Increase gradually (for example 32768) and benchmark login/signup latency. + * - Keep values practical for your slowest production machine. + * + * Node constraint: value must be a power of two greater than 1. + */ cost: 16384, + + /** + * Block size (Node alias: r / blockSize). + * Increases memory and CPU linearly. + * + * Tuning guideline: + * - Keep 8 unless you have a measured reason to change it. + * - Raise only with benchmark data, because memory usage grows quickly. + */ blockSize: 8, + + /** + * Parallelization (Node alias: p / parallelization). + * Controls how many independent computations are performed. + * + * Tuning guideline: + * - Keep 1 for most applications. + * - Increase only after load testing if your infrastructure benefits from it. + */ parallelization: 1, + + /** + * Maximum memory limit in bytes (Node alias: maxmem / maxMemory). + * Hashing throws if the estimated memory usage is above this limit. + * Node documents the check as approximately: 128 * N * r > maxmem. + * + * Tuning guideline: + * - Keep this aligned with your cost/blockSize choices. + * - Increase carefully on memory-constrained environments. + */ maxMemory: 33554432, }), }, diff --git a/config/inertia.ts b/config/inertia.ts index c1c0680..be6578b 100644 --- a/config/inertia.ts +++ b/config/inertia.ts @@ -1,36 +1,20 @@ import { defineConfig } from '@adonisjs/inertia' -import type { InferSharedProps, PageProps } from '@adonisjs/inertia/types' const inertiaConfig = defineConfig({ /** - * Path to the Edge view that will be used as the root view for Inertia responses - */ - rootView: 'inertia_layout', - - /** - * Data that should be shared with all rendered pages - */ - sharedData: { - appName: 'JavaScript Cameroun', - auth: (ctx) => { - return { - user: ctx.auth.user, - } - }, - errors: (ctx) => ctx.inertia.always(() => ctx.session?.flashMessages.get('errors')), - }, - - /** - * Options for the server-side rendering + * Server-side rendering options. */ ssr: { + /** + * Toggle SSR mode for Inertia pages. + */ enabled: true, + + /** + * Entry file used by the SSR server build. + */ entrypoint: 'inertia/app/ssr.tsx', }, }) export default inertiaConfig - -declare module '@adonisjs/inertia/types' { - export interface SharedProps extends InferSharedProps, PageProps {} -} diff --git a/config/limiter.ts b/config/limiter.ts new file mode 100644 index 0000000..13d13ce --- /dev/null +++ b/config/limiter.ts @@ -0,0 +1,26 @@ +import env from '#start/env' +import { defineConfig, stores } from '@adonisjs/limiter' + +const limiterConfig = defineConfig({ + default: env.get('LIMITER_STORE'), + stores: { + /** + * Database store to save rate limiting data inside + * the PostgreSQL database. + */ + database: stores.database({ + tableName: 'rate_limits', + }), + + /** + * Memory store used during testing + */ + memory: stores.memory({}), + }, +}) + +export default limiterConfig + +declare module '@adonisjs/limiter/types' { + export interface LimitersList extends InferLimiters {} +} diff --git a/config/logger.ts b/config/logger.ts index b961300..ba8c96a 100644 --- a/config/logger.ts +++ b/config/logger.ts @@ -1,24 +1,40 @@ import env from '#start/env' import app from '@adonisjs/core/services/app' -import { defineConfig, targets } from '@adonisjs/core/logger' +import { defineConfig, syncDestination, targets } from '@adonisjs/core/logger' const loggerConfig = defineConfig({ - default: 'app', - /** - * The loggers object can be used to define multiple loggers. - * By default, we configure only one logger (named "app"). + * Default logger name used by ctx.logger and app logger calls. */ + default: 'app', + loggers: { app: { + /** + * Toggle this logger on/off. + */ enabled: true, + + /** + * Logger name shown in log records. + */ name: env.get('APP_NAME'), + + /** + * Minimum level to output (trace, debug, info, warn, error, fatal). + */ level: env.get('LOG_LEVEL'), + + /** + * Use sync destination in non-production for immediate flush. + */ + destination: !app.inProduction ? await syncDestination() : undefined, + + /** + * Configure where logs are written. + */ transport: { - targets: targets() - .pushIf(!app.inProduction, targets.pretty()) - .pushIf(app.inProduction, targets.file({ destination: 1 })) - .toArray(), + targets: [targets.file({ destination: 1 })], }, }, }, diff --git a/config/session.ts b/config/session.ts index 6a143aa..6bcad62 100644 --- a/config/session.ts +++ b/config/session.ts @@ -3,8 +3,15 @@ import app from '@adonisjs/core/services/app' import { defineConfig, stores } from '@adonisjs/session' const sessionConfig = defineConfig({ + /** + * Enable or disable session support globally. + */ enabled: true, - cookieName: 'adonis-session', + + /** + * Cookie name storing the session identifier. + */ + cookieName: 'jscm_session', /** * When set to true, the session id cookie will be deleted @@ -20,12 +27,27 @@ const sessionConfig = defineConfig({ /** * Configuration for session cookie and the - * cookie store + * cookie store. */ cookie: { + /** + * Restrict the cookie to a URL path. '/' means all routes. + */ path: '/', + + /** + * Prevent JavaScript access to the cookie in the browser. + */ httpOnly: true, + + /** + * Send cookies only over HTTPS in production. + */ secure: app.inProduction, + + /** + * Cross-site policy for cookie sending. + */ sameSite: 'lax', }, @@ -41,7 +63,15 @@ const sessionConfig = defineConfig({ * list of available stores and their config. */ stores: { + /** + * Store session data inside encrypted cookies. + */ cookie: stores.cookie(), + + /** + * Store session data inside the configured database. + */ + database: stores.database(), }, }) diff --git a/config/shield.ts b/config/shield.ts index d3aa290..b1d580b 100644 --- a/config/shield.ts +++ b/config/shield.ts @@ -1,49 +1,99 @@ +import app from '@adonisjs/core/services/app' import { defineConfig } from '@adonisjs/shield' const shieldConfig = defineConfig({ /** * Configure CSP policies for your app. Refer documentation - * to learn more + * to learn more. */ csp: { - enabled: false, - directives: {}, + /** + * Enabled in production only: Vite's dev server relies on inline scripts. + */ + enabled: app.inProduction, + directives: { + defaultSrc: [`'self'`], + scriptSrc: [`'self'`, '@nonce'], + // Shiki (code highlighting) and a few components use inline styles. + styleSrc: [`'self'`, `'unsafe-inline'`], + // Avatars and article covers may be hosted anywhere over HTTPS. + imgSrc: [`'self'`, 'data:', 'https:'], + fontSrc: [`'self'`, 'data:'], + connectSrc: [`'self'`], + objectSrc: [`'none'`], + baseUri: [`'self'`], + formAction: [`'self'`], + frameAncestors: [`'none'`], + }, reportOnly: false, }, /** * Configure CSRF protection options. Refer documentation - * to learn more + * to learn more. */ csrf: { + /** + * Enable CSRF token verification for state-changing requests. + */ enabled: true, + + /** + * Route patterns to exclude from CSRF checks. + * Useful for external webhooks or API endpoints. + */ exceptRoutes: [], + + /** + * Expose an encrypted XSRF-TOKEN cookie for frontend HTTP clients. + */ enableXsrfCookie: true, + + /** + * HTTP methods protected by CSRF validation. + */ methods: ['POST', 'PUT', 'PATCH', 'DELETE'], }, /** * Control how your website should be embedded inside - * iFrames + * iframes. */ xFrame: { + /** + * Enable the X-Frame-Options header. + */ enabled: true, + + /** + * Block all framing attempts. Default value is DENY. + */ action: 'DENY', }, /** - * Force browser to always use HTTPS + * Force browser to always use HTTPS. */ hsts: { + /** + * Enable the Strict-Transport-Security header. + */ enabled: true, + + /** + * HSTS policy duration remembered by browsers. + */ maxAge: '180 days', }, /** - * Disable browsers from sniffing the content type of a - * response and always rely on the "content-type" header. + * Disable browsers from sniffing content types and rely only + * on the response content-type header. */ contentTypeSniffing: { + /** + * Enable X-Content-Type-Options: nosniff. + */ enabled: true, }, }) diff --git a/config/static.ts b/config/static.ts index 2e20fc0..ad1e27d 100644 --- a/config/static.ts +++ b/config/static.ts @@ -5,12 +5,27 @@ import { defineConfig } from '@adonisjs/static' * The complete set of options are documented on the * official documentation website. * - * https://docs.adonisjs.com/guides/static-assets + * https://docs.adonisjs.com/guides/basics/static-file-server */ const staticServerConfig = defineConfig({ + /** + * Enable or disable static file serving middleware. + */ enabled: true, + + /** + * Generate ETag headers for client/proxy caching. + */ etag: true, + + /** + * Include Last-Modified headers for conditional requests. + */ lastModified: true, + + /** + * Policy for files starting with a dot. + */ dotFiles: 'ignore', }) diff --git a/config/vite.ts b/config/vite.ts index e7d65bf..1e0f4db 100644 --- a/config/vite.ts +++ b/config/vite.ts @@ -20,7 +20,13 @@ const viteBackendConfig = defineConfig({ */ assetsUrl: '/assets', + /** + * HTML attributes added to generated script tags. + */ scriptAttributes: { + /** + * Execute scripts after HTML parsing is complete. + */ defer: true, }, }) diff --git a/database/demo/articles_1.ts b/database/demo/articles_1.ts new file mode 100644 index 0000000..dbb9025 --- /dev/null +++ b/database/demo/articles_1.ts @@ -0,0 +1,1026 @@ +import { text, type DemoArticle } from './types.js' + +export const articlesPart1: DemoArticle[] = [ + /* + |-------------------------------------------------------------------------- + | Closures & tontine + |-------------------------------------------------------------------------- + */ + { + author: 'christelle_k', + title: 'Les closures expliquées avec une tontine', + excerpt: + 'Une closure, c’est une fonction qui se souvient de l’endroit où elle est née. Pour le comprendre une bonne fois pour toutes, construisons ensemble la caisse d’une tontine en JavaScript.', + tags: ['javascript', 'apprendre'], + publishedDaysAgo: 86, + views: 1840, + body: text` +Dans beaucoup de familles camerounaises, la tontine (le *njangi* pour nos amis du Nord-Ouest et du Sud-Ouest) repose sur une règle simple : chacun cotise, une personne de confiance tient la caisse, et **personne ne peut y toucher directement**. On passe par la trésorière, qui vérifie, note et redistribue. + +C’est exactement le service que rendent les closures en JavaScript. Si le mot vous fait peur, cet article est pour vous. + +## Le problème : une caisse que tout le monde peut modifier + +Commençons naïvement, avec un simple objet : + +~~~js +const tontine = { caisse: 0, membres: ['Ngo', 'Kamdem', 'Ebai'] } + +tontine.caisse += 10000 // une cotisation +tontine.caisse = 0 // ... ou un « accident » +~~~ + +Rien n’empêche n’importe quelle partie du code de vider la caisse. Il nous faut un état **privé**, accessible uniquement à travers quelques opérations autorisées. + +## Une fonction qui se souvient + +Quand une fonction est créée, elle garde un lien vers l’*environnement lexical* dans lequel elle a été déclarée, c’est-à-dire les variables visibles à cet endroit du code. Tant que la fonction existe, ces variables restent accessibles, même lorsque la fonction qui les a déclarées a terminé son exécution. Cette association « fonction + environnement » s’appelle une **closure** (fermeture, en français). + +~~~js +function creerCompteur() { + let total = 0 + + return function () { + total += 1 + return total + } +} + +const compter = creerCompteur() +compter() // 1 +compter() // 2 +~~~ + +\`creerCompteur\` a fini de s’exécuter après la première ligne, et pourtant \`total\` existe toujours : la fonction retournée l’a « capturé ». Mieux : chaque appel de \`creerCompteur\` crée un **nouvel** environnement. + +~~~js +const a = creerCompteur() +const b = creerCompteur() + +a() +a() +b() // 1 : b a sa propre variable total +~~~ + +## Construisons la tontine + +Appliquons l’idée à notre caisse. Les variables \`caisse\`, \`tour\` et \`cotisations\` vivent dans la fonction \`creerTontine\` ; seules les fonctions qu’elle retourne peuvent les lire ou les modifier. + +~~~js +function creerTontine(membres, montant) { + const liste = [...membres] // copie : l’appelant ne pourra plus modifier la liste + const cotisations = new Map() + let caisse = 0 + let tour = 0 + + function cotiser(membre) { + if (!liste.includes(membre)) { + throw new Error(\`\${membre} ne fait pas partie de la tontine\`) + } + if (cotisations.has(membre)) { + throw new Error(\`\${membre} a déjà cotisé pour ce tour\`) + } + cotisations.set(membre, montant) + caisse += montant + } + + function remettre() { + if (cotisations.size < liste.length) { + throw new Error('Tout le monde n’a pas encore cotisé') + } + const beneficiaire = liste[tour % liste.length] + const somme = caisse + caisse = 0 + cotisations.clear() + tour += 1 + return { beneficiaire, somme } + } + + return { + cotiser, + remettre, + solde: () => caisse, + } +} +~~~ + +À l’usage : + +~~~js +const njangi = creerTontine(['Ngo', 'Kamdem', 'Ebai'], 10000) + +njangi.cotiser('Ngo') +njangi.cotiser('Kamdem') +njangi.cotiser('Ebai') +njangi.solde() // 30000 + +njangi.remettre() // { beneficiaire: 'Ngo', somme: 30000 } +njangi.caisse // undefined : la caisse n’est pas exposée +~~~ + +Personne ne peut plus écrire \`caisse = 0\` depuis l’extérieur. Les règles (pas de double cotisation, pas de remise tant qu’il manque quelqu’un) sont appliquées à un seul endroit. Et si vous créez une deuxième tontine, elle aura sa propre caisse, exactement comme nos deux compteurs. + +Ce modèle porte un nom : le *module pattern*. On l’utilisait beaucoup avant les classes et les modules ES ; il reste très pratique pour fabriquer de petits objets avec un état privé. + +> Depuis ES2022, les classes ont aussi des champs privés (\`#caisse\`). Les deux approches se valent ; les closures restent omniprésentes dès qu’on manipule des fonctions. + +## Le piège classique : la boucle avec \`var\` + +~~~js +for (var i = 1; i <= 3; i++) { + setTimeout(() => console.log(\`Tour \${i}\`), 1000) +} +// Tour 4, Tour 4, Tour 4 +~~~ + +Les trois fonctions passées à \`setTimeout\` capturent la **même** variable \`i\`, car \`var\` est limitée à la fonction, pas au bloc. Quand elles s’exécutent, une seconde plus tard, la boucle est terminée et \`i\` vaut 4. + +Avec \`let\`, chaque tour de boucle crée une nouvelle liaison, et chaque fonction capture la sienne : + +~~~js +for (let i = 1; i <= 3; i++) { + setTimeout(() => console.log(\`Tour \${i}\`), 1000) +} +// Tour 1, Tour 2, Tour 3 +~~~ + +## Vous utilisez déjà des closures + +- **Les gestionnaires d’événements** qui lisent une variable déclarée plus haut. +- **Les hooks React** : à chaque rendu, vos fonctions capturent les props et l’état *de ce rendu-là*. C’est l’origine des fameuses « stale closures » quand un tableau de dépendances est incomplet. +- **\`debounce\`, \`once\`, la mémoïsation** : toutes reposent sur une variable cachée dans une closure. +- **Les fabriques de fonctions** configurées une fois, utilisées partout : + +~~~js +const appliquerTaxe = (taux) => (montant) => Math.round(montant * (1 + taux)) + +const avecTVA = appliquerTaxe(0.1925) +avecTVA(10000) // 11925 +~~~ + +## Et la mémoire ? + +Tant qu’une fonction qui y fait référence reste accessible, les variables capturées ne peuvent pas être libérées par le ramasse-miettes. En pratique, c’est rarement un problème. Méfiez-vous simplement des fonctions qui vivent très longtemps : un écouteur d’événement jamais retiré, un \`setInterval\` jamais arrêté, un cache global qui grossit sans limite. + +## À retenir + +1. Une closure, c’est une fonction **et** l’environnement lexical où elle a été déclarée. +2. Elle permet de créer un état privé sans classe ni variable globale. +3. Chaque appel de la fonction externe crée un nouvel environnement. +4. \`let\` et \`const\` créent une nouvelle liaison à chaque tour de boucle, \`var\` non. + +**Exercice** : ajoutez à la tontine une méthode \`penalite(membre, montant)\` qui ajoute une amende à la caisse, en refusant les montants négatifs. Postez votre solution en commentaire, je relirai avec plaisir. +`, + comments: [ + { + author: 'ebai-tabe', + after: 30, + body: text` +Très clair, merci. Question : pour la caisse, vous recommanderiez plutôt une classe avec \`#caisse\` ou cette version avec closure ? En stage on m’a dit que les closures « consomment plus de mémoire ». +`, + }, + { + author: 'christelle_k', + after: 33, + body: text` +Les deux sont valables. La version closure crée de nouvelles fonctions pour chaque tontine, la classe partage ses méthodes via le prototype : avec des milliers d’instances, la classe est un peu plus économe. Pour quelques dizaines d’objets, choisissez ce qui est le plus lisible pour votre équipe. +`, + }, + { + author: 'aissatou-oumarou', + after: 1650, + body: text` +Je suis tombée sur cet article après mon sujet sur \`setTimeout\` dans une boucle. Ma proposition pour l’exercice : + +~~~js +function penalite(membre, montant) { + if (!liste.includes(membre)) throw new Error(\`\${membre} est inconnu\`) + if (montant <= 0) throw new Error('Montant invalide') + caisse += montant +} +~~~ + +Il faut bien la déclarer dans \`creerTontine\` et l’ajouter à l’objet retourné, c’est ça ? +`, + }, + ], + }, + + /* + |-------------------------------------------------------------------------- + | TypeScript utility types + |-------------------------------------------------------------------------- + */ + { + author: 'christelle_k', + title: 'TypeScript : les types utilitaires du quotidien', + excerpt: + 'Partial, Pick, Omit, Record, ReturnType, Awaited… Ces types fournis par TypeScript évitent de dupliquer vos interfaces. Tour d’horizon avec un exemple concret : les commandes d’une boutique en ligne.', + tags: ['typescript'], + publishedDaysAgo: 41, + views: 960, + body: text` +Le scénario est classique : une interface \`Commande\`, puis une \`CommandeFormulaire\` presque identique, puis une \`CommandeResume\`… Trois mois plus tard, quelqu’un ajoute un champ à la première et oublie les deux autres. Les **types utilitaires** de TypeScript règlent ce problème : on garde une seule source de vérité et on *dérive* le reste. + +Voici notre type de départ, celui d’une boutique en ligne qui livre à Douala et Yaoundé : + +~~~ts +interface Commande { + id: string + client: string + telephone: string + articles: { produitId: string; quantite: number; prixUnitaire: number }[] + montantTotal: number // en FCFA, toujours un entier + statut: 'en_attente' | 'payee' | 'livree' | 'annulee' + creeLe: Date + noteLivraison?: string +} +~~~ + +## \`Partial\` : tout devient optionnel + +Idéal pour une mise à jour partielle : + +~~~ts +async function mettreAJour(id: string, modifications: Partial) { + // ... +} + +mettreAJour('c_42', { statut: 'livree' }) // ok +~~~ + +Attention, \`Partial\` est **superficiel** : les objets imbriqués ne deviennent pas optionnels pour autant. + +## \`Required\` et \`Readonly\` + +\`Required\` fait l’inverse de \`Partial\` : il retire tous les \`?\`. \`Readonly\` interdit la réaffectation des propriétés : + +~~~ts +const archivee: Readonly = chargerArchive() + +archivee.statut = 'annulee' +// Cannot assign to 'statut' because it is a read-only property. +~~~ + +Lui aussi est superficiel : \`archivee.articles.push(...)\` reste autorisé. Pour un tableau en lecture seule, utilisez \`readonly Article[]\` ou \`ReadonlyArray
\`. + +## \`Pick\` et \`Omit\` + +\`Pick\` garde certaines clés, \`Omit\` en retire : + +~~~ts +type ResumeCommande = Pick + +// Ce que le formulaire envoie : le serveur génère id, date et statut +type NouvelleCommande = Omit +~~~ + +Un piège méconnu : \`Omit\` ne vérifie pas que les clés existent. \`Omit\` (faute de frappe) compile sans broncher et ne retire rien. Si cela vous inquiète, une version stricte tient en une ligne : + +~~~ts +type OmitStrict = Omit + +type Test = OmitStrict +// Type '"cree_le"' does not satisfy the constraint 'keyof Commande'. +~~~ + +## \`Record\` : un dictionnaire exhaustif + +~~~ts +type Statut = Commande['statut'] + +const libelles: Record = { + en_attente: 'En attente de paiement', + payee: 'Payée', + livree: 'Livrée', + annulee: 'Annulée', +} +~~~ + +Le jour où vous ajoutez un statut \`'remboursee'\`, TypeScript signale immédiatement que \`libelles\` est incomplet. C’est l’un des meilleurs filets de sécurité du langage. + +## \`Exclude\`, \`Extract\` et \`NonNullable\` + +Ces trois-là travaillent sur les unions : + +~~~ts +type StatutActif = Exclude // 'en_attente' | 'payee' | 'livree' +type StatutFinal = Extract // 'livree' | 'annulee' +type Note = NonNullable // string +~~~ + +## \`ReturnType\`, \`Parameters\` et \`Awaited\` + +Quand le type existe déjà dans une fonction, inutile de le réécrire : + +~~~ts +async function chargerCommande(id: string) { + const response = await fetch(\`/api/commandes/\${id}\`) + return (await response.json()) as Commande +} + +type Resultat = ReturnType // Promise +type CommandeChargee = Awaited // Commande +type Arguments = Parameters // [id: string] +~~~ + +\`Awaited\` « déballe » une promesse, y compris les promesses imbriquées. Très utile pour typer le résultat d’une fonction d’une bibliothèque qui n’exporte pas ses types. + +## Bonus : \`satisfies\` + +\`satisfies\` vérifie qu’une valeur respecte un type **sans élargir** son type inféré : + +~~~ts +const fraisLivraison = { + Douala: 1500, + Yaounde: 2000, + Bafoussam: 2500, +} satisfies Record + +fraisLivraison.Douala // number, avec l’autocomplétion des villes +fraisLivraison.Kribi // erreur : la propriété n’existe pas +~~~ + +Avec une annotation classique (\`const fraisLivraison: Record\`), on aurait perdu la liste des villes et \`fraisLivraison.Kribi\` serait accepté. + +## Les combiner + +Les types utilitaires se composent : + +~~~ts +// Le client peut seulement corriger son téléphone et sa note de livraison +type CorrectionClient = Partial> +~~~ + +## Ma règle de poche + +1. Un type « source » par concept métier. +2. Tous les autres en sont dérivés avec les types utilitaires. +3. Si une expression de type devient illisible, donnez-lui un nom, comme vous le feriez pour une variable. + +Votre code y gagne en cohérence, et les revues de code en sérénité. +`, + comments: [ + { + author: 'junior-mbarga', + after: 20, + body: text` +Le coup de \`OmitStrict\` m’aurait évité une après-midi de débogage le mois dernier. J’ajoute que \`Record\` marche aussi très bien pour les couleurs de badges côté front. +`, + }, + { + author: 'grace-enow', + after: 52, + body: text` +Merci Christelle ! Je ne savais pas que \`satisfies\` gardait le type précis, j’utilisais des annotations partout. Je vais revoir mon fichier de constantes. +`, + }, + ], + }, + + /* + |-------------------------------------------------------------------------- + | Offline-first + |-------------------------------------------------------------------------- + */ + { + author: 'nfor_ngwa', + title: 'Offline-first : une application web qui tient le coup quand la connexion coupe', + excerpt: + 'Zones blanches, 3G qui plafonne, forfait épuisé en fin de mois : vos utilisateurs perdent souvent le réseau. Service Worker, cache et retries avec backoff exponentiel, la recette d’une app qui ne lâche pas.', + tags: ['javascript', 'performance'], + publishedDaysAgo: 62, + featured: true, + views: 2350, + body: text` +Un livreur remplit un bon de livraison sur son téléphone, entre deux quartiers. Le réseau tombe au moment d’envoyer : formulaire perdu, client mécontent, ressaisie à la main le soir. Chez nous, ce scénario n’est pas un cas limite, c’est le quotidien. + +L’approche **offline-first** consiste à traiter le réseau comme une amélioration, pas comme un prérequis. Elle repose sur trois promesses faites à l’utilisateur : + +1. L’interface s’affiche, même sans réseau. +2. Les données déjà consultées restent disponibles. +3. Ses actions ne sont **jamais perdues** : elles partent dès que le réseau revient. + +## 1. Mettre l’application en cache avec un Service Worker + +Un Service Worker est un script qui s’intercale entre votre page et le réseau. Il ne fonctionne qu’en HTTPS (ou sur \`localhost\` pendant le développement). + +~~~js +// main.js +if ('serviceWorker' in navigator) { + window.addEventListener('load', () => { + navigator.serviceWorker.register('/sw.js') + }) +} +~~~ + +Dans \`sw.js\`, on met en cache la « coquille » de l’application à l’installation, on supprime les anciens caches à l’activation, puis on choisit une stratégie selon le type de requête : + +~~~js +// sw.js +const CACHE = 'app-v3' +const COQUILLE = ['/', '/offline.html', '/app.css', '/app.js', '/logo.svg'] + +self.addEventListener('install', (event) => { + event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(COQUILLE))) +}) + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches + .keys() + .then((cles) => Promise.all(cles.filter((cle) => cle !== CACHE).map((cle) => caches.delete(cle)))) + ) +}) + +self.addEventListener('fetch', (event) => { + const { request } = event + if (request.method !== 'GET') return + + const url = new URL(request.url) + event.respondWith(url.pathname.startsWith('/api/') ? reseauDabord(request) : cacheDabord(request)) +}) + +async function cacheDabord(request) { + const enCache = await caches.match(request) + if (enCache) return enCache + + try { + const response = await fetch(request) + if (response.ok) { + const cache = await caches.open(CACHE) + cache.put(request, response.clone()) + } + return response + } catch (error) { + if (request.mode === 'navigate') return caches.match('/offline.html') + throw error + } +} + +async function reseauDabord(request) { + const cache = await caches.open(CACHE) + try { + const response = await fetch(request) + if (response.ok) cache.put(request, response.clone()) + return response + } catch { + const enCache = await cache.match(request) + return ( + enCache ?? + new Response(JSON.stringify({ erreur: 'hors_ligne' }), { + status: 503, + headers: { 'Content-Type': 'application/json' }, + }) + ) + } +} +~~~ + +- **Cache d’abord** pour les fichiers statiques versionnés : instantané, et ça marche hors ligne. +- **Réseau d’abord** pour les données : on montre l’information la plus fraîche possible, et la dernière version connue en cas de coupure. + +Pour un vrai projet, une bibliothèque comme Workbox génère ce code et gère les cas délicats (quotas, mises à jour). Mais comprendre ces vingt lignes vous évitera bien des surprises. + +## 2. Ne pas croire \`navigator.onLine\` sur parole + +\`navigator.onLine === true\` signifie seulement que l’appareil est connecté à *un* réseau. Un Wi-Fi sans crédit ou un portail captif répondent « en ligne » alors qu’aucune requête ne passe. Utilisez-le comme un indice pour l’interface, jamais comme une vérité : + +~~~js +window.addEventListener('offline', () => afficherBandeau('Vous êtes hors ligne. Vos actions partiront au retour du réseau.')) +window.addEventListener('online', () => { + masquerBandeau() + envoyerFileDAttente() +}) +~~~ + +La seule vraie réponse, c’est le succès ou l’échec de la requête. + +## 3. Réessayer intelligemment : backoff exponentiel et jitter + +Réessayer en boucle toutes les secondes vide la batterie et martèle le serveur. On espace donc les tentatives de façon exponentielle (0,5 s, 1 s, 2 s, 4 s…) et on ajoute du **hasard** (*jitter*) : quand le courant revient dans un quartier, des centaines de téléphones retrouvent le réseau en même temps, et on ne veut pas qu’ils frappent tous à la même milliseconde. + +~~~ts +const attendre = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +const A_REESSAYER = new Set([408, 429, 500, 502, 503, 504]) + +export async function fetchAvecRetry( + url: string, + init: RequestInit = {}, + { tentatives = 5, delaiBase = 500, delaiMax = 15_000, timeout = 10_000 } = {} +): Promise { + for (let essai = 0; ; essai++) { + try { + const response = await fetch(url, { ...init, signal: AbortSignal.timeout(timeout) }) + if (!A_REESSAYER.has(response.status) || essai >= tentatives) return response + } catch (error) { + if (essai >= tentatives) throw error + } + + const plafond = Math.min(delaiMax, delaiBase * 2 ** essai) + await attendre(Math.random() * plafond) // « full jitter » + } +} +~~~ + +Quelques règles : + +- On ne réessaie **que** les erreurs réseau, les timeouts, les 429 et les 5xx. Une 400 ou une 422 ne se corrigera pas toute seule. +- Si le serveur envoie un en-tête \`Retry-After\`, respectez-le. +- \`AbortSignal.timeout()\` remplace ici un éventuel \`init.signal\` ; si vous devez combiner les deux, regardez du côté d’\`AbortSignal.any()\`. + +## 4. Une file d’attente pour les actions + +Réessayer ne suffit pas si l’utilisateur ferme l’application. On enregistre donc chaque action sur l’appareil, avec un identifiant unique, avant même de tenter l’envoi : + +~~~ts +type Action = { id: string; url: string; corps: unknown; creeLe: number } + +const CLE = 'file-actions' + +const lireFile = (): Action[] => JSON.parse(localStorage.getItem(CLE) ?? '[]') +const ecrireFile = (file: Action[]) => localStorage.setItem(CLE, JSON.stringify(file)) + +export function enregistrerAction(url: string, corps: unknown) { + ecrireFile([...lireFile(), { id: crypto.randomUUID(), url, corps, creeLe: Date.now() }]) + void envoyerFileDAttente() +} + +let envoiEnCours = false + +export async function envoyerFileDAttente() { + if (envoiEnCours) return + envoiEnCours = true + try { + for (const action of lireFile()) { + const response = await fetchAvecRetry(action.url, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'Idempotency-Key': action.id }, + body: JSON.stringify(action.corps), + }) + if (response.status >= 500) break // le serveur souffre : on réessaiera plus tard + if (!response.ok) notifierEchec(action, response.status) // à vous : toast, badge… + ecrireFile(lireFile().filter((a) => a.id !== action.id)) + } + } catch { + // toujours hors ligne : la file reste intacte + } finally { + envoiEnCours = false + } +} +~~~ + +Le point essentiel est l’en-tête \`Idempotency-Key\`. Si la requête est arrivée au serveur mais que la réponse s’est perdue en route, l’application va la renvoyer. Le serveur doit reconnaître cette clé et ne **pas** créer deux livraisons. + +\`localStorage\` suffit pour quelques dizaines d’actions ; au-delà, ou si vous stockez des photos, passez à IndexedDB. L’API *Background Sync* permet aussi de déclencher l’envoi en arrière-plan, mais elle n’est disponible que dans les navigateurs basés sur Chromium : gardez toujours le déclenchement manuel décrit plus haut. + +## 5. Dire la vérité à l’utilisateur + +Une app offline-first honnête affiche clairement l’état de chaque élément : *enregistré sur l’appareil*, *envoyé*, *échec*. Un petit bandeau « hors ligne » et un compteur d’actions en attente rassurent bien plus qu’un spinner infini. + +## Tester sans quitter son bureau + +Dans les DevTools de Chrome, onglet **Network**, choisissez *Offline* ou un profil lent, puis rechargez. L’onglet **Application** permet d’inspecter le Service Worker, le cache et le \`localStorage\`. Testez aussi sur un vrai téléphone, en mode avion, en plein milieu d’un envoi : c’est là qu’on découvre les vrais bugs. + +Vos utilisateurs ne remarqueront jamais que votre application fonctionne hors ligne. Ils remarqueront seulement qu’elle ne les lâche pas. +`, + comments: [ + { + author: 'patrice-ekambi', + after: 9, + body: text` +Excellent. Côté serveur, pour l’\`Idempotency-Key\`, je stocke la clé avec une contrainte \`UNIQUE\` et la réponse renvoyée la première fois, pendant 24 h. Si la même clé revient, je renvoie la réponse enregistrée sans rien refaire. +`, + }, + { + author: 'lionel_tchak', + after: 27, + body: text` +Le passage sur \`navigator.onLine\` devrait être affiché en grand dans toutes les équipes. Le portail captif de l’hôtel où je travaillais la semaine dernière m’a rappelé la leçon. +`, + }, + { + author: 'yves_fotso', + after: 1010, + body: text` +La même logique d’idempotence s’applique aux paiements, j’en parle dans mon article sur le mobile money. Merci Nfor pour la file d’attente, je l’ai adaptée pour l’app de mes livreurs. +`, + }, + ], + }, + + /* + |-------------------------------------------------------------------------- + | Page weight + |-------------------------------------------------------------------------- + */ + { + author: 'lionel_tchak', + title: 'Alléger ses pages pour les réseaux mobiles : images, code splitting et mesures', + excerpt: + 'La majorité de vos visiteurs arrivent sur mobile, en 3G ou en 4G capricieuse, avec un forfait qui fond à chaque mégaoctet. Méthode pas à pas pour mesurer, puis alléger vos pages.', + tags: ['performance', 'react'], + publishedDaysAgo: 75, + views: 1420, + body: text` +Chaque mégaoctet de votre page est payé par vos visiteurs, au sens propre : il est décompté de leur forfait. Une page de 5 Mo n’est pas seulement lente, elle coûte de l’argent à ceux qui la consultent. Bonne nouvelle : quelques réglages suffisent souvent à diviser son poids par trois. + +## Mesurer avant de toucher quoi que ce soit + +Lighthouse est intégré aux DevTools de Chrome (onglet **Lighthouse**). Par défaut, il simule un téléphone de milieu de gamme sur une connexion lente : exactement ce qu’il nous faut. On peut aussi le lancer en ligne de commande : + +~~~bash +npx lighthouse https://www.example.com --only-categories=performance --view +~~~ + +Concentrez-vous sur les trois *Core Web Vitals* : + +- **LCP** (affichage du plus gros élément) : 2,5 s maximum ; +- **INP** (réactivité aux interactions) : 200 ms maximum ; +- **CLS** (stabilité visuelle) : 0,1 maximum. + +Lighthouse mesure en laboratoire. Pour connaître l’expérience réelle de vos visiteurs, collectez les mêmes métriques sur le terrain avec la bibliothèque \`web-vitals\` : + +~~~js +import { onCLS, onINP, onLCP } from 'web-vitals' + +function envoyer(metrique) { + navigator.sendBeacon('/api/vitals', JSON.stringify(metrique)) +} + +onCLS(envoyer) +onINP(envoyer) +onLCP(envoyer) +~~~ + +Regardez aussi l’onglet **Network** : la colonne *Transferred* indique ce que l’utilisateur télécharge réellement. + +## 1. Les images : le plus gros gisement + +Sur la plupart des sites que j’audite, les images représentent plus de la moitié du poids. Quatre réflexes : + +1. **Le bon format** : AVIF ou WebP, avec JPEG en secours. +2. **La bonne taille** : inutile d’envoyer une photo de 3000 px à un écran de 400 px. +3. **Des dimensions explicites** (\`width\` et \`height\`) pour éviter que la page saute pendant le chargement. +4. **Du lazy loading** sous la ligne de flottaison, mais **jamais** sur l’image principale, qui mérite au contraire \`fetchpriority="high"\`. + +~~~html + + + Pagne wax plié sur un étal + +~~~ + +Pour produire les variantes, un petit script avec \`sharp\` fait l’affaire : + +~~~js +import sharp from 'sharp' + +for (const largeur of [480, 960]) { + const image = sharp('pagne.jpg').resize({ width: largeur }) + await image.clone().avif({ quality: 50 }).toFile(\`pagne-\${largeur}.avif\`) + await image.clone().jpeg({ quality: 75, mozjpeg: true }).toFile(\`pagne-\${largeur}.jpg\`) +} +~~~ + +## 2. Le JavaScript : n’envoyer que ce qui sert + +Le JavaScript coûte deux fois : au téléchargement, puis à l’exécution sur des processeurs modestes. Le *code splitting* permet de ne charger un module que lorsqu’on en a besoin : + +~~~tsx +import { lazy, Suspense, useState } from 'react' + +// Le module doit exporter le composant par défaut +const CarteLivraison = lazy(() => import('./carte-livraison')) + +export function Checkout() { + const [voirCarte, setVoirCarte] = useState(false) + + return ( + <> + + {voirCarte && ( + Chargement de la carte…

}> + +
+ )} + + ) +} +~~~ + +La carte et sa bibliothèque ne sont téléchargées que par ceux qui cliquent. Pour savoir quoi découper, visualisez votre bundle : + +~~~ts +// vite.config.ts +import { defineConfig } from 'vite' +import { visualizer } from 'rollup-plugin-visualizer' + +export default defineConfig({ + plugins: [visualizer({ filename: 'stats.html', gzipSize: true })], +}) +~~~ + +Les coupables habituels : une bibliothèque de dates avec toutes ses langues, une bibliothèque utilitaire importée en entier, un paquet d’icônes complet. Souvent, l’API standard suffit : + +~~~js +new Intl.NumberFormat('fr-CM', { style: 'currency', currency: 'XAF' }).format(15000) +// « 15 000 FCFA » +~~~ + +## 3. Polices, compression et cache + +- **Polices** : deux graisses au maximum, au format WOFF2, avec \`font-display: swap\`. Les polices système sont gratuites. +- **Compression** : vérifiez que le serveur envoie du Brotli ou du gzip. +- **Cache** : les fichiers dont le nom contient un hash peuvent être mis en cache un an ; le HTML, lui, doit être revalidé. + +~~~bash +curl -sI -H 'Accept-Encoding: br, gzip' https://www.example.com/assets/index-3f2a1c.js \ + | grep -iE 'content-encoding|cache-control' +# content-encoding: br +# cache-control: public, max-age=31536000, immutable +~~~ + +Un visiteur qui revient ne retélécharge alors que ce qui a changé. + +## 4. Se fixer un budget + +Sans objectif chiffré, le poids remonte toujours. Pour une page produit, je vise par exemple : + +- moins de 1 Mo transféré au total ; +- moins de 170 Ko de JavaScript compressé ; +- un LCP sous 2,5 s sur un Android d’entrée de gamme. + +Relancez Lighthouse à chaque fonctionnalité importante, idéalement dans votre CI. Sur une boutique de pagnes que j’ai accompagnée, ces quatre étapes ont fait passer la page produit de 4,2 Mo à 780 Ko, et le LCP de 6,1 s à 2,3 s en 4G simulée. Les clients ne l’ont pas dit. Ils ont simplement commandé davantage. +`, + comments: [ + { + author: 'armelle_ngo', + after: 14, + body: text` +Merci Lionel. Petit rappel au passage : un bon \`alt\` décrit l’image pour quelqu’un qui ne la voit pas (« Pagne wax plié sur un étal »), pas son nom de fichier. Et pour une image purement décorative : \`alt=""\`. +`, + }, + { + author: 'grace-enow', + after: 470, + body: text` +J’ai appliqué la partie images sur mon portfolio : 3,1 Mo à 640 Ko. Je ne savais pas qu’il ne fallait pas mettre \`loading="lazy"\` sur l’image du haut, mon LCP a gagné presque une seconde. +`, + }, + ], + }, + + /* + |-------------------------------------------------------------------------- + | Mobile money (backend) + |-------------------------------------------------------------------------- + */ + { + author: 'yves_fotso', + title: 'Intégrer un paiement mobile money côté backend : webhooks, idempotence et signatures', + excerpt: + 'Que vous passiez par l’API d’un opérateur ou par un agrégateur, les mêmes règles évitent les paiements perdus ou encaissés deux fois : machine à états, clé d’idempotence, vérification HMAC des webhooks et réconciliation.', + tags: ['mobile-money', 'nodejs', 'securite'], + publishedDaysAgo: 20, + featured: true, + views: 2980, + body: text` +J’ai intégré le mobile money dans une dizaine de projets, via des opérateurs et via des agrégateurs. Les API changent d’un fournisseur à l’autre (noms des champs, authentification, URL), et leur documentation reste votre référence. Mais l’architecture d’une intégration fiable, elle, est toujours la même. C’est elle que décrit cet article ; les noms de champs utilisés ici sont volontairement génériques. + +## Le parcours d’un paiement + +1. Le client choisit le mobile money et saisit son numéro. +2. Votre backend enregistre un paiement \`PENDING\` avec une référence unique, puis appelle l’API du fournisseur. +3. Le client reçoit une demande de confirmation sur son téléphone et valide avec son code secret. +4. Le fournisseur notifie votre backend par un **webhook** : succès ou échec. +5. Vous livrez la commande. Seulement maintenant. + +Règle d’or : **le navigateur ne dit jamais la vérité sur un paiement.** Une redirection vers \`/merci?status=success\` se falsifie en deux secondes. Seul votre backend, informé par le fournisseur, décide qu’une commande est payée. + +## 1. Un paiement est une machine à états + +~~~sql +CREATE TABLE payments ( + id BIGSERIAL PRIMARY KEY, + reference UUID NOT NULL UNIQUE, -- générée par nous + order_id BIGINT NOT NULL REFERENCES orders (id), + amount INTEGER NOT NULL CHECK (amount > 0), -- en FCFA + phone VARCHAR(12) NOT NULL, + status VARCHAR(12) NOT NULL DEFAULT 'PENDING', + provider_tx_id VARCHAR(64) UNIQUE, -- identifiant côté fournisseur + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +~~~ + +Les transitions autorisées sont simples : \`PENDING\` vers \`SUCCESSFUL\`, \`FAILED\` ou \`EXPIRED\`, et jamais de retour en arrière. Le franc CFA n’a pas de subdivision en usage : stockez des **entiers**, jamais des flottants. + +## 2. Valider et normaliser le numéro + +Les clients saisissent leur numéro de toutes les façons possibles. Normalisez-le avant tout appel : + +~~~ts +export function normaliserNumero(saisie: string): string | null { + const chiffres = saisie.replace(/[\s.-]/g, '') + const resultat = /^(?:\+?237|00237)?(6\d{8})$/.exec(chiffres) + return resultat ? \`237\${resultat[1]}\` : null +} + +normaliserNumero('6 00 11 22 33') // '237600112233' +normaliserNumero('+237 600-11-22-33') // '237600112233' +normaliserNumero('12345') // null +~~~ + +## 3. Initier le paiement avec une référence unique + +~~~ts +import { randomUUID } from 'node:crypto' + +export async function initierPaiement(commande: Commande, telephone: string) { + const reference = randomUUID() + + await db.query('INSERT INTO payments (reference, order_id, amount, phone) VALUES ($1, $2, $3, $4)', [ + reference, + commande.id, + commande.montant, + telephone, + ]) + + const response = await fetch(\`\${process.env.PAYMENT_API_URL}/payments\`, { + method: 'POST', + headers: { + 'Authorization': \`Bearer \${await obtenirJeton()}\`, + 'Content-Type': 'application/json', + 'Idempotency-Key': reference, + }, + body: JSON.stringify({ + amount: commande.montant, + currency: 'XAF', + phone: telephone, + reference, + callbackUrl: \`\${process.env.APP_URL}/webhooks/paiements\`, + }), + signal: AbortSignal.timeout(15_000), + }) + + if (!response.ok) { + throw new Error(\`Initiation refusée par le fournisseur (\${response.status})\`) + } + return reference +} +~~~ + +Ici, \`db\` est un pool \`pg\` classique. Deux détails comptent : + +- **La référence est à vous**, générée *avant* l’appel. Si le fournisseur accepte une clé d’idempotence, un nouvel essai avec la même référence ne déclenchera pas un second débit. +- **Un timeout ne veut pas dire échec.** La demande a peut-être été reçue et le client est peut-être en train de valider. Laissez le paiement en \`PENDING\` : la réconciliation tranchera (voir plus bas). + +## 4. Recevoir le webhook, et le vérifier + +N’importe qui peut envoyer une requête POST sur votre URL de webhook. La plupart des fournisseurs signent donc leurs notifications : ils calculent un **HMAC-SHA256** du corps de la requête avec un secret partagé et l’envoient dans un en-tête. Vous recalculez la signature et comparez. + +Deux pièges : il faut signer le **corps brut**, tel qu’il est arrivé (un \`JSON.stringify(req.body)\` peut différer d’un octet), et comparer en **temps constant** pour ne rien laisser deviner. + +~~~ts +import express from 'express' +import { createHmac, timingSafeEqual } from 'node:crypto' + +const SECRET = process.env.WEBHOOK_SECRET ?? '' +if (SECRET.length < 32) throw new Error('WEBHOOK_SECRET manquant ou trop court') + +function signatureValide(corpsBrut: Buffer, signature: string | undefined) { + if (!signature) return false + const attendue = createHmac('sha256', SECRET).update(corpsBrut).digest() + const recue = Buffer.from(signature, 'hex') + return attendue.length === recue.length && timingSafeEqual(attendue, recue) +} + +const app = express() + +app.post('/webhooks/paiements', express.raw({ type: 'application/json' }), async (req, res) => { + if (!signatureValide(req.body, req.get('X-Signature'))) { + res.sendStatus(401) + return + } + + const evenement = JSON.parse(req.body.toString('utf8')) + await traiterEvenement(evenement) + res.sendStatus(200) +}) +~~~ + +Le nom de l’en-tête et le format (hexadécimal, base64, horodatage inclus ou non) dépendent du fournisseur : vérifiez sa documentation. Si la signature inclut un horodatage, refusez les notifications trop anciennes pour bloquer les rejeux. Et si votre fournisseur ne signe pas ses webhooks, ne faites jamais confiance à leur contenu : utilisez-les comme un simple signal, puis interrogez son API de statut avec vos identifiants. + +## 5. Idempotence : traiter chaque événement une seule fois + +Les webhooks sont livrés « au moins une fois » : vous recevrez des doublons, parfois dans le désordre. La parade tient en une requête SQL, grâce à une **mise à jour conditionnelle** : + +~~~ts +type Evenement = { reference: string; status: string; transactionId: string; amount: number } + +async function traiterEvenement(evt: Evenement) { + if (evt.status !== 'SUCCESSFUL' && evt.status !== 'FAILED') return // statut intermédiaire + + const { rows } = await db.query( + \`UPDATE payments + SET status = $1, provider_tx_id = $2, updated_at = now() + WHERE reference = $3 AND status = 'PENDING' AND amount = $4 + RETURNING order_id\`, + [evt.status, evt.transactionId, evt.reference, evt.amount] + ) + + // Aucune ligne : déjà traité, référence inconnue ou montant incohérent. On journalise et on s’arrête. + if (rows.length === 0) return + + if (evt.status === 'SUCCESSFUL') { + await marquerCommandePayee(rows[0].order_id) + } +} +~~~ + +La condition \`status = 'PENDING'\` garantit qu’un seul traitement aboutit, même si deux notifications arrivent à la même seconde. Idéalement, la mise à jour du paiement et celle de la commande se font dans la même transaction. + +Répondez **vite** au webhook (en quelques secondes) : les envois de SMS, d’e-mails ou de factures partent dans une file de tâches. Sinon, le fournisseur considère l’envoi comme échoué et réessaie. + +## 6. La réconciliation, votre filet de sécurité + +Un webhook peut se perdre : serveur redémarré pendant une coupure de courant, incident chez le fournisseur, certificat expiré. Une tâche planifiée rattrape les paiements restés en suspens : + +~~~ts +// Toutes les cinq minutes (cron, file de tâches…) +const { rows } = await db.query( + \`SELECT reference FROM payments + WHERE status = 'PENDING' AND created_at < now() - interval '3 minutes' + ORDER BY created_at + LIMIT 100\` +) + +for (const { reference } of rows) { + const statut = await consulterStatutChezLeFournisseur(reference) + await traiterEvenement(statut) +} +~~~ + +Au-delà d’un certain délai sans réponse définitive, passez le paiement en \`EXPIRED\` et prévenez le client. Une fois par jour, comparez vos paiements réussis avec le relevé du fournisseur. + +## Check-list avant la mise en production + +- Secrets (clés d’API, secret des webhooks) dans les variables d’environnement, jamais dans le code front. +- Montants en entiers, devise explicite. +- Référence unique générée par vous et contrainte \`UNIQUE\` en base. +- Signature vérifiée sur le corps brut, comparaison en temps constant. +- Mise à jour conditionnelle \`WHERE status = 'PENDING'\`. +- Webhook qui répond vite, traitements lourds en file. +- Tâche de réconciliation et expiration des paiements. +- Référence du paiement dans chaque ligne de log, numéros de téléphone partiellement masqués. +- Tests en environnement de test du fournisseur, y compris un même webhook rejoué deux fois. + +Avec ces règles, vous ne livrerez jamais une commande impayée, et vous n’encaisserez jamais deux fois le même client. C’est tout ce qu’on demande à un paiement. +`, + comments: [ + { + author: 'junior-mbarga', + after: 6, + body: text` +Pour ceux qui sont sur AdonisJS : \`request.raw()\` renvoie le corps brut de la requête, pas besoin de bricoler le bodyparser pour vérifier la signature. +`, + }, + { + author: 'hamadou-bello', + after: 21, + body: text` +Question : pourquoi comparer les longueurs avant \`timingSafeEqual\` ? Ça ne fait pas fuiter une information ? +`, + }, + { + author: 'yves_fotso', + after: 24, + body: text` +\`timingSafeEqual\` lève une exception si les deux buffers n’ont pas la même longueur, d’où le test. La longueur d’un HMAC-SHA256 est publique (32 octets), donc on ne révèle rien d’utile à un attaquant. +`, + }, + { + author: 'patrice-ekambi', + after: 75, + body: text` +La tâche de réconciliation m’a sauvé le mois dernier : le serveur d’un client est resté éteint deux heures pendant un délestage. Quarante paiements validés côté fournisseur, zéro webhook reçu. Tout a été rattrapé automatiquement au redémarrage. +`, + }, + ], + }, +] diff --git a/database/demo/articles_2.ts b/database/demo/articles_2.ts new file mode 100644 index 0000000..8a39e4e --- /dev/null +++ b/database/demo/articles_2.ts @@ -0,0 +1,1084 @@ +import { text, type DemoArticle } from './types.js' + +export const articlesPart2: DemoArticle[] = [ + /* + |-------------------------------------------------------------------------- + | async/await error handling + |-------------------------------------------------------------------------- + */ + { + author: 'patrice-ekambi', + title: 'Gérer proprement les erreurs avec async/await', + excerpt: + 'Promesses oubliées, fetch qui ne rejette pas sur une erreur 500, Promise.all qui échoue en bloc, try/catch partout… Les pièges courants de la gestion d’erreurs asynchrone et les réflexes qui rendent votre code fiable.', + tags: ['javascript', 'nodejs'], + publishedDaysAgo: 54, + views: 1130, + body: text` +\`async\`/\`await\` a rendu le code asynchrone lisible. Il a aussi rendu les erreurs plus faciles à… perdre. Voici les pièges que je retrouve le plus souvent en revue de code, et les réflexes qui les évitent. + +## 1. Une promesse non attendue est une erreur perdue + +~~~js +async function enregistrer(commande) { + try { + sauvegarder(commande) // oubli du await + return 'ok' + } catch (error) { + journaliser(error) // ne sera jamais appelé + } +} +~~~ + +Sans \`await\`, la fonction retourne \`'ok'\` avant que la sauvegarde ne soit terminée, et une éventuelle erreur échappe au \`try/catch\`. Elle devient une *unhandled rejection* : depuis Node.js 15, cela **arrête le processus** par défaut. + +Laissez un outil vous surveiller : la règle \`@typescript-eslint/no-floating-promises\` signale chaque promesse ni attendue, ni retournée, ni explicitement ignorée avec \`void\`. + +## 2. \`fetch\` ne rejette pas sur une erreur HTTP + +\`fetch\` ne rejette que si la requête n’a pas pu aboutir (réseau coupé, DNS, CORS). Une réponse 404 ou 500 est une réponse comme une autre, avec \`response.ok === false\`. Centralisez donc la vérification : + +~~~ts +export async function getJSON(url: string): Promise { + const response = await fetch(url, { signal: AbortSignal.timeout(10_000) }) + if (!response.ok) { + throw new HttpError(response.status, \`\${response.status} sur \${url}\`) + } + return (await response.json()) as T +} +~~~ + +Au passage, \`AbortSignal.timeout()\` évite d’attendre indéfiniment une réponse qui ne viendra pas, ce qui arrive vite sur un réseau mobile. + +## 3. Des erreurs qui portent du sens + +Une classe d’erreur dédiée permet de réagir différemment selon le cas : + +~~~ts +export class HttpError extends Error { + constructor( + public readonly status: number, + message: string, + options?: ErrorOptions + ) { + super(message, options) + this.name = 'HttpError' + } +} +~~~ + +Et quand vous attrapez une erreur pour la relancer avec plus de contexte, gardez l’originale grâce à l’option \`cause\` (ES2022) : + +~~~ts +try { + await envoyerSMS(client.telephone, message) +} catch (error) { + throw new Error(\`Échec de la notification de la commande \${commande.id}\`, { cause: error }) +} +~~~ + +Node.js affiche toute la chaîne des causes dans la trace : on sait *quoi* a échoué et *pourquoi*. + +## 4. Attraper au bon niveau + +Entourer chaque \`await\` d’un \`try/catch\` rend le code illisible et masque souvent les erreurs. Attrapez une erreur là où vous pouvez **faire quelque chose** : réessayer, utiliser une valeur de repli, afficher un message utile. Laissez remonter le reste jusqu’à un gestionnaire central (le gestionnaire d’exceptions de votre framework, un middleware d’erreur, une *error boundary* côté React). + +Attention à Express 4 : il n’attrape pas les promesses rejetées dans les routes \`async\`, il faut un petit wrapper ou passer à Express 5, qui transmet ces erreurs au middleware d’erreur. + +Et un détail qui piège même les seniors : + +~~~js +async function chargerProduits() { + try { + return await getJSON('/api/produits') // sans await, le catch ne verrait jamais l’erreur + } catch (error) { + journaliser(error) + return [] + } +} +~~~ + +Dans un bloc \`try\`, écrivez \`return await\`, sinon la promesse est retournée telle quelle et son rejet se produit *après* la sortie du \`try\`. + +## 5. \`Promise.all\`, \`allSettled\` et \`any\` + +\`Promise.all\` rejette dès la première erreur, ce qui convient quand tout est nécessaire : + +~~~js +const [produits, categories] = await Promise.all([getJSON('/api/produits'), getJSON('/api/categories')]) +~~~ + +Les autres promesses continuent cependant de s’exécuter : \`Promise.all\` n’annule rien. Quand chaque opération est indépendante, préférez \`Promise.allSettled\` : + +~~~js +const resultats = await Promise.allSettled(numeros.map((numero) => envoyerSMS(numero, message))) +const echecs = resultats.filter((resultat) => resultat.status === 'rejected') + +console.log(\`\${echecs.length} SMS non envoyés sur \${numeros.length}\`) +~~~ + +\`Promise.any\`, enfin, renvoie le premier succès : pratique pour interroger plusieurs serveurs miroirs. + +## 6. Le motif « Result » pour les erreurs attendues + +Pour les erreurs qui font partie du fonctionnement normal (produit introuvable, solde insuffisant), un objet résultat est souvent plus clair qu’une exception : + +~~~ts +type Result = { ok: true; value: T } | { ok: false; error: Error } + +export async function essayer(promesse: Promise): Promise> { + try { + return { ok: true, value: await promesse } + } catch (error) { + return { ok: false, error: error instanceof Error ? error : new Error(String(error)) } + } +} + +const resultat = await essayer(getJSON('/api/produits')) +if (resultat.ok) { + afficherProduits(resultat.value) +} else { + afficherErreur('Impossible de charger les produits pour le moment.') +} +~~~ + +TypeScript vous oblige alors à traiter les deux cas. + +## 7. Dans un \`catch\`, l’erreur est \`unknown\` + +En mode \`strict\`, TypeScript type la variable du \`catch\` en \`unknown\`, et il a raison : on peut lancer n’importe quoi en JavaScript, y compris une chaîne. Vérifiez avant d’utiliser : + +~~~ts +async function trouverProduit(id: string) { + try { + return await getJSON(\`/api/produits/\${id}\`) + } catch (error) { + if (error instanceof HttpError && error.status === 404) return null // cas prévu + throw error // tout le reste remonte + } +} +~~~ + +## 8. Le dernier filet + +Pour ce qui passe malgré tout, journalisez avant de laisser le processus s’arrêter, puis comptez sur votre superviseur (systemd, la politique de redémarrage de Docker…) pour le relancer dans un état propre : + +~~~js +process.on('unhandledRejection', (raison) => { + logger.fatal({ raison }, 'Promesse rejetée non gérée') + process.exit(1) +}) +~~~ + +Côté navigateur, l’équivalent est l’événement \`unhandledrejection\` sur \`window\`, idéal pour remonter les erreurs vers votre outil de suivi. + +## En résumé + +- Toujours \`await\` ou retourner une promesse (et laisser ESLint vérifier). +- Vérifier \`response.ok\` après chaque \`fetch\`. +- Des erreurs typées, avec une \`cause\`. +- Attraper là où l’on peut agir, centraliser le reste. +- \`return await\` dans un \`try\`. +- \`allSettled\` pour les opérations indépendantes. + +Une erreur bien gérée, c’est un incident de cinq minutes au lieu d’une nuit blanche. +`, + comments: [ + { + author: 'ebai-tabe', + after: 18, + body: text` +J’ai activé \`no-floating-promises\` sur le projet de mon stage après avoir lu ça : quatorze avertissements, dont deux vrais bugs en production. Merci ! +`, + }, + { + author: 'hamadou-bello', + after: 40, + body: text` +Le \`return await\` dans un \`try\` est une question que je pose souvent en entretien. Presque personne ne connaît la réponse, alors que c’est la source de bugs bien sournois. +`, + }, + ], + }, + + /* + |-------------------------------------------------------------------------- + | AdonisJS REST API + |-------------------------------------------------------------------------- + */ + { + author: 'junior-mbarga', + title: 'Démarrer une API REST avec AdonisJS', + excerpt: + 'Routes, contrôleurs, validation, base de données : AdonisJS fournit tout ce qu’il faut pour une API Node.js solide sans assembler vingt paquets. Pas à pas, construisons l’API du catalogue d’une petite boutique.', + tags: ['adonisjs', 'nodejs', 'typescript'], + publishedDaysAgo: 33, + views: 1290, + body: text` +Quand on démarre une API Node.js avec un micro-framework, on passe la première semaine à choisir un validateur, un ORM, un système de migrations, une bibliothèque d’authentification… puis à les faire cohabiter. AdonisJS prend le parti inverse : un framework complet, écrit en TypeScript, avec des conventions claires. Pour une équipe, c’est un gain énorme : tout le monde sait où se trouve quoi. + +Construisons ensemble l’API du catalogue d’une boutique : lister, créer, modifier et supprimer des produits. + +## Créer le projet + +~~~bash +npm init adonisjs@latest catalogue-api +~~~ + +L’assistant vous demande quel kit de démarrage utiliser : choisissez **API**. Ensuite : + +~~~bash +cd catalogue-api +node ace serve --hmr +~~~ + +L’API répond sur \`http://localhost:3333\`. Les dossiers à connaître : + +- \`start/routes.ts\` : les routes ; +- \`app/controllers\`, \`app/models\`, \`app/validators\` : le code métier ; +- \`database/migrations\` : l’évolution du schéma ; +- \`.env\` : la configuration, notamment l’accès à la base de données (\`DB_HOST\`, \`DB_USER\`, \`DB_DATABASE\`…). + +Si Lucid, l’ORM d’AdonisJS, n’est pas encore installé dans votre projet : \`node ace add @adonisjs/lucid\`. + +## La migration et le modèle + +~~~bash +node ace make:model Product -m +~~~ + +L’option \`-m\` crée aussi une migration. Complétons-la : + +~~~ts +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'products' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id') + table.string('name', 120).notNullable() + table.integer('price').notNullable() // en FCFA + table.integer('stock').notNullable().defaultTo(0) + table.timestamp('created_at') + table.timestamp('updated_at') + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} +~~~ + +~~~bash +node ace migration:run +~~~ + +Depuis AdonisJS 7, Lucid génère un fichier \`database/schema.ts\` à partir de vos migrations : chaque table y devient une classe dont les colonnes sont déjà typées. Votre modèle se contente d’en hériter, et c’est là que vous ajouterez relations et méthodes : + +~~~ts +// app/models/product.ts +import { ProductSchema } from '#database/schema' + +export default class Product extends ProductSchema {} +~~~ + +Sur AdonisJS 6, on déclare les colonnes soi-même dans le modèle, avec \`@column()\` et \`@column.dateTime({ autoCreate: true })\`. Le reste de l’article s’applique aux deux versions. + +## Valider les entrées avec VineJS + +Ne faites jamais confiance aux données reçues. AdonisJS embarque VineJS, un validateur rapide qui infère les types TypeScript : + +~~~bash +node ace make:validator product --resource +~~~ + +~~~ts +// app/validators/product.ts +import vine from '@vinejs/vine' + +export const createProductValidator = vine.create({ + name: vine.string().trim().minLength(2).maxLength(120), + price: vine.number().withoutDecimals().positive(), + stock: vine.number().withoutDecimals().min(0).optional(), +}) + +export const updateProductValidator = vine.create({ + name: vine.string().trim().minLength(2).maxLength(120).optional(), + price: vine.number().withoutDecimals().positive().optional(), + stock: vine.number().withoutDecimals().min(0).optional(), +}) +~~~ + +Avec les versions plus anciennes de VineJS, l’équivalent s’écrit \`vine.compile(vine.object({ ... }))\`. + +## Le contrôleur + +~~~bash +node ace make:controller products --api +~~~ + +L’option \`--api\` génère les cinq méthodes d’une ressource d’API : \`index\`, \`store\`, \`show\`, \`update\` et \`destroy\`. + +~~~ts +// app/controllers/products_controller.ts +import type { HttpContext } from '@adonisjs/core/http' +import Product from '#models/product' +import { createProductValidator, updateProductValidator } from '#validators/product' + +export default class ProductsController { + async index({ request }: HttpContext) { + const page = request.input('page', 1) + return Product.query().orderBy('name').paginate(page, 20) + } + + async store({ request, response }: HttpContext) { + const payload = await request.validateUsing(createProductValidator) + const product = await Product.create(payload) + return response.created(product) + } + + async show({ params }: HttpContext) { + return Product.findOrFail(params.id) + } + + async update({ params, request }: HttpContext) { + const product = await Product.findOrFail(params.id) + const payload = await request.validateUsing(updateProductValidator) + return product.merge(payload).save() + } + + async destroy({ params, response }: HttpContext) { + const product = await Product.findOrFail(params.id) + await product.delete() + return response.noContent() + } +} +~~~ + +Remarquez ce qui **n’est pas** écrit : aucune gestion manuelle des erreurs. \`findOrFail\` renvoie automatiquement une 404 si le produit n’existe pas, et \`validateUsing\` une 422 qui liste les champs invalides. + +## Les routes + +~~~ts +// start/routes.ts +import router from '@adonisjs/core/services/router' + +const ProductsController = () => import('#controllers/products_controller') + +router + .group(() => { + router.resource('products', ProductsController).apiOnly() + }) + .prefix('/api/v1') +~~~ + +Le contrôleur est importé paresseusement : il n’est chargé qu’à la première requête, ce qui accélère le démarrage. Vérifiez le résultat : + +~~~bash +node ace list:routes +~~~ + +## Essayer + +~~~bash +curl -X POST http://localhost:3333/api/v1/products \ + -H 'Content-Type: application/json' \ + -H 'Accept: application/json' \ + -d '{"name": "Pagne wax 6 yards", "price": 15000, "stock": 12}' +~~~ + +Envoyez ensuite un prix négatif : la réponse 422 indique précisément quel champ pose problème et pourquoi. + +## Et ensuite ? + +En une heure, vous avez une API paginée, validée et typée de bout en bout. Pour aller plus loin, tout est déjà prévu dans l’écosystème : + +- l’authentification par jetons d’accès avec \`@adonisjs/auth\` ; +- la limitation de débit avec \`@adonisjs/limiter\` ; +- la configuration CORS dans \`config/cors.ts\` ; +- les tests avec Japa : \`node ace test\`. + +Si vous démarrez un projet backend en TypeScript, donnez-lui sa chance. Et posez vos questions dans le canal Node.js & Backend du forum, on se fera un plaisir de vous aider. +`, + comments: [ + { + author: 'hamadou-bello', + after: 26, + body: text` +Très bon tutoriel. Pour les lecteurs qui viennent d’Express : le gain le plus visible au quotidien, c’est \`validateUsing\` qui renvoie un objet déjà typé. Plus de \`req.body as any\`. +`, + }, + ], + }, + + /* + |-------------------------------------------------------------------------- + | useMemo / useCallback + |-------------------------------------------------------------------------- + */ + { + author: 'armelle_ngo', + title: 'React : quand utiliser useMemo et useCallback (et quand s’en passer)', + excerpt: + 'Mettre useMemo et useCallback partout ne rend pas une application plus rapide. Les trois situations où ils servent vraiment, comment le vérifier avec le Profiler, et ce que change le React Compiler.', + tags: ['react', 'performance'], + publishedDaysAgo: 12, + views: 870, + body: text` +En revue de code, je vois régulièrement des composants où chaque valeur est enveloppée dans un \`useMemo\` et chaque fonction dans un \`useCallback\`, « pour la performance ». Le résultat est presque toujours le même : un code plus difficile à lire, et aucun gain mesurable. Remettons ces deux hooks à leur place. + +## Ce qu’ils font vraiment + +- \`useMemo(calcul, deps)\` mémorise le **résultat** d’un calcul entre deux rendus, tant que les dépendances ne changent pas. +- \`useCallback(fn, deps)\` mémorise la **fonction** elle-même. C’est exactement \`useMemo(() => fn, deps)\`. + +Les dépendances sont comparées avec \`Object.is\`. Ces hooks n’accélèrent pas le premier rendu ; ils ajoutent même un léger coût (comparaison des dépendances, mémoire). Ils ne sont utiles que si ce qu’ils évitent coûte plus cher que ce qu’ils coûtent. + +## Cas n° 1 : un calcul réellement coûteux + +~~~tsx +type Transaction = { id: string; libelle: string; montant: number; date: number } + +function Releve({ transactions, filtre }: { transactions: Transaction[]; filtre: string }) { + const visibles = useMemo(() => { + const recherche = filtre.toLowerCase() + return transactions + .filter((t) => t.libelle.toLowerCase().includes(recherche)) + .sort((a, b) => b.date - a.date) + }, [transactions, filtre]) + + return +} +~~~ + +Filtrer et trier quelques milliers de transactions à chaque frappe peut se sentir sur un téléphone d’entrée de gamme. Comment savoir ? On mesure : + +~~~ts +console.time('filtrage') +const visibles = filtrerEtTrier(transactions, filtre) +console.timeEnd('filtrage') +~~~ + +Activez le ralentissement du processeur (×4 ou ×6) dans l’onglet **Performance** des DevTools : la plupart de vos utilisateurs n’ont pas votre ordinateur. Si le temps mesuré dépasse régulièrement la milliseconde, \`useMemo\` est justifié. + +## Cas n° 2 : une référence stable pour un composant mémoïsé + +~~~tsx +const LigneTransaction = memo(function LigneTransaction({ + transaction, + onAnnuler, +}: { + transaction: Transaction + onAnnuler: (id: string) => void +}) { + return ( +
  • + {transaction.libelle} + +
  • + ) +}) + +function Historique({ transactions }: { transactions: Transaction[] }) { + const [recherche, setRecherche] = useState('') + + const annuler = useCallback((id: string) => { + void annulerTransaction(id) + }, []) + + return ( + <> + setRecherche(e.target.value)} /> +
      + {transactions.map((t) => ( + + ))} +
    + + ) +} +~~~ + +À chaque frappe, \`Historique\` se rend à nouveau. \`memo\` permet aux lignes de ne pas suivre, **à condition** que leurs props ne changent pas. Sans \`useCallback\`, \`annuler\` serait une nouvelle fonction à chaque rendu, et \`memo\` ne servirait à rien. Retenez le couple : \`memo\` sur l’enfant, \`useCallback\` dans le parent. L’un sans l’autre est inutile. + +## Cas n° 3 : une dépendance d’effet + +~~~tsx +function SuiviPaiement({ reference }: { reference: string }) { + const options = useMemo(() => ({ reference, intervalle: 5000 }), [reference]) + + useEffect(() => { + const abonnement = suivrePaiement(options) + return () => abonnement.arreter() + }, [options]) + + // ... +} +~~~ + +Sans \`useMemo\`, l’objet \`options\` serait recréé à chaque rendu et l’effet se relancerait sans cesse. Mais il existe souvent mieux : créer l’objet **dans** l’effet et ne dépendre que de \`reference\`, une chaîne, stable par nature. Et si l’objet ne dépend de rien, déclarez-le hors du composant : une référence stable, gratuitement. + +## Quand s’en passer + +- **Les calculs triviaux** : \`prix * quantite\`, un \`.map\` sur vingt éléments. +- **Les fonctions passées à un élément natif** (\`
    ') + assert.include(html, 'type="checkbox"') + assert.include(html, 'barré') + }) + + test('never renders raw HTML or scripts', async ({ assert }) => { + const html = await renderMarkdown( + '\n\n\n\n' + ) + assert.notInclude(html, ' { + const html = await renderMarkdown('[clic](javascript:alert(1)) ![x](javascript:alert(2))') + assert.notInclude(html.toLowerCase(), 'javascript:') + }) + + test('external links are nofollow and open in a new tab', async ({ assert }) => { + const html = await renderMarkdown('[site](https://example.com)') + assert.include(html, 'target="_blank"') + assert.include(html, 'rel="nofollow ugc noopener noreferrer"') + }) + + test('highlights fenced code with Shiki dual themes', async ({ assert }) => { + const html = await renderMarkdown('```ts\nconst answer: number = 42\n```') + assert.include(html, 'class="shiki') + assert.include(html, '--shiki-dark') + }) + + test('unknown languages fall back to plain text', async ({ assert }) => { + const html = await renderMarkdown('```brainfuck-2099\n+++\n```') + assert.include(html, ' { + let ticks = 0 + const interval = setInterval(() => ticks++, 100) + const started = Date.now() + await assert.rejects(() => renderMarkdown('*_'.repeat(29_000)), /trop complexe/) + clearInterval(interval) + + const elapsed = Date.now() - started + assert.isBelow(elapsed, 8_000) + // The event loop kept running while the worker was busy. + assert.isAbove(ticks, Math.floor(elapsed / 100) - 10) + + // The renderer recovers with a fresh worker. + assert.include(await renderMarkdown('**ok**'), 'ok') + }).timeout(15_000) + + test('excerpt helpers stay linear on hostile input', ({ assert }) => { + const started = Date.now() + plainExcerpt('['.repeat(100_000)) + plainExcerpt('```\n'.repeat(30_000)) + readingMinutes('```\n'.repeat(30_000)) + assert.isBelow(Date.now() - started, 200) + }) + + test('reading time and excerpt', ({ assert }) => { + assert.equal(readingMinutes('mot '.repeat(10)), 1) + assert.equal(readingMinutes('mot '.repeat(1100)), 5) + assert.equal( + plainExcerpt('## Titre\n\nUn **texte** avec [un lien](https://x.y).'), + 'Un texte avec un lien.' + ) + assert.isAtMost(plainExcerpt('a'.repeat(500), 100).length, 100) + }) +}) diff --git a/tests/unit/safe_redirect.spec.ts b/tests/unit/safe_redirect.spec.ts new file mode 100644 index 0000000..15e8b0b --- /dev/null +++ b/tests/unit/safe_redirect.spec.ts @@ -0,0 +1,22 @@ +import { test } from '@japa/runner' +import { safeRedirectPath } from '#services/safe_redirect' + +test.group('safeRedirectPath', () => { + test('keeps same-site relative paths', ({ assert }) => { + assert.equal(safeRedirectPath('/forum/ma-question?x=1#r'), '/forum/ma-question?x=1#r') + }) + + test('rejects absolute and protocol-relative URLs', ({ assert }) => { + for (const value of [ + 'https://evil.test', + '//evil.test', + '/\\evil.test', + 'javascript:alert(1)', + '', + null, + 42, + ]) { + assert.equal(safeRedirectPath(value), '/dashboard') + } + }) +}) diff --git a/tmp/.gitkeep b/tmp/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tsconfig.inertia.json b/tsconfig.inertia.json new file mode 100644 index 0000000..0caef63 --- /dev/null +++ b/tsconfig.inertia.json @@ -0,0 +1,16 @@ +/** + * This file only exists to avoid the circular reference between the Inertia + * codebase and the backend codebase, which takes place because of the + * codegen. We have Inertia app referencing backend code and backend + * code referencing Inertia pages for inferring props types. + * + * The main part here is "composite: true" + */ +{ + "extends": "./inertia/tsconfig.json", + "compilerOptions": { + "rootDir": "./inertia", + "composite": true + }, + "include": ["./inertia/**/*.ts", "./inertia/**/*.tsx"] +} diff --git a/tsconfig.json b/tsconfig.json index cd3596e..8736a5d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,8 +2,8 @@ "extends": "@adonisjs/tsconfig/tsconfig.app.json", "compilerOptions": { "rootDir": "./", - "outDir": "./build", + "jsx": "react", + "outDir": "./build" }, - "exclude": ["./inertia/**/*", "node_modules", "build"], - + "references": [{ "path": "./tsconfig.inertia.json" }] } diff --git a/vite.config.ts b/vite.config.ts index baf019f..bce3f09 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,14 +1,17 @@ import { defineConfig } from 'vite' -import { getDirname } from '@adonisjs/core/helpers' -import inertia from '@adonisjs/inertia/client' import react from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' import adonisjs from '@adonisjs/vite/client' export default defineConfig({ plugins: [ - inertia({ ssr: { enabled: true, entrypoint: 'inertia/app/ssr.tsx' } }), react(), - adonisjs({ entrypoints: ['inertia/app/app.tsx'], reload: ['resources/views/**/*.edge'] }), + tailwindcss(), + adonisjs({ + entryPoints: ['inertia/app/app.tsx'], + serverEntryPoints: ['inertia/app/ssr.tsx'], + reload: ['resources/views/**/*.edge'], + }), ], /** @@ -17,7 +20,14 @@ export default defineConfig({ */ resolve: { alias: { - '~/': `${getDirname(import.meta.url)}/inertia/`, + '~/': `${import.meta.dirname}/inertia/`, + '@generated': `${import.meta.dirname}/.adonisjs/client/`, + }, + }, + + server: { + watch: { + ignored: ['**/storage/**', '**/tmp/**'], }, }, })