From 65982bceda8c99fbadb0791f7fd336be12cd32a0 Mon Sep 17 00:00:00 2001 From: Brightky Efoo Date: Wed, 7 Oct 2026 21:01:45 +0100 Subject: [PATCH 01/17] Migrate to AdonisJS 7, PostgreSQL and a new design system - Rebuild on the AdonisJS 7 Inertia/React starter (Inertia 3, Vite 8, React 19.3) - Switch to PostgreSQL; full schema for articles, tags, forum channels/threads, discussions, replies, likes and rate limits; fix migration ordering - Self-hosted GitHub OAuth (Ally has no AdonisJS 7 release), login by e-mail or username, remember-me, rate-limited auth, safe post-login redirects - Markdown pipeline (GFM, sanitize, Shiki dual theme) rendered server-side - Tailwind 4 design system: paper/ink tokens, JS-yellow accent, Bricolage Grotesque + JetBrains Mono, light/dark themes, SSR enabled - New home page, auth pages, error pages, shared UI components - robots.txt (noindex outside production), sitemap.xml, RSS feed --- .adonisjs/client/data.d.ts | 49 + .adonisjs/client/manifest.d.ts | 11 + .adonisjs/client/registry/index.ts | 113 + .adonisjs/client/registry/schema.d.ts | 190 + .adonisjs/client/registry/tree.d.ts | 31 + .adonisjs/server/controllers.ts | 18 + .adonisjs/server/events.ts | 6 + .adonisjs/server/listeners.ts | 6 + .adonisjs/server/pages.d.ts | 26 + .adonisjs/server/routes.d.ts | 59 + .env.example | 25 +- .gitignore | 3 +- .prettierignore | 3 + ace.js | 4 +- adonisrc.ts | 54 +- app/controllers/auth/github_controller.ts | 112 +- app/controllers/auth/login_controller.ts | 51 +- app/controllers/auth/register_controller.ts | 14 +- app/controllers/home_controller.ts | 58 +- app/controllers/markdown_controller.ts | 14 + app/controllers/replies_controller.ts | 46 + app/controllers/seo_controller.ts | 113 + app/exceptions/handler.ts | 6 +- app/middleware/auth_middleware.ts | 20 +- .../container_bindings_middleware.ts | 3 +- app/middleware/guest_middleware.ts | 2 + app/middleware/inertia_middleware.ts | 67 + app/middleware/silent_auth_middleware.ts | 1 - app/models/article.ts | 55 +- app/models/channel.ts | 9 + app/models/discussion.ts | 21 + app/models/like.ts | 9 + app/models/reply.ts | 30 + app/models/tag.ts | 13 + app/models/thread.ts | 28 + app/models/user.ts | 105 +- app/services/github_oauth.ts | 110 + app/services/markdown.ts | 106 + app/services/reply_service.ts | 96 + app/services/safe_redirect.ts | 9 + app/services/slug.ts | 20 + app/transformers/article_transformer.ts | 52 + app/transformers/channel_transformer.ts | 11 + app/transformers/discussion_transformer.ts | 39 + app/transformers/reply_transformer.ts | 23 + app/transformers/tag_transformer.ts | 12 + app/transformers/thread_transformer.ts | 42 + app/transformers/user_transformer.ts | 46 + app/validators/login_validator.ts | 14 +- app/validators/register_validator.ts | 48 +- app/validators/reply_validator.ts | 5 + bin/console.ts | 4 +- bin/server.ts | 4 +- bin/test.ts | 2 +- commands/promote_user.ts | 45 + config/ally.ts | 25 +- config/app.ts | 62 +- config/auth.ts | 13 +- config/bodyparser.ts | 41 +- config/cors.ts | 33 +- config/database.ts | 18 +- config/encryption.ts | 34 + config/hash.ts | 51 + config/inertia.ts | 32 +- config/limiter.ts | 26 + config/logger.ts | 34 +- config/session.ts | 32 +- config/shield.ts | 56 +- config/static.ts | 17 +- config/vite.ts | 6 + .../1736839410875_create_users_table.ts | 31 +- ...410900_create_remember_me_tokens_table.ts} | 6 +- .../1736839410950_create_articles_table.ts | 37 + .../17368394109899_create_articles_table.ts | 23 - .../1760000000100_create_tags_table.ts | 21 + .../1760000000110_create_article_tag_table.ts | 30 + .../1760000000200_create_channels_table.ts | 22 + .../1760000000210_create_threads_table.ts | 44 + .../1760000000300_create_discussions_table.ts | 36 + ...60000000310_create_discussion_tag_table.ts | 30 + .../1760000000400_create_replies_table.ts | 62 + ...00000410_add_solution_reply_to_threads.ts} | 12 +- .../1760000000500_create_likes_table.ts | 47 + .../1760000000600_create_rate_limits_table.ts | 17 + database/schema.ts | 268 + database/schema_rules.ts | 14 + database/seeders/01_base_seeder.ts | 56 + database/seeders/user_seeder.ts | 28 - eslint.config.js | 4 +- inertia/app/app.tsx | 30 +- inertia/app/resolve_page.ts | 25 + inertia/app/ssr.tsx | 18 +- inertia/client.ts | 9 + inertia/components/articles-section.tsx | 118 +- inertia/components/articles/create-form.tsx | 201 +- inertia/components/articles/list.tsx | 169 +- inertia/components/create-content-modal.tsx | 199 +- .../discussions/discussion-list.tsx | 55 + inertia/components/flash-toasts.tsx | 28 + inertia/components/footer.tsx | 253 +- inertia/components/forum/thread-list.tsx | 78 + inertia/components/github-button.tsx | 21 + inertia/components/logo.tsx | 32 + inertia/components/navbar.tsx | 320 +- inertia/components/open-source-section.tsx | 85 +- inertia/components/replies/reply-form.tsx | 89 + inertia/components/replies/reply-list.tsx | 185 + inertia/components/seo.tsx | 49 + inertia/components/slide-over.tsx | 83 +- inertia/components/theme-toggle.tsx | 43 + inertia/components/ui/avatar.tsx | 56 + inertia/components/ui/button.tsx | 78 + inertia/components/ui/confirm-dialog.tsx | 45 + inertia/components/ui/empty-state.tsx | 33 + inertia/components/ui/field.tsx | 112 + inertia/components/ui/markdown-editor.tsx | 180 + inertia/components/ui/menu.tsx | 79 + inertia/components/ui/page-header.tsx | 37 + inertia/components/ui/pagination.tsx | 86 + inertia/components/ui/prose.tsx | 13 + inertia/components/ui/section-heading.tsx | 50 + inertia/components/ui/tag.tsx | 38 + inertia/components/ui/time-ago.tsx | 14 + inertia/css/app.css | 386 +- inertia/layouts/app.tsx | 43 +- inertia/layouts/auth.tsx | 55 + inertia/layouts/dashboard.tsx | 20 +- inertia/lib/format.ts | 50 + inertia/lib/http.ts | 24 + inertia/pages/articles/[slug].tsx | 74 +- inertia/pages/articles/create.tsx | 101 +- inertia/pages/articles/index.tsx | 56 +- inertia/pages/auth/login.tsx | 270 +- inertia/pages/auth/register.tsx | 321 +- inertia/pages/dashboard/index.tsx | 64 +- inertia/pages/errors/not_found.tsx | 33 +- inertia/pages/errors/server_error.tsx | 29 +- inertia/pages/home.tsx | 319 +- inertia/pages/profile/show.tsx | 99 +- inertia/tsconfig.json | 13 +- inertia/types.ts | 18 + package-lock.json | 12037 +++++++--------- package.json | 129 +- providers/api_provider.ts | 69 + public/favicon.svg | 1 + resources/views/inertia_layout.edge | 106 +- start/env.ts | 30 +- start/kernel.ts | 2 +- start/limiter.ts | 37 + start/routes.ts | 94 +- start/routes/admin.ts | 8 + start/routes/articles.ts | 8 + start/routes/discussions.ts | 8 + start/routes/forum.ts | 8 + start/routes/members.ts | 8 + start/validator.ts | 56 + tests/bootstrap.ts | 13 +- tmp/.gitkeep | 0 tsconfig.inertia.json | 16 + tsconfig.json | 6 +- vite.config.ts | 20 +- 161 files changed, 11765 insertions(+), 9108 deletions(-) create mode 100644 .adonisjs/client/data.d.ts create mode 100644 .adonisjs/client/manifest.d.ts create mode 100644 .adonisjs/client/registry/index.ts create mode 100644 .adonisjs/client/registry/schema.d.ts create mode 100644 .adonisjs/client/registry/tree.d.ts create mode 100644 .adonisjs/server/controllers.ts create mode 100644 .adonisjs/server/events.ts create mode 100644 .adonisjs/server/listeners.ts create mode 100644 .adonisjs/server/pages.d.ts create mode 100644 .adonisjs/server/routes.d.ts create mode 100644 .prettierignore create mode 100644 app/controllers/markdown_controller.ts create mode 100644 app/controllers/replies_controller.ts create mode 100644 app/controllers/seo_controller.ts create mode 100644 app/middleware/inertia_middleware.ts create mode 100644 app/models/channel.ts create mode 100644 app/models/discussion.ts create mode 100644 app/models/like.ts create mode 100644 app/models/reply.ts create mode 100644 app/models/tag.ts create mode 100644 app/models/thread.ts create mode 100644 app/services/github_oauth.ts create mode 100644 app/services/markdown.ts create mode 100644 app/services/reply_service.ts create mode 100644 app/services/safe_redirect.ts create mode 100644 app/services/slug.ts create mode 100644 app/transformers/article_transformer.ts create mode 100644 app/transformers/channel_transformer.ts create mode 100644 app/transformers/discussion_transformer.ts create mode 100644 app/transformers/reply_transformer.ts create mode 100644 app/transformers/tag_transformer.ts create mode 100644 app/transformers/thread_transformer.ts create mode 100644 app/transformers/user_transformer.ts create mode 100644 app/validators/reply_validator.ts create mode 100644 commands/promote_user.ts create mode 100644 config/encryption.ts create mode 100644 config/limiter.ts rename database/migrations/{1740725627468_create_remember_me_tokens_table.ts => 1736839410900_create_remember_me_tokens_table.ts} (72%) create mode 100644 database/migrations/1736839410950_create_articles_table.ts delete mode 100644 database/migrations/17368394109899_create_articles_table.ts create mode 100644 database/migrations/1760000000100_create_tags_table.ts create mode 100644 database/migrations/1760000000110_create_article_tag_table.ts create mode 100644 database/migrations/1760000000200_create_channels_table.ts create mode 100644 database/migrations/1760000000210_create_threads_table.ts create mode 100644 database/migrations/1760000000300_create_discussions_table.ts create mode 100644 database/migrations/1760000000310_create_discussion_tag_table.ts create mode 100644 database/migrations/1760000000400_create_replies_table.ts rename database/migrations/{1736839410999_add_author_id_to_articles.ts => 1760000000410_add_solution_reply_to_threads.ts} (51%) create mode 100644 database/migrations/1760000000500_create_likes_table.ts create mode 100644 database/migrations/1760000000600_create_rate_limits_table.ts create mode 100644 database/schema.ts create mode 100644 database/schema_rules.ts create mode 100644 database/seeders/01_base_seeder.ts delete mode 100644 database/seeders/user_seeder.ts create mode 100644 inertia/app/resolve_page.ts create mode 100644 inertia/client.ts create mode 100644 inertia/components/discussions/discussion-list.tsx create mode 100644 inertia/components/flash-toasts.tsx create mode 100644 inertia/components/forum/thread-list.tsx create mode 100644 inertia/components/github-button.tsx create mode 100644 inertia/components/logo.tsx create mode 100644 inertia/components/replies/reply-form.tsx create mode 100644 inertia/components/replies/reply-list.tsx create mode 100644 inertia/components/seo.tsx create mode 100644 inertia/components/theme-toggle.tsx create mode 100644 inertia/components/ui/avatar.tsx create mode 100644 inertia/components/ui/button.tsx create mode 100644 inertia/components/ui/confirm-dialog.tsx create mode 100644 inertia/components/ui/empty-state.tsx create mode 100644 inertia/components/ui/field.tsx create mode 100644 inertia/components/ui/markdown-editor.tsx create mode 100644 inertia/components/ui/menu.tsx create mode 100644 inertia/components/ui/page-header.tsx create mode 100644 inertia/components/ui/pagination.tsx create mode 100644 inertia/components/ui/prose.tsx create mode 100644 inertia/components/ui/section-heading.tsx create mode 100644 inertia/components/ui/tag.tsx create mode 100644 inertia/components/ui/time-ago.tsx create mode 100644 inertia/layouts/auth.tsx create mode 100644 inertia/lib/format.ts create mode 100644 inertia/lib/http.ts create mode 100644 inertia/types.ts create mode 100644 providers/api_provider.ts create mode 100644 public/favicon.svg create mode 100644 start/limiter.ts create mode 100644 start/routes/admin.ts create mode 100644 start/routes/articles.ts create mode 100644 start/routes/discussions.ts create mode 100644 start/routes/forum.ts create mode 100644 start/routes/members.ts create mode 100644 start/validator.ts create mode 100644 tmp/.gitkeep create mode 100644 tsconfig.inertia.json diff --git a/.adonisjs/client/data.d.ts b/.adonisjs/client/data.d.ts new file mode 100644 index 0000000..d219b63 --- /dev/null +++ b/.adonisjs/client/data.d.ts @@ -0,0 +1,49 @@ +/** + * 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 ReplyTransformer from '#transformers/reply_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 Reply = InferData + export namespace Reply { + 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..e31d39f --- /dev/null +++ b/.adonisjs/client/registry/index.ts @@ -0,0 +1,113 @@ +/* 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'], + }, + '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'], + }, +} 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..ebf4079 --- /dev/null +++ b/.adonisjs/client/registry/schema.d.ts @@ -0,0 +1,190 @@ +/* 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>> + } + } + '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>> + } + } +} diff --git a/.adonisjs/client/registry/tree.d.ts b/.adonisjs/client/registry/tree.d.ts new file mode 100644 index 0000000..c810ef8 --- /dev/null +++ b/.adonisjs/client/registry/tree.d.ts @@ -0,0 +1,31 @@ +/* eslint-disable prettier/prettier */ +import type { routes } from './index.ts' + +export interface ApiDefinition { + home: typeof routes['home'] + 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'] + } +} diff --git a/.adonisjs/server/controllers.ts b/.adonisjs/server/controllers.ts new file mode 100644 index 0000000..5ddd48c --- /dev/null +++ b/.adonisjs/server/controllers.ts @@ -0,0 +1,18 @@ +/** + * This file is automatically generated. + * DO NOT EDIT manually + */ + +export const controllers = { + Articles: () => import('#controllers/articles_controller'), + auth: { + Github: () => import('#controllers/auth/github_controller'), + Login: () => import('#controllers/auth/login_controller'), + Register: () => import('#controllers/auth/register_controller'), + }, + Home: () => import('#controllers/home_controller'), + Markdown: () => import('#controllers/markdown_controller'), + Profile: () => import('#controllers/profile_controller'), + Replies: () => import('#controllers/replies_controller'), + Seo: () => import('#controllers/seo_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..e312271 --- /dev/null +++ b/.adonisjs/server/pages.d.ts @@ -0,0 +1,26 @@ +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 { + 'articles/[slug]': ExtractProps<(typeof import('../../inertia/pages/articles/[slug].tsx'))['default']> + 'articles/create': ExtractProps<(typeof import('../../inertia/pages/articles/create.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']> + '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']> + 'home': ExtractProps<(typeof import('../../inertia/pages/home.tsx'))['default']> + 'profile/show': ExtractProps<(typeof import('../../inertia/pages/profile/show.tsx'))['default']> + } +} diff --git a/.adonisjs/server/routes.d.ts b/.adonisjs/server/routes.d.ts new file mode 100644 index 0000000..0b9e3c9 --- /dev/null +++ b/.adonisjs/server/routes.d.ts @@ -0,0 +1,59 @@ +import '@adonisjs/core/types/http' + +type ParamValue = string | number | bigint | boolean + +export type ScannedRoutes = { + ALL: { + 'home': { 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?: {} } + } + GET: { + 'home': { 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?: {} } + } + HEAD: { + 'home': { 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?: {} } + } + POST: { + 'login.store': { paramsTuple?: []; params?: {} } + 'register.store': { paramsTuple?: []; params?: {} } + 'logout': { paramsTuple?: []; params?: {} } + 'markdown.preview': { paramsTuple?: []; params?: {} } + 'replies.like': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + } + PUT: { + 'replies.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} } + } + DELETE: { + 'replies.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/.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/.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..8e91c7d --- /dev/null +++ b/.prettierignore @@ -0,0 +1,3 @@ +.adonisjs +node_modules +build 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..845922e 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,15 +88,20 @@ 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, }, + { + files: ['tests/browser/**/*.spec.{ts,js}'], + name: 'browser', + timeout: 300000, + }, ], forceExit: false, }, @@ -96,8 +126,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/auth/github_controller.ts b/app/controllers/auth/github_controller.ts index 4a4d0bc..e9591db 100644 --- a/app/controllers/auth/github_controller.ts +++ b/app/controllers/auth/github_controller.ts @@ -1,62 +1,84 @@ -import { HttpContext } from '@adonisjs/core/http' +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. + user = await User.findBy('email', profile.email.toLowerCase()) + if (user) { + user.githubId = profile.id + user.githubUsername = profile.login + user.avatarUrl = user.avatarUrl ?? profile.avatarUrl + await user.save() + } + } + + 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', + }) + session.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`) + } else { + session.flash('success', `Bon retour, ${user.displayName} !`) } - /** - * GitHub responded with some error - */ - if (github.hasError()) { + 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) + 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..d867089 100644 --- a/app/controllers/auth/login_controller.ts +++ b/app/controllers/auth/login_controller.ts @@ -1,39 +1,40 @@ -import { loginValidator } from '#validators/login_validator' -import { HttpContext } from '@adonisjs/core/http' 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.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..4134f45 100644 --- a/app/controllers/auth/register_controller.ts +++ b/app/controllers/auth/register_controller.ts @@ -1,18 +1,18 @@ -import { HttpContext } from '@adonisjs/core/http' 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.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`) + return response.redirect().toPath('/dashboard') } } 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/replies_controller.ts b/app/controllers/replies_controller.ts new file mode 100644 index 0000000..b44da3c --- /dev/null +++ b/app/controllers/replies_controller.ts @@ -0,0 +1,46 @@ +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 (!auth.user!.canManage(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 (!auth.user!.canManage(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) await Like.create({ userId: auth.user!.id, replyId: reply.id }) + return response.redirect().back() + } +} diff --git a/app/controllers/seo_controller.ts b/app/controllers/seo_controller.ts new file mode 100644 index 0000000..1845b62 --- /dev/null +++ b/app/controllers/seo_controller.ts @@ -0,0 +1,113 @@ +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/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/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..a42efee --- /dev/null +++ b/app/middleware/inertia_middleware.ts @@ -0,0 +1,67 @@ +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' + +export type ThemePreference = 'light' | 'dark' | 'system' + +export default class InertiaMiddleware extends BaseInertiaMiddleware { + 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' + + /** + * 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') }), + } + } + + 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/silent_auth_middleware.ts b/app/middleware/silent_auth_middleware.ts index 869411a..3e46f40 100644 --- a/app/middleware/silent_auth_middleware.ts +++ b/app/middleware/silent_auth_middleware.ts @@ -9,7 +9,6 @@ import type { NextFn } from '@adonisjs/core/types/http' */ export default class SilentAuthMiddleware { async handle(ctx: HttpContext, next: NextFn) { - // Check authentication without redirecting await ctx.auth.check() 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/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/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..9b580ce 100644 --- a/app/models/user.ts +++ b/app/models/user.ts @@ -1,77 +1,62 @@ -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 - - @column() - declare twitterId: string | null + @hasMany(() => Article) + declare articles: HasMany - @column() - declare isAdmin: boolean + @hasMany(() => Thread) + declare threads: HasMany - @column() - declare isSponsor: boolean + @hasMany(() => Discussion) + declare discussions: HasMany - @column.dateTime() - declare emailVerifiedAt: DateTime | null + @hasMany(() => Reply) + declare replies: HasMany - @column() - declare rememberMeToken: string | null + get displayName() { + return this.name || this.username + } - @column.dateTime({ autoCreate: true }) - declare createdAt: DateTime + 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, autoUpdate: true }) - declare updatedAt: DateTime + get isAdmin() { + return this.role === 'admin' + } - @hasMany(() => Article) - declare articles: HasMany + get isModerator() { + return this.role === 'admin' || this.role === 'moderator' + } - static rememberMeTokens = DbRememberMeTokensProvider.forModel(User) + get isBanned() { + return this.bannedAt !== null + } /** - * Serialize the model for Inertia + * Whether the user can edit/delete a piece of content owned by "ownerId". */ - serialize() { - return { - id: this.id, - username: this.username, - name: this.name, - email: this.email, - avatar: this.avatar, - isAdmin: this.isAdmin, - isSponsor: this.isSponsor, - } + canManage(ownerId: number) { + return this.id === ownerId || this.isModerator } } 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..e2d1d9f --- /dev/null +++ b/app/services/markdown.ts @@ -0,0 +1,106 @@ +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). + */ +export async function renderMarkdown(source: string): Promise { + const file = await getProcessor().process(source) + return String(file) +} + +/** + * Estimated reading time in minutes (~220 words per minute). + */ +export function readingMinutes(source: string): number { + const words = source + .replace(/```[\s\S]*?```/g, ' ') + .split(/\s+/) + .filter(Boolean).length + return Math.max(1, Math.round(words / 220)) +} + +/** + * Plain-text excerpt from markdown, used for meta descriptions and + * listings when the author did not write one. + */ +export function plainExcerpt(source: string, length = 180): string { + const text = source + .replace(/```[\s\S]*?```/g, ' ') + .replace(/`([^`]*)`/g, '$1') + .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ') + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/^#{1,6}\s+/gm, '') + .replace(/[*_~>#-]+/g, ' ') + .replace(/\s+/g, ' ') + .trim() + return text.length > length ? `${text.slice(0, length - 1).trimEnd()}…` : text +} diff --git a/app/services/reply_service.ts b/app/services/reply_service.ts new file mode 100644 index 0000000..5523a0d --- /dev/null +++ b/app/services/reply_service.ts @@ -0,0 +1,96 @@ +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' + +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) { + return 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 = await renderMarkdown(body) + 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 + }) +} + +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) => { + reply.useTransaction(trx) + await reply.delete() + if (reply.threadId) { + await trx.from('threads').where('id', reply.threadId).where('replies_count', '>', 0).decrement('replies_count', 1) + } else if (reply.discussionId) { + await trx.from('discussions').where('id', reply.discussionId).where('replies_count', '>', 0).decrement('replies_count', 1) + } + }) +} + +/** + * Query modifier: preload author, count likes and flag the viewer's likes. + * Usage: Reply.query().where('thread_id', id).apply(withReplyMeta(user)) + * 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/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..1cfa940 --- /dev/null +++ b/app/transformers/discussion_transformer.ts @@ -0,0 +1,39 @@ +import type Discussion from '#models/discussion' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' +import TagTransformer from '#transformers/tag_transformer' + +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)), + } + } + + forDetail() { + return { + ...this.toObject(), + bodyHtml: this.resource.bodyHtml, + } + } + + forEdit() { + return { + ...this.toObject(), + body: this.resource.body, + } + } +} 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/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..36cb71d --- /dev/null +++ b/app/transformers/thread_transformer.ts @@ -0,0 +1,42 @@ +import type Thread from '#models/thread' +import { BaseTransformer } from '@adonisjs/core/transformers' +import UserTransformer from '#transformers/user_transformer' +import ChannelTransformer from '#transformers/channel_transformer' + +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)), + } + } + + forDetail() { + return { + ...this.toObject(), + bodyHtml: this.resource.bodyHtml, + } + } + + 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..ad76d28 --- /dev/null +++ b/app/transformers/user_transformer.ts @@ -0,0 +1,46 @@ +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, + } + } +} 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..250e14e 100644 --- a/app/validators/register_validator.ts +++ b/app/validators/register_validator.ts @@ -1,13 +1,43 @@ 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/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/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..69e767d 100644 --- a/config/app.ts +++ b/config/app.ts @@ -1,22 +1,29 @@ import env from '#start/env' import app from '@adonisjs/core/services/app' -import { Secret } from '@adonisjs/core/helpers' 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 +32,57 @@ export const http = defineConfig({ */ useAsyncLocalStorage: false, + 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..7e836e6 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,28 @@ const bodyParserConfig = defineConfig({ */ multipart: { /** - * Enabling auto process allows bodyparser middleware to - * move all uploaded files inside the tmp folder of your - * operating system + * Automatically process uploaded files into the system tmp directory. */ autoProcess: true, + + /** + * Normalize empty string values to null. + */ 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..cc34262 100644 --- a/config/session.ts +++ b/config/session.ts @@ -3,7 +3,14 @@ import app from '@adonisjs/core/services/app' import { defineConfig, stores } from '@adonisjs/session' const sessionConfig = defineConfig({ + /** + * Enable or disable session support globally. + */ enabled: true, + + /** + * Cookie name storing the session identifier. + */ cookieName: 'adonis-session', /** @@ -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..37067c6 100644 --- a/config/shield.ts +++ b/config/shield.ts @@ -3,47 +3,91 @@ import { defineConfig } from '@adonisjs/shield' const shieldConfig = defineConfig({ /** * Configure CSP policies for your app. Refer documentation - * to learn more + * to learn more. */ csp: { + /** + * Enable the Content-Security-Policy header. + */ enabled: false, + + /** + * Per-resource CSP directives. + */ directives: {}, + + /** + * Report violations without blocking resources. + */ 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/migrations/1736839410875_create_users_table.ts b/database/migrations/1736839410875_create_users_table.ts index d318ef8..2438df3 100644 --- a/database/migrations/1736839410875_create_users_table.ts +++ b/database/migrations/1736839410875_create_users_table.ts @@ -5,18 +5,25 @@ export default class extends BaseSchema { async up() { this.schema.createTable(this.tableName, (table) => { - table.increments('id').primary() - table.string('username').unique().notNullable() - table.string('name').nullable() - table.string('email').unique().notNullable() - table.string('password').notNullable() - table.string('avatar').nullable() - table.string('github_id').unique().nullable() - table.string('twitter_id').unique().nullable() - table.boolean('is_admin').defaultTo(false) - table.boolean('is_sponsor').defaultTo(false) - table.timestamp('email_verified_at').nullable() - table.timestamps(true, true) + table.increments('id').notNullable() + table.string('username', 40).notNullable().unique() + table.string('name', 120).nullable() + table.string('email', 254).notNullable().unique() + table.string('password').nullable() + table.string('avatar_url', 500).nullable() + table.string('bio', 280).nullable() + table.string('location', 100).nullable() + table.string('website_url', 255).nullable() + table.string('github_username', 40).nullable() + table.string('twitter_username', 40).nullable() + table.string('linkedin_username', 100).nullable() + table.string('github_id', 40).nullable().unique() + table.string('role', 20).notNullable().defaultTo('member') + table.timestamp('banned_at', { useTz: true }).nullable() + table.timestamp('email_verified_at', { useTz: true }).nullable() + + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).nullable() }) } diff --git a/database/migrations/1740725627468_create_remember_me_tokens_table.ts b/database/migrations/1736839410900_create_remember_me_tokens_table.ts similarity index 72% rename from database/migrations/1740725627468_create_remember_me_tokens_table.ts rename to database/migrations/1736839410900_create_remember_me_tokens_table.ts index 6ddbe77..59f556c 100644 --- a/database/migrations/1740725627468_create_remember_me_tokens_table.ts +++ b/database/migrations/1736839410900_create_remember_me_tokens_table.ts @@ -15,9 +15,9 @@ export default class extends BaseSchema { .onDelete('CASCADE') table.string('hash').notNullable().unique() - table.timestamp('created_at').notNullable() - table.timestamp('updated_at').notNullable() - table.timestamp('expires_at').notNullable() + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).notNullable() + table.timestamp('expires_at', { useTz: true }).notNullable() }) } diff --git a/database/migrations/1736839410950_create_articles_table.ts b/database/migrations/1736839410950_create_articles_table.ts new file mode 100644 index 0000000..8f5ecd0 --- /dev/null +++ b/database/migrations/1736839410950_create_articles_table.ts @@ -0,0 +1,37 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'articles' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id').notNullable() + table + .integer('user_id') + .notNullable() + .unsigned() + .references('id') + .inTable('users') + .onDelete('CASCADE') + table.string('title', 160).notNullable() + table.string('slug', 200).notNullable().unique() + table.string('excerpt', 300).nullable() + table.text('body').notNullable() + table.text('body_html').notNullable() + table.string('cover_url', 500).nullable() + table.smallint('reading_minutes').notNullable().defaultTo(1) + table.integer('views_count').notNullable().defaultTo(0) + table.timestamp('published_at', { useTz: true }).nullable().index() + table.timestamp('featured_at', { useTz: true }).nullable() + + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).nullable() + + table.index(['user_id']) + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/17368394109899_create_articles_table.ts b/database/migrations/17368394109899_create_articles_table.ts deleted file mode 100644 index ce3cae4..0000000 --- a/database/migrations/17368394109899_create_articles_table.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BaseSchema } from '@adonisjs/lucid/schema' - -export default class extends BaseSchema { - protected tableName = 'articles' - - async up() { - this.schema.createTable(this.tableName, (table) => { - table.increments('id') - table.string('title').notNullable() - table.string('slug').unique().notNullable() - table.text('excerpt').notNullable() - table.text('content').notNullable() - table.integer('user_id').unsigned().references('id').inTable('users').onDelete('CASCADE') - table.boolean('is_published').defaultTo(false) - table.timestamp('published_at').nullable() - table.timestamps(true, true) - }) - } - - async down() { - this.schema.dropTable(this.tableName) - } -} diff --git a/database/migrations/1760000000100_create_tags_table.ts b/database/migrations/1760000000100_create_tags_table.ts new file mode 100644 index 0000000..99585a0 --- /dev/null +++ b/database/migrations/1760000000100_create_tags_table.ts @@ -0,0 +1,21 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'tags' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id').notNullable() + table.string('name', 40).notNullable() + table.string('slug', 50).notNullable().unique() + table.string('description', 255).nullable() + + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).nullable() + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1760000000110_create_article_tag_table.ts b/database/migrations/1760000000110_create_article_tag_table.ts new file mode 100644 index 0000000..8d719a4 --- /dev/null +++ b/database/migrations/1760000000110_create_article_tag_table.ts @@ -0,0 +1,30 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'article_tag' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table + .integer('article_id') + .notNullable() + .unsigned() + .references('id') + .inTable('articles') + .onDelete('CASCADE') + table + .integer('tag_id') + .notNullable() + .unsigned() + .references('id') + .inTable('tags') + .onDelete('CASCADE') + table.primary(['article_id', 'tag_id']) + table.index(['tag_id']) + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1760000000200_create_channels_table.ts b/database/migrations/1760000000200_create_channels_table.ts new file mode 100644 index 0000000..3cb9e2d --- /dev/null +++ b/database/migrations/1760000000200_create_channels_table.ts @@ -0,0 +1,22 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'channels' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id').notNullable() + table.string('name', 60).notNullable() + table.string('slug', 70).notNullable().unique() + table.string('description', 255).nullable() + table.smallint('position').notNullable().defaultTo(0) + + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).nullable() + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1760000000210_create_threads_table.ts b/database/migrations/1760000000210_create_threads_table.ts new file mode 100644 index 0000000..95541d6 --- /dev/null +++ b/database/migrations/1760000000210_create_threads_table.ts @@ -0,0 +1,44 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'threads' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id').notNullable() + table + .integer('user_id') + .notNullable() + .unsigned() + .references('id') + .inTable('users') + .onDelete('CASCADE') + table + .integer('channel_id') + .notNullable() + .unsigned() + .references('id') + .inTable('channels') + .onDelete('CASCADE') + table.string('title', 160).notNullable() + table.string('slug', 200).notNullable().unique() + table.text('body').notNullable() + table.text('body_html').notNullable() + table.integer('views_count').notNullable().defaultTo(0) + table.integer('replies_count').notNullable().defaultTo(0) + table.timestamp('pinned_at', { useTz: true }).nullable() + table.timestamp('locked_at', { useTz: true }).nullable() + table.timestamp('last_activity_at', { useTz: true }).notNullable().index() + + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).nullable() + + table.index(['user_id']) + table.index(['channel_id']) + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1760000000300_create_discussions_table.ts b/database/migrations/1760000000300_create_discussions_table.ts new file mode 100644 index 0000000..74f189d --- /dev/null +++ b/database/migrations/1760000000300_create_discussions_table.ts @@ -0,0 +1,36 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'discussions' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id').notNullable() + table + .integer('user_id') + .notNullable() + .unsigned() + .references('id') + .inTable('users') + .onDelete('CASCADE') + table.string('title', 160).notNullable() + table.string('slug', 200).notNullable().unique() + table.text('body').notNullable() + table.text('body_html').notNullable() + table.integer('views_count').notNullable().defaultTo(0) + table.integer('replies_count').notNullable().defaultTo(0) + table.timestamp('pinned_at', { useTz: true }).nullable() + table.timestamp('locked_at', { useTz: true }).nullable() + table.timestamp('last_activity_at', { useTz: true }).notNullable().index() + + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).nullable() + + table.index(['user_id']) + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1760000000310_create_discussion_tag_table.ts b/database/migrations/1760000000310_create_discussion_tag_table.ts new file mode 100644 index 0000000..bac0163 --- /dev/null +++ b/database/migrations/1760000000310_create_discussion_tag_table.ts @@ -0,0 +1,30 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'discussion_tag' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table + .integer('discussion_id') + .notNullable() + .unsigned() + .references('id') + .inTable('discussions') + .onDelete('CASCADE') + table + .integer('tag_id') + .notNullable() + .unsigned() + .references('id') + .inTable('tags') + .onDelete('CASCADE') + table.primary(['discussion_id', 'tag_id']) + table.index(['tag_id']) + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1760000000400_create_replies_table.ts b/database/migrations/1760000000400_create_replies_table.ts new file mode 100644 index 0000000..cde71cd --- /dev/null +++ b/database/migrations/1760000000400_create_replies_table.ts @@ -0,0 +1,62 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +/** + * A reply belongs to exactly one parent: a forum thread, a discussion + * or an article (comments). Using one nullable FK per parent keeps real + * foreign keys (with cascade) and plain hasMany relations in Lucid. + */ +export default class extends BaseSchema { + protected tableName = 'replies' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id').notNullable() + table + .integer('user_id') + .notNullable() + .unsigned() + .references('id') + .inTable('users') + .onDelete('CASCADE') + table + .integer('thread_id') + .nullable() + .unsigned() + .references('id') + .inTable('threads') + .onDelete('CASCADE') + table + .integer('discussion_id') + .nullable() + .unsigned() + .references('id') + .inTable('discussions') + .onDelete('CASCADE') + table + .integer('article_id') + .nullable() + .unsigned() + .references('id') + .inTable('articles') + .onDelete('CASCADE') + table.text('body').notNullable() + table.text('body_html').notNullable() + + table.timestamp('created_at', { useTz: true }).notNullable() + table.timestamp('updated_at', { useTz: true }).nullable() + + table.index(['thread_id']) + table.index(['discussion_id']) + table.index(['article_id']) + table.index(['user_id']) + }) + + this.schema.raw( + 'ALTER TABLE replies ADD CONSTRAINT replies_single_parent CHECK (num_nonnulls(thread_id, discussion_id, article_id) = 1)' + ) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1736839410999_add_author_id_to_articles.ts b/database/migrations/1760000000410_add_solution_reply_to_threads.ts similarity index 51% rename from database/migrations/1736839410999_add_author_id_to_articles.ts rename to database/migrations/1760000000410_add_solution_reply_to_threads.ts index 6ee3326..81ae5e3 100644 --- a/database/migrations/1736839410999_add_author_id_to_articles.ts +++ b/database/migrations/1760000000410_add_solution_reply_to_threads.ts @@ -1,17 +1,23 @@ import { BaseSchema } from '@adonisjs/lucid/schema' export default class extends BaseSchema { - protected tableName = 'articles' + protected tableName = 'threads' async up() { this.schema.alterTable(this.tableName, (table) => { - table.integer('author_id').unsigned().references('id').inTable('users').onDelete('CASCADE') + table + .integer('solution_reply_id') + .nullable() + .unsigned() + .references('id') + .inTable('replies') + .onDelete('SET NULL') }) } async down() { this.schema.alterTable(this.tableName, (table) => { - table.dropColumn('author_id') + table.dropColumn('solution_reply_id') }) } } diff --git a/database/migrations/1760000000500_create_likes_table.ts b/database/migrations/1760000000500_create_likes_table.ts new file mode 100644 index 0000000..ca68f67 --- /dev/null +++ b/database/migrations/1760000000500_create_likes_table.ts @@ -0,0 +1,47 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'likes' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.increments('id').notNullable() + table + .integer('user_id') + .notNullable() + .unsigned() + .references('id') + .inTable('users') + .onDelete('CASCADE') + table + .integer('article_id') + .nullable() + .unsigned() + .references('id') + .inTable('articles') + .onDelete('CASCADE') + table + .integer('reply_id') + .nullable() + .unsigned() + .references('id') + .inTable('replies') + .onDelete('CASCADE') + + table.timestamp('created_at', { useTz: true }).notNullable() + + table.unique(['user_id', 'article_id']) + table.unique(['user_id', 'reply_id']) + table.index(['article_id']) + table.index(['reply_id']) + }) + + this.schema.raw( + 'ALTER TABLE likes ADD CONSTRAINT likes_single_target CHECK (num_nonnulls(article_id, reply_id) = 1)' + ) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/migrations/1760000000600_create_rate_limits_table.ts b/database/migrations/1760000000600_create_rate_limits_table.ts new file mode 100644 index 0000000..3baffd1 --- /dev/null +++ b/database/migrations/1760000000600_create_rate_limits_table.ts @@ -0,0 +1,17 @@ +import { BaseSchema } from '@adonisjs/lucid/schema' + +export default class extends BaseSchema { + protected tableName = 'rate_limits' + + async up() { + this.schema.createTable(this.tableName, (table) => { + table.string('key', 255).notNullable().primary() + table.integer('points', 9).notNullable().defaultTo(0) + table.bigint('expire').unsigned() + }) + } + + async down() { + this.schema.dropTable(this.tableName) + } +} diff --git a/database/schema.ts b/database/schema.ts new file mode 100644 index 0000000..0fd082b --- /dev/null +++ b/database/schema.ts @@ -0,0 +1,268 @@ +/** + * This file is automatically generated + * DO NOT EDIT manually + * Run "node ace migration:run" command to re-generate this file + */ + +import { BaseModel, column } from '@adonisjs/lucid/orm' +import { DateTime } from 'luxon' + +export class ArticleTagSchema extends BaseModel { + static $columns = ['articleId', 'tagId'] as const + $columns = ArticleTagSchema.$columns + @column({ isPrimary: true }) + declare articleId: number + @column() + declare tagId: number +} + +export class ArticleSchema extends BaseModel { + static $columns = ['body', 'bodyHtml', 'coverUrl', 'createdAt', 'excerpt', 'featuredAt', 'id', 'publishedAt', 'readingMinutes', 'slug', 'title', 'updatedAt', 'userId', 'viewsCount'] as const + $columns = ArticleSchema.$columns + @column() + declare body: string + @column() + declare bodyHtml: string + @column() + declare coverUrl: string | null + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column() + declare excerpt: string | null + @column.dateTime() + declare featuredAt: DateTime | null + @column({ isPrimary: true }) + declare id: number + @column.dateTime() + declare publishedAt: DateTime | null + @column() + declare readingMinutes: number + @column() + declare slug: string + @column() + declare title: string + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime | null + @column() + declare userId: number + @column() + declare viewsCount: number +} + +export class ChannelSchema extends BaseModel { + static $columns = ['createdAt', 'description', 'id', 'name', 'position', 'slug', 'updatedAt'] as const + $columns = ChannelSchema.$columns + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column() + declare description: string | null + @column({ isPrimary: true }) + declare id: number + @column() + declare name: string + @column() + declare position: number + @column() + declare slug: string + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime | null +} + +export class DiscussionTagSchema extends BaseModel { + static $columns = ['discussionId', 'tagId'] as const + $columns = DiscussionTagSchema.$columns + @column({ isPrimary: true }) + declare discussionId: number + @column() + declare tagId: number +} + +export class DiscussionSchema extends BaseModel { + static $columns = ['body', 'bodyHtml', 'createdAt', 'id', 'lastActivityAt', 'lockedAt', 'pinnedAt', 'repliesCount', 'slug', 'title', 'updatedAt', 'userId', 'viewsCount'] as const + $columns = DiscussionSchema.$columns + @column() + declare body: string + @column() + declare bodyHtml: string + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column({ isPrimary: true }) + declare id: number + @column.dateTime() + declare lastActivityAt: DateTime + @column.dateTime() + declare lockedAt: DateTime | null + @column.dateTime() + declare pinnedAt: DateTime | null + @column() + declare repliesCount: number + @column() + declare slug: string + @column() + declare title: string + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime | null + @column() + declare userId: number + @column() + declare viewsCount: number +} + +export class LikeSchema extends BaseModel { + static $columns = ['articleId', 'createdAt', 'id', 'replyId', 'userId'] as const + $columns = LikeSchema.$columns + @column() + declare articleId: number | null + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column({ isPrimary: true }) + declare id: number + @column() + declare replyId: number | null + @column() + declare userId: number +} + +export class RateLimitSchema extends BaseModel { + static $columns = ['expire', 'key', 'points'] as const + $columns = RateLimitSchema.$columns + @column() + declare expire: bigint | number | null + @column({ isPrimary: true }) + declare key: string + @column() + declare points: number +} + +export class RememberMeTokenSchema extends BaseModel { + static $columns = ['createdAt', 'expiresAt', 'hash', 'id', 'tokenableId', 'updatedAt'] as const + $columns = RememberMeTokenSchema.$columns + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column.dateTime() + declare expiresAt: DateTime + @column() + declare hash: string + @column({ isPrimary: true }) + declare id: number + @column() + declare tokenableId: number + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime +} + +export class ReplySchema extends BaseModel { + static $columns = ['articleId', 'body', 'bodyHtml', 'createdAt', 'discussionId', 'id', 'threadId', 'updatedAt', 'userId'] as const + $columns = ReplySchema.$columns + @column() + declare articleId: number | null + @column() + declare body: string + @column() + declare bodyHtml: string + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column() + declare discussionId: number | null + @column({ isPrimary: true }) + declare id: number + @column() + declare threadId: number | null + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime | null + @column() + declare userId: number +} + +export class TagSchema extends BaseModel { + static $columns = ['createdAt', 'description', 'id', 'name', 'slug', 'updatedAt'] as const + $columns = TagSchema.$columns + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column() + declare description: string | null + @column({ isPrimary: true }) + declare id: number + @column() + declare name: string + @column() + declare slug: string + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime | null +} + +export class ThreadSchema extends BaseModel { + static $columns = ['body', 'bodyHtml', 'channelId', 'createdAt', 'id', 'lastActivityAt', 'lockedAt', 'pinnedAt', 'repliesCount', 'slug', 'solutionReplyId', 'title', 'updatedAt', 'userId', 'viewsCount'] as const + $columns = ThreadSchema.$columns + @column() + declare body: string + @column() + declare bodyHtml: string + @column() + declare channelId: number + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column({ isPrimary: true }) + declare id: number + @column.dateTime() + declare lastActivityAt: DateTime + @column.dateTime() + declare lockedAt: DateTime | null + @column.dateTime() + declare pinnedAt: DateTime | null + @column() + declare repliesCount: number + @column() + declare slug: string + @column() + declare solutionReplyId: number | null + @column() + declare title: string + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime | null + @column() + declare userId: number + @column() + declare viewsCount: number +} + +export class UserSchema extends BaseModel { + static $columns = ['avatarUrl', 'bannedAt', 'bio', 'createdAt', 'email', 'emailVerifiedAt', 'githubId', 'githubUsername', 'id', 'linkedinUsername', 'location', 'name', 'password', 'role', 'twitterUsername', 'updatedAt', 'username', 'websiteUrl'] as const + $columns = UserSchema.$columns + @column() + declare avatarUrl: string | null + @column.dateTime() + declare bannedAt: DateTime | null + @column() + declare bio: string | null + @column.dateTime({ autoCreate: true }) + declare createdAt: DateTime + @column() + declare email: string + @column.dateTime() + declare emailVerifiedAt: DateTime | null + @column() + declare githubId: string | null + @column() + declare githubUsername: string | null + @column({ isPrimary: true }) + declare id: number + @column() + declare linkedinUsername: string | null + @column() + declare location: string | null + @column() + declare name: string | null + @column({ serializeAs: null }) + declare password: string | null + @column() + declare role: 'member' | 'moderator' | 'admin' + @column() + declare twitterUsername: string | null + @column.dateTime({ autoCreate: true, autoUpdate: true }) + declare updatedAt: DateTime | null + @column() + declare username: string + @column() + declare websiteUrl: string | null +} diff --git a/database/schema_rules.ts b/database/schema_rules.ts new file mode 100644 index 0000000..195eddf --- /dev/null +++ b/database/schema_rules.ts @@ -0,0 +1,14 @@ +import { type SchemaRules } from '@adonisjs/lucid/types/schema_generator' + +export default { + tables: { + users: { + columns: { + role: { + tsType: `'member' | 'moderator' | 'admin'`, + decorators: [{ name: '@column' }], + }, + }, + }, + }, +} satisfies SchemaRules diff --git a/database/seeders/01_base_seeder.ts b/database/seeders/01_base_seeder.ts new file mode 100644 index 0000000..4ca19c7 --- /dev/null +++ b/database/seeders/01_base_seeder.ts @@ -0,0 +1,56 @@ +import { BaseSeeder } from '@adonisjs/lucid/seeders' +import Channel from '#models/channel' +import Tag from '#models/tag' + +/** + * Structural data required in every environment: forum channels and tags. + * Idempotent (safe to run on every deploy). + */ +export default class BaseSeeder_ extends BaseSeeder { + static environment = ['development', 'production', 'test'] + + async run() { + await Channel.updateOrCreateMany('slug', [ + { position: 1, slug: 'javascript', name: 'JavaScript', description: 'Le langage lui-même : syntaxe, asynchrone, DOM, ES2025 et au-delà.' }, + { position: 2, slug: 'typescript', name: 'TypeScript', description: 'Typage, génériques, configuration du compilateur, migration depuis JS.' }, + { position: 3, slug: 'react', name: 'React & Next.js', description: 'Composants, hooks, état, rendu serveur, Next.js et Remix.' }, + { position: 4, slug: 'vue', name: 'Vue & Nuxt', description: 'Vue 3, Composition API, Pinia, Nuxt.' }, + { position: 5, slug: 'angular', name: 'Angular', description: 'Composants, signals, RxJS, architecture des applications Angular.' }, + { position: 6, slug: 'backend', name: 'Node.js & Backend', description: 'Node, Bun, Deno, AdonisJS, NestJS, Express, bases de données et API.' }, + { position: 7, slug: 'mobile', name: 'Mobile', description: 'React Native, Expo, Ionic, PWA et intégrations mobile money.' }, + { position: 8, slug: 'outils', name: 'Outils & DevOps', description: 'Vite, tests, CI/CD, Docker, déploiement, hébergement.' }, + { position: 9, slug: 'debutants', name: 'Débutants', description: 'Premiers pas, ressources pour apprendre, questions sans honte.' }, + ]) + + const tags: [string, string][] = [ + ['javascript', 'JavaScript'], + ['typescript', 'TypeScript'], + ['react', 'React'], + ['nextjs', 'Next.js'], + ['vue', 'Vue'], + ['angular', 'Angular'], + ['svelte', 'Svelte'], + ['nodejs', 'Node.js'], + ['adonisjs', 'AdonisJS'], + ['nestjs', 'NestJS'], + ['bun', 'Bun'], + ['react-native', 'React Native'], + ['tailwindcss', 'Tailwind CSS'], + ['tests', 'Tests'], + ['performance', 'Performance'], + ['securite', 'Sécurité'], + ['devops', 'DevOps'], + ['mobile-money', 'Mobile Money'], + ['ia', 'IA'], + ['carriere', 'Carrière'], + ['freelance', 'Freelance'], + ['evenements', 'Événements'], + ['open-source', 'Open source'], + ['apprendre', 'Apprendre'], + ] + await Tag.updateOrCreateMany( + 'slug', + tags.map(([slug, name]) => ({ slug, name })) + ) + } +} diff --git a/database/seeders/user_seeder.ts b/database/seeders/user_seeder.ts deleted file mode 100644 index cc2ecaa..0000000 --- a/database/seeders/user_seeder.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { BaseSeeder } from '@adonisjs/lucid/seeders' -import User from '#models/user' - -export default class UserSeeder extends BaseSeeder { - async run() { - // Create a test user - await User.create({ - username: 'testuser', - name: 'Test User', - email: 'test@example.com', - password: 'password123', - isAdmin: true, - isSponsor: false, - }) - - // You can add more test users if needed - await User.create({ - username: 'regularuser', - name: 'Regular User', - email: 'regular@example.com', - password: 'password123', - isAdmin: false, - isSponsor: false, - }) - - console.log('✅ Users seeded successfully') - } -} diff --git a/eslint.config.js b/eslint.config.js index 9be1be3..b7fd9c9 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -1,2 +1,4 @@ import { configApp } from '@adonisjs/eslint-config' -export default configApp() +import { react } from '@adonisjs/eslint-config/react' + +export default configApp(...react) diff --git a/inertia/app/app.tsx b/inertia/app/app.tsx index ddadb35..3dd59a3 100644 --- a/inertia/app/app.tsx +++ b/inertia/app/app.tsx @@ -1,23 +1,23 @@ -/// -/// - import '../css/app.css' +import { client } from '../client' import { hydrateRoot } from 'react-dom/client' +import { TuyauProvider } from '@adonisjs/inertia/react' import { createInertiaApp } from '@inertiajs/react' -import { resolvePageComponent } from '@adonisjs/inertia/helpers' - -const appName = import.meta.env.VITE_APP_NAME || 'AdonisJS' +import { resolvePage, pageTitle } from './resolve_page' createInertiaApp({ - progress: { color: '#5468FF' }, - - title: (title) => `${title} - ${appName}`, - - resolve: (name) => { - return resolvePageComponent(`../pages/${name}.tsx`, import.meta.glob('../pages/**/*.tsx')) - }, - + title: pageTitle, + resolve: (name) => resolvePage(name, import.meta.glob('../pages/**/*.tsx')), setup({ el, App, props }) { - hydrateRoot(el, ) + hydrateRoot( + el, + + + + ) + }, + progress: { + color: '#F7DF1E', + showSpinner: false, }, }) diff --git a/inertia/app/resolve_page.ts b/inertia/app/resolve_page.ts new file mode 100644 index 0000000..fdea664 --- /dev/null +++ b/inertia/app/resolve_page.ts @@ -0,0 +1,25 @@ +import type { ResolvedComponent } from '@inertiajs/react' +import { resolvePageComponent } from '@adonisjs/inertia/helpers' +import SiteLayout from '~/layouts/app' + +export const SITE_NAME = 'JavaScript Cameroun' + +export function pageTitle(title: string) { + return title ? `${title} — ${SITE_NAME}` : `${SITE_NAME} — la communauté des développeurs JavaScript du 237` +} + +/** + * Resolve a page component and apply the default site layout, unless the + * page declares its own `layout` (use `Page.layout = (page) => page` for none). + */ +export async function resolvePage(name: string, pages: Record) { + const module = await resolvePageComponent<{ default: ResolvedComponent }>( + `../pages/${name}.tsx`, + pages + ) + const component = module.default as ResolvedComponent & { layout?: unknown } + if (component.layout === undefined) { + component.layout = [SiteLayout] + } + return component +} diff --git a/inertia/app/ssr.tsx b/inertia/app/ssr.tsx index 56793e6..a5a99c6 100644 --- a/inertia/app/ssr.tsx +++ b/inertia/app/ssr.tsx @@ -1,14 +1,22 @@ +import { client } from '~/client' import ReactDOMServer from 'react-dom/server' +import { TuyauProvider } from '@adonisjs/inertia/react' import { createInertiaApp } from '@inertiajs/react' +import { resolvePage, pageTitle } from './resolve_page' export default function render(page: any) { return createInertiaApp({ page, + title: pageTitle, render: ReactDOMServer.renderToString, - resolve: (name) => { - const pages = import.meta.glob('../pages/**/*.tsx', { eager: true }) - return pages[`../pages/${name}.tsx`] + resolve: (name) => + resolvePage(name, import.meta.glob('../pages/**/*.tsx', { eager: true })), + setup: ({ App, props }) => { + return ( + + + + ) }, - setup: ({ App, props }) => , }) -} \ No newline at end of file +} diff --git a/inertia/client.ts b/inertia/client.ts new file mode 100644 index 0000000..ce7edb8 --- /dev/null +++ b/inertia/client.ts @@ -0,0 +1,9 @@ +import { registry } from '@generated/registry' +import { createTuyau } from '@tuyau/core/client' + +export const client = createTuyau({ + baseUrl: '/', + registry, +}) + +export const urlFor = client.urlFor diff --git a/inertia/components/articles-section.tsx b/inertia/components/articles-section.tsx index 3a8f5e7..a5405db 100644 --- a/inertia/components/articles-section.tsx +++ b/inertia/components/articles-section.tsx @@ -1,83 +1,47 @@ -import { Link } from '@inertiajs/react' +import type { Data } from '@generated/data' +import { ArticleFeature, ArticleRow } from '~/components/articles/list' +import { SectionHeading } from '~/components/ui/section-heading' +import { EmptyState } from '~/components/ui/empty-state' +import { ButtonLink } from '~/components/ui/button' -interface Article { - id: number - title: string - slug: string - excerpt: string - author: { - name: string - username: string - } - createdAt: string -} - -interface ArticlesSectionProps { - articles: Article[] -} +/** + * Home: lead story on the left, the next four as a numbered index. + */ +export default function ArticlesSection({ articles }: { articles: Data.Article[] }) { + const [lead, ...rest] = articles -export default function ArticlesSection({ articles }: ArticlesSectionProps) { return ( -
-
-
-

Articles Populaires

-

- Découvrez les articles les plus appréciés et partagés par les membres de la communauté -

-
- -
- {articles.map((article) => ( -
-
-
- -

{article.title}

-

{article.excerpt}

- -
-
-
- - {article.author.name} - - -
-
-

- - {article.author.name} - -

-
- -
-
-
-
-
- ))} -
- -
- - Voir tous les articles - +
+ + Ce qui s’écrit en ce moment. + + } + action={{ href: '/articles', label: 'Tous les articles' }} + /> + {lead ? ( +
+
+ +
+
+ {rest.map((article, i) => ( + + ))} +
-
-
+ ) : ( + Écrire le premier article} + /> + )} + ) } diff --git a/inertia/components/articles/create-form.tsx b/inertia/components/articles/create-form.tsx index 69cb270..a4313f0 100644 --- a/inertia/components/articles/create-form.tsx +++ b/inertia/components/articles/create-form.tsx @@ -1,199 +1,2 @@ -import { FormEvent, useState, Suspense, lazy } from 'react' -import { useForm } from '@inertiajs/react' -import { Switch } from '@headlessui/react' -import SlideOver from '../slide-over' - -const MDEditor = lazy(() => import('@uiw/react-md-editor')) - -interface CreateArticleFormProps { - isOpen: boolean - onClose: () => void -} - -export default function CreateArticleForm({ isOpen, onClose }: CreateArticleFormProps) { - const [isDraft, setIsDraft] = useState(true) - const { data, setData, post, processing, errors } = useForm({ - title: '', - canonicalUrl: '', - content: '', - excerpt: '', - tags: [], - language: 'fr', - coverImage: null as File | null, - }) - - function handleSubmit(e: FormEvent) { - e.preventDefault() - post('/articles', { - onSuccess: () => onClose(), - }) - } - - return ( - -
-
-
-
- - - -
-
-

- Soumettez votre article au site JavaScript.cm. Nous recherchons des articles de - haute qualité autour de JavaScript, Node.js, React, Next.js, Nest.js, AdonisJS, - Angular, Vue, CSS et autres sujets connexes. Les articles ne peuvent pas être de - nature promotionnelle et doivent être éducatifs et informatifs. -

-
-
-
- -
-
-
- - setData('title', e.target.value)} - className="mt-1 block w-full rounded-md border border-gray-300 px-3 py-2 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" - /> - {errors.title &&

{errors.title}

} -
- -
- -
- - -
-
-
- -
- -