Compare commits
98 Commits
7cb5ff487d
...
v0.1.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2450977e61
|
||
|
|
afc18b555a
|
||
|
|
9699127739
|
||
|
|
938d8bde7b
|
||
|
|
65c7096f46
|
||
|
|
57c00ad4d1
|
||
|
|
39618f7708
|
||
|
|
e84e4a5a9d
|
||
|
|
e74973a9d0
|
||
|
|
9233c1bf89
|
||
|
|
88c7f45a2c
|
||
|
|
9af72156f5
|
||
|
|
597a4d615e
|
||
|
|
2df45af305
|
||
|
|
863a4bf528
|
||
|
|
9a1cdb05a4
|
||
|
|
28caf92f9a
|
||
|
|
8b2728dc5a
|
||
|
|
3bbbbc307f
|
||
|
|
f080919563
|
||
|
|
edc1ab2438
|
||
|
|
01b66d6f2f
|
||
|
|
9a70dd02bb
|
||
|
|
e285a4e634
|
||
|
|
f247a01ac7
|
||
|
|
bb640cd8f9
|
||
|
|
c1118e9f25
|
||
|
|
eae1f84b92
|
||
|
|
8d27532dc0
|
||
|
|
f79507730e
|
||
|
|
7048c2731e
|
||
|
|
d74fd15036
|
||
|
|
86a697c392
|
||
|
|
38adbb6e77
|
||
| 594a387712 | |||
|
|
4ca15b578d
|
||
| 2912231769 | |||
|
|
db17994bb5
|
||
|
|
f57e028178
|
||
|
|
e84aa8a8db
|
||
|
|
c6b23de481
|
||
|
|
0611ef715c
|
||
|
|
0a1391674f
|
||
|
|
2fedaca502
|
||
|
|
a6837ff7fb
|
||
|
|
74b61004e7
|
||
|
|
760343da76
|
||
|
|
14f8b8b63d
|
||
|
|
50a186da1d
|
||
|
|
3908989b39
|
||
|
|
02d70f27ea
|
||
|
|
65f8860cc0
|
||
|
|
0e9edd4bfc
|
||
|
|
6ce58d1639
|
||
|
|
47d6fcb6a0
|
||
|
|
d7c2a965a0
|
||
|
|
fb7ddde42e
|
||
|
|
026aebaee3
|
||
|
|
a30113e8e2
|
||
| f10c444957 | |||
|
|
975e29dea1
|
||
|
|
a4ce48a91c
|
||
|
|
ff6fc1c6b3
|
||
|
|
5671ba60a6
|
||
|
|
5f2672021e
|
||
| 17c2cea366 | |||
| 5665fcd98f | |||
| cb6d87eafd | |||
| 48ebc7dc36 | |||
| dbfd14b57a | |||
| 570576435c | |||
| 7c3f4050c5 | |||
| c19d86a0cb | |||
| 6d2e1ead05 | |||
| 6756cf6bc7 | |||
| 6aaf53c90b | |||
| ccec39bfa0 | |||
| a06fdbf21e | |||
| de537e5947 | |||
|
|
0cb361afb8
|
||
| 9097a3e9b5 | |||
|
|
24eb99093c
|
||
|
|
75ac95cadb
|
||
|
|
35abd0496e
|
||
|
|
03e5915fcc
|
||
|
|
77ac960411
|
||
|
|
8425ffe4fc
|
||
|
|
b81835661c
|
||
|
|
fbc231dc9a
|
||
|
|
37a23390d5
|
||
|
|
bd9dd140ab
|
||
|
|
5b6e0143b6
|
||
|
|
214bf077e5
|
||
|
|
bb9ae058db
|
||
|
|
0b07320974
|
||
|
|
0c045e8d3c
|
||
|
|
8ffeaeba05
|
||
|
|
9e37272bff
|
42
.env.example
42
.env.example
@@ -8,32 +8,40 @@ BACKEND_PORT=3001
|
||||
FRONTEND_PORT=3000
|
||||
|
||||
# Database (PostgreSQL)
|
||||
POSTGRES_HOST=localhost
|
||||
POSTGRES_HOST=db
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_DB=memegoat
|
||||
POSTGRES_DB=app
|
||||
POSTGRES_USER=app
|
||||
POSTGRES_PASSWORD=app
|
||||
|
||||
# Storage (S3/MinIO) - À configurer lors de l'implémentation
|
||||
# S3_ENDPOINT=localhost
|
||||
# S3_PORT=9000
|
||||
# S3_ACCESS_KEY=
|
||||
# S3_SECRET_KEY=
|
||||
# S3_BUCKET=memegoat
|
||||
# Redis
|
||||
REDIS_HOST=redis
|
||||
REDIS_PORT=6379
|
||||
|
||||
# Security (PGP & Auth) - À configurer lors de l'implémentation
|
||||
# PGP_PASSPHRASE=
|
||||
JWT_SECRET=super-secret-key-change-me-in-production
|
||||
ENCRYPTION_KEY=another-super-secret-key-32-chars
|
||||
# Storage (S3/MinIO)
|
||||
S3_ENDPOINT=s3
|
||||
S3_PORT=9000
|
||||
S3_ACCESS_KEY=minioadmin
|
||||
S3_SECRET_KEY=minioadmin
|
||||
S3_BUCKET_NAME=memegoat
|
||||
|
||||
# Security
|
||||
JWT_SECRET=super-secret-jwt-key-change-me-in-prod
|
||||
ENCRYPTION_KEY=01234567890123456789012345678901
|
||||
PGP_ENCRYPTION_KEY=super-secret-pgp-key
|
||||
SESSION_PASSWORD=super-secret-session-password-32-chars
|
||||
|
||||
# Mail
|
||||
MAIL_HOST=localhost
|
||||
MAIL_HOST=mail
|
||||
MAIL_PORT=1025
|
||||
MAIL_SECURE=false
|
||||
MAIL_USER=user
|
||||
MAIL_PASS=password
|
||||
MAIL_FROM=noreply@memegoat.fr
|
||||
DOMAIN_NAME=memegoat.fr
|
||||
MAIL_USER=
|
||||
MAIL_PASS=
|
||||
MAIL_FROM=noreply@memegoat.local
|
||||
DOMAIN_NAME=localhost
|
||||
|
||||
ENABLE_CORS=false
|
||||
CORS_DOMAIN_NAME=localhost
|
||||
|
||||
# Media Limits (in KB)
|
||||
MAX_IMAGE_SIZE_KB=512
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
name: Backend Tests
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'backend/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'backend/**'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Run Backend Tests
|
||||
run: pnpm -F @memegoat/backend test
|
||||
111
.gitea/workflows/ci.yml
Normal file
111
.gitea/workflows/ci.yml
Normal file
@@ -0,0 +1,111 @@
|
||||
# Pipeline CI/CD pour Gitea Actions (Forgejo)
|
||||
# Compatible avec GitHub Actions pour la portabilité
|
||||
name: CI/CD Pipeline
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- '**'
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
validate:
|
||||
name: Valider ${{ matrix.component }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
component: [backend, frontend, documentation]
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Installer pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Configurer Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
- name: Obtenir le chemin du store pnpm
|
||||
id: pnpm-cache
|
||||
shell: bash
|
||||
run: |
|
||||
echo "STORE_PATH=$(pnpm store path --silent)" >> "${GITEA_OUTPUT:-$GITHUB_OUTPUT}"
|
||||
|
||||
- name: Configurer le cache pnpm
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
|
||||
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pnpm-store-
|
||||
|
||||
- name: Installer les dépendances
|
||||
run: pnpm install --frozen-lockfile --prefer-offline
|
||||
|
||||
- name: Lint ${{ matrix.component }}
|
||||
run: pnpm -F @memegoat/${{ matrix.component }} lint
|
||||
|
||||
- name: Tester ${{ matrix.component }}
|
||||
if: matrix.component == 'backend' || matrix.component == 'frontend'
|
||||
run: |
|
||||
if pnpm -F @memegoat/${{ matrix.component }} run | grep -q "test"; then
|
||||
pnpm -F @memegoat/${{ matrix.component }} test
|
||||
else
|
||||
echo "Pas de script de test trouvé pour ${{ matrix.component }}, passage."
|
||||
fi
|
||||
|
||||
- name: Build ${{ matrix.component }}
|
||||
run: pnpm -F @memegoat/${{ matrix.component }} build
|
||||
env:
|
||||
NEXT_PUBLIC_API_URL: ${{ secrets.NEXT_PUBLIC_API_URL }}
|
||||
|
||||
deploy:
|
||||
name: Déploiement en Production
|
||||
needs: validate
|
||||
# Déclenchement uniquement sur push sur main ou tag de version
|
||||
# Gitea supporte le contexte 'github' pour la compatibilité
|
||||
if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v'))
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Vérifier l'environnement Docker
|
||||
run: |
|
||||
docker version
|
||||
docker compose version
|
||||
|
||||
- name: Déployer avec Docker Compose
|
||||
run: |
|
||||
docker compose -f docker-compose.prod.yml up -d --build
|
||||
env:
|
||||
BACKEND_PORT: ${{ secrets.BACKEND_PORT }}
|
||||
FRONTEND_PORT: ${{ secrets.FRONTEND_PORT }}
|
||||
POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }}
|
||||
POSTGRES_PORT: ${{ secrets.POSTGRES_PORT }}
|
||||
POSTGRES_USER: ${{ secrets.POSTGRES_USER }}
|
||||
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
|
||||
POSTGRES_DB: ${{ secrets.POSTGRES_DB }}
|
||||
REDIS_HOST: ${{ secrets.REDIS_HOST }}
|
||||
REDIS_PORT: ${{ secrets.REDIS_PORT }}
|
||||
S3_ENDPOINT: ${{ secrets.S3_ENDPOINT }}
|
||||
S3_PORT: ${{ secrets.S3_PORT }}
|
||||
S3_ACCESS_KEY: ${{ secrets.S3_ACCESS_KEY }}
|
||||
S3_SECRET_KEY: ${{ secrets.S3_SECRET_KEY }}
|
||||
S3_BUCKET_NAME: ${{ secrets.S3_BUCKET_NAME }}
|
||||
JWT_SECRET: ${{ secrets.JWT_SECRET }}
|
||||
ENCRYPTION_KEY: ${{ secrets.ENCRYPTION_KEY }}
|
||||
PGP_ENCRYPTION_KEY: ${{ secrets.PGP_ENCRYPTION_KEY }}
|
||||
SESSION_PASSWORD: ${{ secrets.SESSION_PASSWORD }}
|
||||
MAIL_HOST: ${{ secrets.MAIL_HOST }}
|
||||
MAIL_PASS: ${{ secrets.MAIL_PASS }}
|
||||
MAIL_USER: ${{ secrets.MAIL_USER }}
|
||||
MAIL_FROM: ${{ secrets.MAIL_FROM }}
|
||||
DOMAIN_NAME: ${{ secrets.DOMAIN_NAME }}
|
||||
NEXT_PUBLIC_API_URL: ${{ secrets.NEXT_PUBLIC_API_URL }}
|
||||
@@ -1,36 +0,0 @@
|
||||
name: Lint
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'backend/**'
|
||||
- 'documentation/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'frontend/**'
|
||||
- 'backend/**'
|
||||
- 'documentation/**'
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: 'pnpm'
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Lint Frontend
|
||||
if: success() || failure()
|
||||
run: pnpm -F @memegoat/frontend lint
|
||||
- name: Lint Backend
|
||||
if: success() || failure()
|
||||
run: pnpm -F @memegoat/backend lint
|
||||
- name: Lint Documentation
|
||||
if: success() || failure()
|
||||
run: pnpm -F @bypass/documentation lint
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,6 +1,7 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
.pnpm-store
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
|
||||
50
ROADMAP.md
Normal file
50
ROADMAP.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# 🐐 Memegoat - Roadmap & Critères de Production
|
||||
|
||||
Ce document définit les objectifs, les critères techniques et les fonctionnalités à atteindre pour que le projet Memegoat soit considéré comme prêt pour la production et conforme aux normes européennes (RGPD) et françaises.
|
||||
|
||||
## 1. 🏗️ Architecture & Infrastructure
|
||||
- [x] Backend NestJS (TypeScript)
|
||||
- [x] Base de données PostgreSQL avec Drizzle ORM
|
||||
- [x] Stockage d'objets compatible S3 (MinIO)
|
||||
- [x] Service d'Emailing (Nodemailer / SMTPS)
|
||||
- [x] Documentation Technique & Référence API (`docs.memegoat.fr`)
|
||||
- [x] Health Checks (`/health`)
|
||||
- [x] Gestion des variables d'environnement (Validation avec Zod)
|
||||
- [ ] CI/CD (Build, Lint, Test, Deploy)
|
||||
|
||||
## 2. 🔐 Sécurité & Authentification
|
||||
- [x] Hachage des mots de passe (Argon2id)
|
||||
- [x] Gestion des sessions robuste (JWT avec Refresh Token et Rotation)
|
||||
- [x] RBAC (Role Based Access Control) fonctionnel
|
||||
- [x] Système de Clés API (Hachées en base)
|
||||
- [x] Double Authentification (2FA / TOTP)
|
||||
- [x] Limitation de débit (Rate Limiting / Throttler)
|
||||
- [x] Validation stricte des entrées (DTOs + ValidationPipe)
|
||||
- [x] Protection contre les vulnérabilités OWASP (Helmet, CORS)
|
||||
|
||||
## 3. ⚖️ Conformité RGPD (EU & France)
|
||||
- [x] Chiffrement natif des données personnelles (PII) via PGP (pgcrypto)
|
||||
- [x] Hachage aveugle (Blind Indexing) pour l'email (recherche/unicité)
|
||||
- [x] Journalisation d'audit complète (Audit Logs) pour les actions sensibles
|
||||
- [x] Gestion du consentement (Versionnage CGU/Politique de Confidentialité)
|
||||
- [x] Droit à l'effacement : Flux de suppression (Soft Delete -> Purge définitive)
|
||||
- [x] Droit à la portabilité : Export des données utilisateur (JSON)
|
||||
- [x] Purge automatique des données obsolètes (Signalements, Sessions expirées)
|
||||
- [x] Anonymisation des adresses IP (Hachage) dans les logs
|
||||
|
||||
## 4. 🖼️ Fonctionnalités Coeur (Media & Galerie)
|
||||
- [x] Exploration (Trends, Recent, Favoris)
|
||||
- [x] Recherche par Tags, Catégories, Auteur, Texte
|
||||
- [x] Gestion des Favoris
|
||||
- [x] Upload sécurisé via S3 (URLs présignées)
|
||||
- [x] Scan Antivirus (ClamAV) et traitement des médias (WebP, WebM, AVIF, AV1)
|
||||
- [x] Limitation de la taille et des formats de fichiers entrants (Configurable)
|
||||
- [x] Système de Signalement (Reports) et workflow de modération
|
||||
- [ ] SEO : Metatags dynamiques et slugs sémantiques
|
||||
|
||||
## 5. ✅ Qualité & Robustesse
|
||||
- [ ] Couverture de tests unitaires (Jest) > 80%
|
||||
- [ ] Tests d'intégration et E2E
|
||||
- [x] Gestion centralisée des erreurs (Filters NestJS)
|
||||
- [ ] Monitoring et centralisation des logs (ex: Sentry, ELK/Loki)
|
||||
- [ ] Performance : Cache (Redis) pour les tendances et recherches fréquentes
|
||||
177
backend/.migrations/0000_right_sally_floyd.sql
Normal file
177
backend/.migrations/0000_right_sally_floyd.sql
Normal file
@@ -0,0 +1,177 @@
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
CREATE TYPE "public"."user_status" AS ENUM('active', 'verification', 'suspended', 'pending', 'deleted');--> statement-breakpoint
|
||||
CREATE TYPE "public"."content_type" AS ENUM('meme', 'gif');--> statement-breakpoint
|
||||
CREATE TYPE "public"."report_reason" AS ENUM('inappropriate', 'spam', 'copyright', 'other');--> statement-breakpoint
|
||||
CREATE TYPE "public"."report_status" AS ENUM('pending', 'reviewed', 'resolved', 'dismissed');--> statement-breakpoint
|
||||
CREATE TABLE "users" (
|
||||
"uuid" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"status" "user_status" DEFAULT 'pending' NOT NULL,
|
||||
"email" "bytea" NOT NULL,
|
||||
"email_hash" varchar(64) NOT NULL,
|
||||
"display_name" varchar(32),
|
||||
"username" varchar(32) NOT NULL,
|
||||
"password_hash" varchar(72) NOT NULL,
|
||||
"two_factor_secret" "bytea",
|
||||
"is_two_factor_enabled" boolean DEFAULT false NOT NULL,
|
||||
"terms_version" varchar(16),
|
||||
"privacy_version" varchar(16),
|
||||
"gdpr_accepted_at" timestamp with time zone,
|
||||
"last_login_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"deleted_at" timestamp with time zone,
|
||||
CONSTRAINT "users_email_hash_unique" UNIQUE("email_hash"),
|
||||
CONSTRAINT "users_username_unique" UNIQUE("username")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "permissions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" varchar(64) NOT NULL,
|
||||
"slug" varchar(64) NOT NULL,
|
||||
"description" varchar(128),
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "permissions_name_unique" UNIQUE("name"),
|
||||
CONSTRAINT "permissions_slug_unique" UNIQUE("slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "roles" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" varchar(64) NOT NULL,
|
||||
"slug" varchar(64) NOT NULL,
|
||||
"description" varchar(128),
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "roles_name_unique" UNIQUE("name"),
|
||||
CONSTRAINT "roles_slug_unique" UNIQUE("slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "roles_to_permissions" (
|
||||
"role_id" uuid NOT NULL,
|
||||
"permission_id" uuid NOT NULL,
|
||||
CONSTRAINT "roles_to_permissions_role_id_permission_id_pk" PRIMARY KEY("role_id","permission_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "users_to_roles" (
|
||||
"user_id" uuid NOT NULL,
|
||||
"role_id" uuid NOT NULL,
|
||||
CONSTRAINT "users_to_roles_user_id_role_id_pk" PRIMARY KEY("user_id","role_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "sessions" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"refresh_token" varchar(512) NOT NULL,
|
||||
"user_agent" varchar(255),
|
||||
"ip_hash" varchar(64),
|
||||
"is_valid" boolean DEFAULT true NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "sessions_refresh_token_unique" UNIQUE("refresh_token")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "api_keys" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"key_hash" varchar(128) NOT NULL,
|
||||
"name" varchar(128) NOT NULL,
|
||||
"prefix" varchar(8) NOT NULL,
|
||||
"is_active" boolean DEFAULT true NOT NULL,
|
||||
"last_used_at" timestamp with time zone,
|
||||
"expires_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "api_keys_key_hash_unique" UNIQUE("key_hash")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "tags" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" varchar(64) NOT NULL,
|
||||
"slug" varchar(64) NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "tags_name_unique" UNIQUE("name"),
|
||||
CONSTRAINT "tags_slug_unique" UNIQUE("slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "contents" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL,
|
||||
"type" "content_type" NOT NULL,
|
||||
"title" varchar(255) NOT NULL,
|
||||
"storage_key" varchar(512) NOT NULL,
|
||||
"mime_type" varchar(128) NOT NULL,
|
||||
"file_size" integer NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"deleted_at" timestamp with time zone,
|
||||
CONSTRAINT "contents_storage_key_unique" UNIQUE("storage_key")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "contents_to_tags" (
|
||||
"content_id" uuid NOT NULL,
|
||||
"tag_id" uuid NOT NULL,
|
||||
CONSTRAINT "contents_to_tags_content_id_tag_id_pk" PRIMARY KEY("content_id","tag_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "reports" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"reporter_id" uuid NOT NULL,
|
||||
"content_id" uuid,
|
||||
"tag_id" uuid,
|
||||
"reason" "report_reason" NOT NULL,
|
||||
"description" text,
|
||||
"status" "report_status" DEFAULT 'pending' NOT NULL,
|
||||
"expires_at" timestamp with time zone,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "audit_logs" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid,
|
||||
"action" varchar(64) NOT NULL,
|
||||
"entity_type" varchar(64) NOT NULL,
|
||||
"entity_id" uuid,
|
||||
"details" jsonb,
|
||||
"ip_hash" varchar(64),
|
||||
"user_agent" varchar(255),
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "roles_to_permissions" ADD CONSTRAINT "roles_to_permissions_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "roles_to_permissions" ADD CONSTRAINT "roles_to_permissions_permission_id_permissions_id_fk" FOREIGN KEY ("permission_id") REFERENCES "public"."permissions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "users_to_roles" ADD CONSTRAINT "users_to_roles_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "users_to_roles" ADD CONSTRAINT "users_to_roles_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "contents" ADD CONSTRAINT "contents_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "contents_to_tags" ADD CONSTRAINT "contents_to_tags_content_id_contents_id_fk" FOREIGN KEY ("content_id") REFERENCES "public"."contents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "contents_to_tags" ADD CONSTRAINT "contents_to_tags_tag_id_tags_id_fk" FOREIGN KEY ("tag_id") REFERENCES "public"."tags"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "reports" ADD CONSTRAINT "reports_reporter_id_users_uuid_fk" FOREIGN KEY ("reporter_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "reports" ADD CONSTRAINT "reports_content_id_contents_id_fk" FOREIGN KEY ("content_id") REFERENCES "public"."contents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "reports" ADD CONSTRAINT "reports_tag_id_tags_id_fk" FOREIGN KEY ("tag_id") REFERENCES "public"."tags"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "users_uuid_idx" ON "users" USING btree ("uuid");--> statement-breakpoint
|
||||
CREATE INDEX "users_email_hash_idx" ON "users" USING btree ("email_hash");--> statement-breakpoint
|
||||
CREATE INDEX "users_username_idx" ON "users" USING btree ("username");--> statement-breakpoint
|
||||
CREATE INDEX "users_status_idx" ON "users" USING btree ("status");--> statement-breakpoint
|
||||
CREATE INDEX "permissions_slug_idx" ON "permissions" USING btree ("slug");--> statement-breakpoint
|
||||
CREATE INDEX "roles_slug_idx" ON "roles" USING btree ("slug");--> statement-breakpoint
|
||||
CREATE INDEX "sessions_user_id_idx" ON "sessions" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE INDEX "sessions_refresh_token_idx" ON "sessions" USING btree ("refresh_token");--> statement-breakpoint
|
||||
CREATE INDEX "sessions_expires_at_idx" ON "sessions" USING btree ("expires_at");--> statement-breakpoint
|
||||
CREATE INDEX "api_keys_user_id_idx" ON "api_keys" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE INDEX "api_keys_key_hash_idx" ON "api_keys" USING btree ("key_hash");--> statement-breakpoint
|
||||
CREATE INDEX "tags_slug_idx" ON "tags" USING btree ("slug");--> statement-breakpoint
|
||||
CREATE INDEX "contents_user_id_idx" ON "contents" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE INDEX "contents_storage_key_idx" ON "contents" USING btree ("storage_key");--> statement-breakpoint
|
||||
CREATE INDEX "contents_deleted_at_idx" ON "contents" USING btree ("deleted_at");--> statement-breakpoint
|
||||
CREATE INDEX "reports_reporter_id_idx" ON "reports" USING btree ("reporter_id");--> statement-breakpoint
|
||||
CREATE INDEX "reports_content_id_idx" ON "reports" USING btree ("content_id");--> statement-breakpoint
|
||||
CREATE INDEX "reports_tag_id_idx" ON "reports" USING btree ("tag_id");--> statement-breakpoint
|
||||
CREATE INDEX "reports_status_idx" ON "reports" USING btree ("status");--> statement-breakpoint
|
||||
CREATE INDEX "reports_expires_at_idx" ON "reports" USING btree ("expires_at");--> statement-breakpoint
|
||||
CREATE INDEX "audit_logs_user_id_idx" ON "audit_logs" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE INDEX "audit_logs_action_idx" ON "audit_logs" USING btree ("action");--> statement-breakpoint
|
||||
CREATE INDEX "audit_logs_entity_idx" ON "audit_logs" USING btree ("entity_type","entity_id");--> statement-breakpoint
|
||||
CREATE INDEX "audit_logs_created_at_idx" ON "audit_logs" USING btree ("created_at");
|
||||
30
backend/.migrations/0001_purple_goliath.sql
Normal file
30
backend/.migrations/0001_purple_goliath.sql
Normal file
@@ -0,0 +1,30 @@
|
||||
CREATE TABLE "categories" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"name" varchar(64) NOT NULL,
|
||||
"slug" varchar(64) NOT NULL,
|
||||
"description" varchar(255),
|
||||
"icon_url" varchar(512),
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "categories_name_unique" UNIQUE("name"),
|
||||
CONSTRAINT "categories_slug_unique" UNIQUE("slug")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "favorites" (
|
||||
"user_id" uuid NOT NULL,
|
||||
"content_id" uuid NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "favorites_user_id_content_id_pk" PRIMARY KEY("user_id","content_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "tags" ADD COLUMN "user_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "contents" ADD COLUMN "category_id" uuid;--> statement-breakpoint
|
||||
ALTER TABLE "contents" ADD COLUMN "slug" varchar(255) NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "contents" ADD COLUMN "views" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "contents" ADD COLUMN "usage_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
|
||||
ALTER TABLE "favorites" ADD CONSTRAINT "favorites_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "favorites" ADD CONSTRAINT "favorites_content_id_contents_id_fk" FOREIGN KEY ("content_id") REFERENCES "public"."contents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "categories_slug_idx" ON "categories" USING btree ("slug");--> statement-breakpoint
|
||||
ALTER TABLE "tags" ADD CONSTRAINT "tags_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "contents" ADD CONSTRAINT "contents_category_id_categories_id_fk" FOREIGN KEY ("category_id") REFERENCES "public"."categories"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "contents" ADD CONSTRAINT "contents_slug_unique" UNIQUE("slug");
|
||||
1
backend/.migrations/0002_redundant_skin.sql
Normal file
1
backend/.migrations/0002_redundant_skin.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN "avatar_url" varchar(255);
|
||||
2
backend/.migrations/0003_colossal_fantastic_four.sql
Normal file
2
backend/.migrations/0003_colossal_fantastic_four.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "users" ALTER COLUMN "password_hash" SET DATA TYPE varchar(255);--> statement-breakpoint
|
||||
ALTER TABLE "users" DROP COLUMN "avatar_url";
|
||||
1
backend/.migrations/0004_cheerful_dakota_north.sql
Normal file
1
backend/.migrations/0004_cheerful_dakota_north.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ALTER COLUMN "password_hash" SET DATA TYPE varchar(95);
|
||||
1
backend/.migrations/0005_perpetual_silverclaw.sql
Normal file
1
backend/.migrations/0005_perpetual_silverclaw.sql
Normal file
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ALTER COLUMN "password_hash" SET DATA TYPE varchar(100);
|
||||
2
backend/.migrations/0006_friendly_adam_warlock.sql
Normal file
2
backend/.migrations/0006_friendly_adam_warlock.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "users" ADD COLUMN "avatar_url" varchar(512);--> statement-breakpoint
|
||||
ALTER TABLE "users" ADD COLUMN "bio" varchar(255);
|
||||
1316
backend/.migrations/meta/0000_snapshot.json
Normal file
1316
backend/.migrations/meta/0000_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
1513
backend/.migrations/meta/0001_snapshot.json
Normal file
1513
backend/.migrations/meta/0001_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
1519
backend/.migrations/meta/0002_snapshot.json
Normal file
1519
backend/.migrations/meta/0002_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
1640
backend/.migrations/meta/0003_snapshot.json
Normal file
1640
backend/.migrations/meta/0003_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
1640
backend/.migrations/meta/0004_snapshot.json
Normal file
1640
backend/.migrations/meta/0004_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
1640
backend/.migrations/meta/0005_snapshot.json
Normal file
1640
backend/.migrations/meta/0005_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
1652
backend/.migrations/meta/0006_snapshot.json
Normal file
1652
backend/.migrations/meta/0006_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
55
backend/.migrations/meta/_journal.json
Normal file
55
backend/.migrations/meta/_journal.json
Normal file
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1767618753676,
|
||||
"tag": "0000_right_sally_floyd",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 1,
|
||||
"version": "7",
|
||||
"when": 1768392191169,
|
||||
"tag": "0001_purple_goliath",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1768393637823,
|
||||
"tag": "0002_redundant_skin",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1768415667895,
|
||||
"tag": "0003_colossal_fantastic_four",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1768417827439,
|
||||
"tag": "0004_cheerful_dakota_north",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "7",
|
||||
"when": 1768420201679,
|
||||
"tag": "0005_perpetual_silverclaw",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 6,
|
||||
"version": "7",
|
||||
"when": 1768423315172,
|
||||
"tag": "0006_friendly_adam_warlock",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,17 +1,34 @@
|
||||
FROM node:22-slim AS base
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM node:22-alpine AS base
|
||||
ENV PNPM_HOME="/pnpm"
|
||||
ENV PATH="$PNPM_HOME:$PATH"
|
||||
RUN corepack enable
|
||||
RUN corepack enable && corepack prepare pnpm@latest --activate
|
||||
|
||||
FROM base AS build
|
||||
WORKDIR /usr/src/app
|
||||
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
|
||||
COPY backend/package.json ./backend/
|
||||
COPY frontend/package.json ./frontend/
|
||||
COPY documentation/package.json ./documentation/
|
||||
|
||||
# Utilisation du cache pour pnpm et installation figée
|
||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile
|
||||
|
||||
# Deuxième passe avec cache pour les scripts/liens
|
||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
RUN pnpm run --filter @memegoat/backend build
|
||||
RUN pnpm deploy --filter=@memegoat/backend --prod /app
|
||||
RUN pnpm deploy --filter=@memegoat/backend --prod --legacy /app
|
||||
RUN cp -r backend/dist /app/dist
|
||||
RUN cp -r backend/.migrations /app/.migrations
|
||||
|
||||
FROM base AS runtime
|
||||
WORKDIR /app
|
||||
COPY --from=build /app .
|
||||
EXPOSE 3000
|
||||
CMD [ "node", "dist/main" ]
|
||||
ENV NODE_ENV=production
|
||||
CMD [ "node", "dist/src/main" ]
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
},
|
||||
"files": {
|
||||
"ignoreUnknown": true,
|
||||
"includes": ["**", "!node_modules", "!dist", "!build"]
|
||||
"includes": ["**", "!node_modules", "!dist", "!build", "!.migrations"]
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
{
|
||||
"name": "@memegoat/backend",
|
||||
"version": "0.0.1",
|
||||
"version": "0.1.0",
|
||||
"description": "",
|
||||
"author": "",
|
||||
"private": true,
|
||||
"license": "UNLICENSED",
|
||||
"files": [
|
||||
"dist"
|
||||
"dist",
|
||||
".migrations",
|
||||
"drizzle.config.ts"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "nest build",
|
||||
@@ -60,10 +62,22 @@
|
||||
"rxjs": "^7.8.1",
|
||||
"sharp": "^0.34.5",
|
||||
"uuid": "^13.0.0",
|
||||
"zod": "^4.3.5"
|
||||
"zod": "^4.3.5",
|
||||
"drizzle-kit": "^0.31.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"globals": "^16.0.0",
|
||||
"jest": "^30.0.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@types/express": "^5.0.0",
|
||||
@@ -77,18 +91,7 @@
|
||||
"@types/sharp": "^0.32.0",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"@types/uuid": "^11.0.0",
|
||||
"drizzle-kit": "^0.31.8",
|
||||
"globals": "^16.0.0",
|
||||
"jest": "^30.0.0",
|
||||
"source-map-support": "^0.5.21",
|
||||
"supertest": "^7.0.0",
|
||||
"ts-jest": "^29.2.5",
|
||||
"ts-loader": "^9.5.2",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"tsx": "^4.21.0",
|
||||
"typescript": "^5.7.3",
|
||||
"typescript-eslint": "^8.20.0"
|
||||
"drizzle-kit": "^0.31.8"
|
||||
},
|
||||
"jest": {
|
||||
"moduleFileExtensions": [
|
||||
@@ -104,7 +107,7 @@
|
||||
"coverageDirectory": "../coverage",
|
||||
"testEnvironment": "node",
|
||||
"transformIgnorePatterns": [
|
||||
"node_modules/(?!(jose|@noble)/)"
|
||||
"node_modules/(?!(.pnpm/)?(jose|@noble|uuid)/)"
|
||||
],
|
||||
"transform": {
|
||||
"^.+\\.(t|j)sx?$": "ts-jest"
|
||||
|
||||
17
backend/src/admin/admin.controller.ts
Normal file
17
backend/src/admin/admin.controller.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { Controller, Get, UseGuards } from "@nestjs/common";
|
||||
import { Roles } from "../auth/decorators/roles.decorator";
|
||||
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||
import { RolesGuard } from "../auth/guards/roles.guard";
|
||||
import { AdminService } from "./admin.service";
|
||||
|
||||
@Controller("admin")
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Roles("admin")
|
||||
export class AdminController {
|
||||
constructor(private readonly adminService: AdminService) {}
|
||||
|
||||
@Get("stats")
|
||||
getStats() {
|
||||
return this.adminService.getStats();
|
||||
}
|
||||
}
|
||||
14
backend/src/admin/admin.module.ts
Normal file
14
backend/src/admin/admin.module.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { CategoriesModule } from "../categories/categories.module";
|
||||
import { ContentsModule } from "../contents/contents.module";
|
||||
import { UsersModule } from "../users/users.module";
|
||||
import { AdminController } from "./admin.controller";
|
||||
import { AdminService } from "./admin.service";
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, UsersModule, ContentsModule, CategoriesModule],
|
||||
controllers: [AdminController],
|
||||
providers: [AdminService],
|
||||
})
|
||||
export class AdminModule {}
|
||||
27
backend/src/admin/admin.service.ts
Normal file
27
backend/src/admin/admin.service.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { CategoriesRepository } from "../categories/repositories/categories.repository";
|
||||
import { ContentsRepository } from "../contents/repositories/contents.repository";
|
||||
import { UsersRepository } from "../users/repositories/users.repository";
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
constructor(
|
||||
private readonly usersRepository: UsersRepository,
|
||||
private readonly contentsRepository: ContentsRepository,
|
||||
private readonly categoriesRepository: CategoriesRepository,
|
||||
) {}
|
||||
|
||||
async getStats() {
|
||||
const [userCount, contentCount, categoryCount] = await Promise.all([
|
||||
this.usersRepository.countAll(),
|
||||
this.contentsRepository.count({}),
|
||||
this.categoriesRepository.countAll(),
|
||||
]);
|
||||
|
||||
return {
|
||||
users: userCount,
|
||||
contents: contentCount,
|
||||
categories: categoryCount,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||
import type { AuthenticatedRequest } from "../common/interfaces/request.interface";
|
||||
import { ApiKeysService } from "./api-keys.service";
|
||||
import { CreateApiKeyDto } from "./dto/create-api-key.dto";
|
||||
|
||||
@Controller("api-keys")
|
||||
@UseGuards(AuthGuard)
|
||||
@@ -20,13 +21,12 @@ export class ApiKeysController {
|
||||
@Post()
|
||||
create(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
@Body("name") name: string,
|
||||
@Body("expiresAt") expiresAt?: string,
|
||||
@Body() createApiKeyDto: CreateApiKeyDto,
|
||||
) {
|
||||
return this.apiKeysService.create(
|
||||
req.user.sub,
|
||||
name,
|
||||
expiresAt ? new Date(expiresAt) : undefined,
|
||||
createApiKeyDto.name,
|
||||
createApiKeyDto.expiresAt ? new Date(createApiKeyDto.expiresAt) : undefined,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { forwardRef, Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { CryptoModule } from "../crypto/crypto.module";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { ApiKeysController } from "./api-keys.controller";
|
||||
import { ApiKeysService } from "./api-keys.service";
|
||||
import { ApiKeysRepository } from "./repositories/api-keys.repository";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, AuthModule, CryptoModule],
|
||||
imports: [forwardRef(() => AuthModule)],
|
||||
controllers: [ApiKeysController],
|
||||
providers: [ApiKeysService, ApiKeysRepository],
|
||||
exports: [ApiKeysService],
|
||||
exports: [ApiKeysService, ApiKeysRepository],
|
||||
})
|
||||
export class ApiKeysModule {}
|
||||
|
||||
18
backend/src/api-keys/dto/create-api-key.dto.ts
Normal file
18
backend/src/api-keys/dto/create-api-key.dto.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import {
|
||||
IsDateString,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
} from "class-validator";
|
||||
|
||||
export class CreateApiKeyDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(128)
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
expiresAt?: string;
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import { CacheModule } from "@nestjs/cache-manager";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
|
||||
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||
import { ScheduleModule } from "@nestjs/schedule";
|
||||
import { ThrottlerModule } from "@nestjs/throttler";
|
||||
import { redisStore } from "cache-manager-redis-yet";
|
||||
import { AdminModule } from "./admin/admin.module";
|
||||
import { ApiKeysModule } from "./api-keys/api-keys.module";
|
||||
import { AppController } from "./app.controller";
|
||||
import { AppService } from "./app.service";
|
||||
import { AuthModule } from "./auth/auth.module";
|
||||
import { CategoriesModule } from "./categories/categories.module";
|
||||
import { CommonModule } from "./common/common.module";
|
||||
import { CrawlerDetectionMiddleware } from "./common/middlewares/crawler-detection.middleware";
|
||||
import { HTTPLoggerMiddleware } from "./common/middlewares/http-logger.middleware";
|
||||
import { validateEnv } from "./config/env.schema";
|
||||
import { ContentsModule } from "./contents/contents.module";
|
||||
import { CryptoModule } from "./crypto/crypto.module";
|
||||
@@ -41,6 +44,7 @@ import { UsersModule } from "./users/users.module";
|
||||
SessionsModule,
|
||||
ReportsModule,
|
||||
ApiKeysModule,
|
||||
AdminModule,
|
||||
ScheduleModule.forRoot(),
|
||||
ThrottlerModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
@@ -71,4 +75,10 @@ import { UsersModule } from "./users/users.module";
|
||||
controllers: [AppController, HealthController],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule {}
|
||||
export class AppModule implements NestModule {
|
||||
configure(consumer: MiddlewareConsumer) {
|
||||
consumer
|
||||
.apply(HTTPLoggerMiddleware, CrawlerDetectionMiddleware)
|
||||
.forRoutes("*");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,32 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { CryptoModule } from "../crypto/crypto.module";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { forwardRef, Module } from "@nestjs/common";
|
||||
import { SessionsModule } from "../sessions/sessions.module";
|
||||
import { UsersModule } from "../users/users.module";
|
||||
import { AuthController } from "./auth.controller";
|
||||
import { AuthService } from "./auth.service";
|
||||
import { AuthGuard } from "./guards/auth.guard";
|
||||
import { OptionalAuthGuard } from "./guards/optional-auth.guard";
|
||||
import { RolesGuard } from "./guards/roles.guard";
|
||||
import { RbacService } from "./rbac.service";
|
||||
import { RbacRepository } from "./repositories/rbac.repository";
|
||||
|
||||
@Module({
|
||||
imports: [UsersModule, CryptoModule, SessionsModule, DatabaseModule],
|
||||
imports: [forwardRef(() => UsersModule), SessionsModule],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, RbacService, RbacRepository],
|
||||
exports: [AuthService, RbacService],
|
||||
providers: [
|
||||
AuthService,
|
||||
RbacService,
|
||||
RbacRepository,
|
||||
AuthGuard,
|
||||
OptionalAuthGuard,
|
||||
RolesGuard,
|
||||
],
|
||||
exports: [
|
||||
AuthService,
|
||||
RbacService,
|
||||
RbacRepository,
|
||||
AuthGuard,
|
||||
OptionalAuthGuard,
|
||||
RolesGuard,
|
||||
],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
jest.mock("uuid", () => ({
|
||||
v4: jest.fn(() => "mocked-uuid"),
|
||||
}));
|
||||
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
|
||||
jest.mock("@noble/post-quantum/ml-kem.js", () => ({
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
forwardRef,
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
UnauthorizedException,
|
||||
@@ -19,6 +21,7 @@ export class AuthService {
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
|
||||
constructor(
|
||||
@Inject(forwardRef(() => UsersService))
|
||||
private readonly usersService: UsersService,
|
||||
private readonly hashingService: HashingService,
|
||||
private readonly jwtService: JwtService,
|
||||
@@ -107,6 +110,7 @@ export class AuthService {
|
||||
const user = await this.usersService.findByEmailHash(emailHash);
|
||||
|
||||
if (!user) {
|
||||
this.logger.warn(`Login failed: user not found for email hash`);
|
||||
throw new UnauthorizedException("Invalid credentials");
|
||||
}
|
||||
|
||||
@@ -116,10 +120,12 @@ export class AuthService {
|
||||
);
|
||||
|
||||
if (!isPasswordValid) {
|
||||
this.logger.warn(`Login failed: invalid password for user ${user.uuid}`);
|
||||
throw new UnauthorizedException("Invalid credentials");
|
||||
}
|
||||
|
||||
if (user.isTwoFactorEnabled) {
|
||||
this.logger.log(`2FA required for user ${user.uuid}`);
|
||||
return {
|
||||
message: "2FA required",
|
||||
requires2FA: true,
|
||||
@@ -138,6 +144,7 @@ export class AuthService {
|
||||
ip,
|
||||
);
|
||||
|
||||
this.logger.log(`User ${user.uuid} logged in successfully`);
|
||||
return {
|
||||
message: "User logged in successfully",
|
||||
access_token: accessToken,
|
||||
@@ -162,6 +169,9 @@ export class AuthService {
|
||||
|
||||
const isValid = authenticator.verify({ token, secret });
|
||||
if (!isValid) {
|
||||
this.logger.warn(
|
||||
`2FA verification failed for user ${userId}: invalid token`,
|
||||
);
|
||||
throw new UnauthorizedException("Invalid 2FA token");
|
||||
}
|
||||
|
||||
@@ -176,6 +186,7 @@ export class AuthService {
|
||||
ip,
|
||||
);
|
||||
|
||||
this.logger.log(`User ${userId} logged in successfully via 2FA`);
|
||||
return {
|
||||
message: "User logged in successfully (2FA)",
|
||||
access_token: accessToken,
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
import { IsEmail, IsNotEmpty, IsString, MinLength } from "class-validator";
|
||||
import {
|
||||
IsEmail,
|
||||
IsNotEmpty,
|
||||
IsString,
|
||||
MaxLength,
|
||||
MinLength,
|
||||
} from "class-validator";
|
||||
|
||||
export class RegisterDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(32)
|
||||
username!: string;
|
||||
|
||||
@IsString()
|
||||
@MaxLength(32)
|
||||
displayName?: string;
|
||||
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
|
||||
39
backend/src/auth/guards/optional-auth.guard.ts
Normal file
39
backend/src/auth/guards/optional-auth.guard.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { getIronSession } from "iron-session";
|
||||
import { JwtService } from "../../crypto/services/jwt.service";
|
||||
import { getSessionOptions, SessionData } from "../session.config";
|
||||
|
||||
@Injectable()
|
||||
export class OptionalAuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const response = context.switchToHttp().getResponse();
|
||||
|
||||
const session = await getIronSession<SessionData>(
|
||||
request,
|
||||
response,
|
||||
getSessionOptions(this.configService.get("SESSION_PASSWORD") as string),
|
||||
);
|
||||
|
||||
const token = session.accessToken;
|
||||
|
||||
if (!token) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await this.jwtService.verifyJwt(token);
|
||||
request.user = payload;
|
||||
} catch {
|
||||
// Ignore invalid tokens for optional auth
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,9 @@ describe("RbacService", () => {
|
||||
it("should return user permissions", async () => {
|
||||
const userId = "user-id";
|
||||
const mockPermissions = ["read", "write"];
|
||||
mockRbacRepository.findPermissionsByUserId.mockResolvedValue(mockPermissions);
|
||||
mockRbacRepository.findPermissionsByUserId.mockResolvedValue(
|
||||
mockPermissions,
|
||||
);
|
||||
|
||||
const result = await service.getUserPermissions(userId);
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { CacheInterceptor, CacheKey, CacheTTL } from "@nestjs/cache-manager";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@@ -9,7 +10,6 @@ import {
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from "@nestjs/common";
|
||||
import { CacheInterceptor, CacheKey, CacheTTL } from "@nestjs/cache-manager";
|
||||
import { Roles } from "../auth/decorators/roles.decorator";
|
||||
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||
import { RolesGuard } from "../auth/guards/roles.guard";
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { CategoriesController } from "./categories.controller";
|
||||
import { CategoriesService } from "./categories.service";
|
||||
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule],
|
||||
imports: [AuthModule],
|
||||
controllers: [CategoriesController],
|
||||
providers: [CategoriesService, CategoriesRepository],
|
||||
exports: [CategoriesService],
|
||||
exports: [CategoriesService, CategoriesRepository],
|
||||
})
|
||||
export class CategoriesModule {}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { CategoriesService } from "./categories.service";
|
||||
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||
import { CreateCategoryDto } from "./dto/create-category.dto";
|
||||
import { UpdateCategoryDto } from "./dto/update-category.dto";
|
||||
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||
|
||||
describe("CategoriesService", () => {
|
||||
let service: CategoriesService;
|
||||
@@ -75,7 +75,9 @@ describe("CategoriesService", () => {
|
||||
describe("create", () => {
|
||||
it("should create a category and generate slug", async () => {
|
||||
const dto: CreateCategoryDto = { name: "Test Category" };
|
||||
mockCategoriesRepository.create.mockResolvedValue([{ ...dto, slug: "test-category" }]);
|
||||
mockCategoriesRepository.create.mockResolvedValue([
|
||||
{ ...dto, slug: "test-category" },
|
||||
]);
|
||||
|
||||
const result = await service.create(dto);
|
||||
|
||||
@@ -91,7 +93,9 @@ describe("CategoriesService", () => {
|
||||
it("should update a category and regenerate slug", async () => {
|
||||
const id = "1";
|
||||
const dto: UpdateCategoryDto = { name: "New Name" };
|
||||
mockCategoriesRepository.update.mockResolvedValue([{ id, ...dto, slug: "new-name" }]);
|
||||
mockCategoriesRepository.update.mockResolvedValue([
|
||||
{ id, ...dto, slug: "new-name" },
|
||||
]);
|
||||
|
||||
const result = await service.update(id, dto);
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Injectable, Logger, Inject } from "@nestjs/common";
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { Cache } from "cache-manager";
|
||||
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||
import { Inject, Injectable, Logger } from "@nestjs/common";
|
||||
import type { Cache } from "cache-manager";
|
||||
import { CreateCategoryDto } from "./dto/create-category.dto";
|
||||
import { UpdateCategoryDto } from "./dto/update-category.dto";
|
||||
import { CategoriesRepository } from "./repositories/categories.repository";
|
||||
|
||||
@Injectable()
|
||||
export class CategoriesService {
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||
import { IsNotEmpty, IsOptional, IsString, MaxLength } from "class-validator";
|
||||
|
||||
export class CreateCategoryDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(64)
|
||||
name!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
description?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(512)
|
||||
iconUrl?: string;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { DatabaseService } from "../../database/database.service";
|
||||
import { categories } from "../../database/schemas";
|
||||
import type { CreateCategoryDto } from "../dto/create-category.dto";
|
||||
@@ -16,6 +16,13 @@ export class CategoriesRepository {
|
||||
.orderBy(categories.name);
|
||||
}
|
||||
|
||||
async countAll() {
|
||||
const result = await this.databaseService.db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(categories);
|
||||
return Number(result[0].count);
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
const result = await this.databaseService.db
|
||||
.select()
|
||||
@@ -33,7 +40,10 @@ export class CategoriesRepository {
|
||||
.returning();
|
||||
}
|
||||
|
||||
async update(id: string, data: UpdateCategoryDto & { slug?: string; updatedAt: Date }) {
|
||||
async update(
|
||||
id: string,
|
||||
data: UpdateCategoryDto & { slug?: string; updatedAt: Date },
|
||||
) {
|
||||
return await this.databaseService.db
|
||||
.update(categories)
|
||||
.set(data)
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { forwardRef, Global, Module } from "@nestjs/common";
|
||||
import { ContentsModule } from "../contents/contents.module";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { ReportsModule } from "../reports/reports.module";
|
||||
import { SessionsModule } from "../sessions/sessions.module";
|
||||
import { UsersModule } from "../users/users.module";
|
||||
import { PurgeService } from "./services/purge.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [DatabaseModule],
|
||||
imports: [
|
||||
DatabaseModule,
|
||||
forwardRef(() => SessionsModule),
|
||||
forwardRef(() => ReportsModule),
|
||||
forwardRef(() => UsersModule),
|
||||
forwardRef(() => ContentsModule),
|
||||
],
|
||||
providers: [PurgeService],
|
||||
exports: [PurgeService],
|
||||
})
|
||||
|
||||
@@ -9,6 +9,14 @@ import {
|
||||
import * as Sentry from "@sentry/nestjs";
|
||||
import { Request, Response } from "express";
|
||||
|
||||
interface RequestWithUser extends Request {
|
||||
user?: {
|
||||
sub?: string;
|
||||
username?: string;
|
||||
id?: string;
|
||||
};
|
||||
}
|
||||
|
||||
@Catch()
|
||||
export class AllExceptionsFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger("ExceptionFilter");
|
||||
@@ -16,7 +24,7 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
const request = ctx.getRequest<Request>();
|
||||
const request = ctx.getRequest<RequestWithUser>();
|
||||
|
||||
const status =
|
||||
exception instanceof HttpException
|
||||
@@ -28,6 +36,9 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
? exception.getResponse()
|
||||
: "Internal server error";
|
||||
|
||||
const userId = request.user?.sub || request.user?.id;
|
||||
const userPart = userId ? `[User: ${userId}] ` : "";
|
||||
|
||||
const errorResponse = {
|
||||
statusCode: status,
|
||||
timestamp: new Date().toISOString(),
|
||||
@@ -42,12 +53,12 @@ export class AllExceptionsFilter implements ExceptionFilter {
|
||||
if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
|
||||
Sentry.captureException(exception);
|
||||
this.logger.error(
|
||||
`${request.method} ${request.url} - Error: ${exception instanceof Error ? exception.message : "Unknown error"}`,
|
||||
`${userPart}${request.method} ${request.url} - Error: ${exception instanceof Error ? exception.message : "Unknown error"}`,
|
||||
exception instanceof Error ? exception.stack : "",
|
||||
);
|
||||
} else {
|
||||
this.logger.warn(
|
||||
`${request.method} ${request.url} - Status: ${status} - Message: ${JSON.stringify(message)}`,
|
||||
`${userPart}${request.method} ${request.url} - Status: ${status} - Message: ${JSON.stringify(message)}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ export interface IMediaService {
|
||||
processImage(
|
||||
buffer: Buffer,
|
||||
format?: "webp" | "avif",
|
||||
resize?: { width?: number; height?: number },
|
||||
): Promise<MediaProcessingResult>;
|
||||
processVideo(
|
||||
buffer: Buffer,
|
||||
|
||||
@@ -9,10 +9,7 @@ export interface IStorageService {
|
||||
bucketName?: string,
|
||||
): Promise<string>;
|
||||
|
||||
getFile(
|
||||
fileName: string,
|
||||
bucketName?: string,
|
||||
): Promise<Readable>;
|
||||
getFile(fileName: string, bucketName?: string): Promise<Readable>;
|
||||
|
||||
getFileUrl(
|
||||
fileName: string,
|
||||
@@ -28,7 +25,7 @@ export interface IStorageService {
|
||||
|
||||
deleteFile(fileName: string, bucketName?: string): Promise<void>;
|
||||
|
||||
getFileInfo(fileName: string, bucketName?: string): Promise<any>;
|
||||
getFileInfo(fileName: string, bucketName?: string): Promise<unknown>;
|
||||
|
||||
moveFile(
|
||||
sourceFileName: string,
|
||||
@@ -36,4 +33,6 @@ export interface IStorageService {
|
||||
sourceBucketName?: string,
|
||||
destinationBucketName?: string,
|
||||
): Promise<string>;
|
||||
|
||||
getPublicUrl(storageKey: string): string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class CrawlerDetectionMiddleware implements NestMiddleware {
|
||||
private readonly logger = new Logger("CrawlerDetection");
|
||||
|
||||
private readonly SUSPICIOUS_PATTERNS = [
|
||||
/\.env/,
|
||||
/wp-admin/,
|
||||
/wp-login/,
|
||||
/\.git/,
|
||||
/\.php$/,
|
||||
/xmlrpc/,
|
||||
/config/,
|
||||
/setup/,
|
||||
/wp-config/,
|
||||
/_next/,
|
||||
/install/,
|
||||
/admin/,
|
||||
/phpmyadmin/,
|
||||
/sql/,
|
||||
/backup/,
|
||||
/db\./,
|
||||
/backup\./,
|
||||
/cgi-bin/,
|
||||
/\.well-known\/security\.txt/, // Bien que légitime, souvent scanné
|
||||
];
|
||||
|
||||
private readonly BOT_USER_AGENTS = [
|
||||
/bot/i,
|
||||
/crawler/i,
|
||||
/spider/i,
|
||||
/python/i,
|
||||
/curl/i,
|
||||
/wget/i,
|
||||
/nmap/i,
|
||||
/nikto/i,
|
||||
/zgrab/i,
|
||||
/masscan/i,
|
||||
];
|
||||
|
||||
use(req: Request, res: Response, next: NextFunction) {
|
||||
const { method, url, ip } = req;
|
||||
const userAgent = req.get("user-agent") || "unknown";
|
||||
|
||||
res.on("finish", () => {
|
||||
if (res.statusCode === 404) {
|
||||
const isSuspiciousPath = this.SUSPICIOUS_PATTERNS.some((pattern) =>
|
||||
pattern.test(url),
|
||||
);
|
||||
const isBotUserAgent = this.BOT_USER_AGENTS.some((pattern) =>
|
||||
pattern.test(userAgent),
|
||||
);
|
||||
|
||||
if (isSuspiciousPath || isBotUserAgent) {
|
||||
this.logger.warn(
|
||||
`Potential crawler detected: [${ip}] ${method} ${url} - User-Agent: ${userAgent}`,
|
||||
);
|
||||
// Ici, on pourrait ajouter une logique pour bannir l'IP temporairement via Redis
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
37
backend/src/common/middlewares/http-logger.middleware.ts
Normal file
37
backend/src/common/middlewares/http-logger.middleware.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
|
||||
@Injectable()
|
||||
export class HTTPLoggerMiddleware implements NestMiddleware {
|
||||
private readonly logger = new Logger("HTTP");
|
||||
|
||||
use(request: Request, response: Response, next: NextFunction): void {
|
||||
const { method, originalUrl, ip } = request;
|
||||
const userAgent = request.get("user-agent") || "";
|
||||
const startTime = Date.now();
|
||||
|
||||
response.on("finish", () => {
|
||||
const { statusCode } = response;
|
||||
const contentLength = response.get("content-length");
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
const hashedIp = createHash("sha256")
|
||||
.update(ip as string)
|
||||
.digest("hex");
|
||||
const message = `${method} ${originalUrl} ${statusCode} ${contentLength || 0} - ${userAgent} ${hashedIp} +${duration}ms`;
|
||||
|
||||
if (statusCode >= 500) {
|
||||
return this.logger.error(message);
|
||||
}
|
||||
|
||||
if (statusCode >= 400) {
|
||||
return this.logger.warn(message);
|
||||
}
|
||||
|
||||
return this.logger.log(message);
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,16 @@ import { PurgeService } from "./purge.service";
|
||||
describe("PurgeService", () => {
|
||||
let service: PurgeService;
|
||||
|
||||
const mockSessionsRepository = { purgeExpired: jest.fn().mockResolvedValue([]) };
|
||||
const mockReportsRepository = { purgeObsolete: jest.fn().mockResolvedValue([]) };
|
||||
const mockSessionsRepository = {
|
||||
purgeExpired: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
const mockReportsRepository = {
|
||||
purgeObsolete: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
const mockUsersRepository = { purgeDeleted: jest.fn().mockResolvedValue([]) };
|
||||
const mockContentsRepository = { purgeSoftDeleted: jest.fn().mockResolvedValue([]) };
|
||||
const mockContentsRepository = {
|
||||
purgeSoftDeleted: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
@@ -42,9 +42,8 @@ export class PurgeService {
|
||||
);
|
||||
|
||||
// 4. Purge des contenus supprimés (Soft Delete > 30 jours)
|
||||
const deletedContents = await this.contentsRepository.purgeSoftDeleted(
|
||||
thirtyDaysAgo,
|
||||
);
|
||||
const deletedContents =
|
||||
await this.contentsRepository.purgeSoftDeleted(thirtyDaysAgo);
|
||||
this.logger.log(
|
||||
`Purged ${deletedContents.length} contents marked for deletion more than 30 days ago.`,
|
||||
);
|
||||
|
||||
@@ -33,6 +33,7 @@ export const envSchema = z.object({
|
||||
MAIL_FROM: z.string().email(),
|
||||
|
||||
DOMAIN_NAME: z.string(),
|
||||
API_URL: z.string().url().optional(),
|
||||
|
||||
// Sentry
|
||||
SENTRY_DSN: z.string().optional(),
|
||||
|
||||
@@ -19,8 +19,11 @@ import {
|
||||
UseInterceptors,
|
||||
} from "@nestjs/common";
|
||||
import { FileInterceptor } from "@nestjs/platform-express";
|
||||
import type { Request, Response } from "express";
|
||||
import type { Response } from "express";
|
||||
import { Roles } from "../auth/decorators/roles.decorator";
|
||||
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||
import { OptionalAuthGuard } from "../auth/guards/optional-auth.guard";
|
||||
import { RolesGuard } from "../auth/guards/roles.guard";
|
||||
import type { AuthenticatedRequest } from "../common/interfaces/request.interface";
|
||||
import { ContentsService } from "./contents.service";
|
||||
import { CreateContentDto } from "./dto/create-content.dto";
|
||||
@@ -65,10 +68,12 @@ export class ContentsController {
|
||||
}
|
||||
|
||||
@Get("explore")
|
||||
@UseGuards(OptionalAuthGuard)
|
||||
@UseInterceptors(CacheInterceptor)
|
||||
@CacheTTL(60)
|
||||
@Header("Cache-Control", "public, max-age=60")
|
||||
explore(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
@Query("limit", new DefaultValuePipe(10), ParseIntPipe) limit: number,
|
||||
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
|
||||
@Query("sort") sort?: "trend" | "recent",
|
||||
@@ -78,7 +83,7 @@ export class ContentsController {
|
||||
@Query("query") query?: string,
|
||||
@Query("favoritesOnly", new DefaultValuePipe(false), ParseBoolPipe)
|
||||
favoritesOnly?: boolean,
|
||||
@Query("userId") userId?: string,
|
||||
@Query("userId") userIdQuery?: string,
|
||||
) {
|
||||
return this.contentsService.findAll({
|
||||
limit,
|
||||
@@ -89,42 +94,57 @@ export class ContentsController {
|
||||
author,
|
||||
query,
|
||||
favoritesOnly,
|
||||
userId,
|
||||
userId: userIdQuery || req.user?.sub,
|
||||
});
|
||||
}
|
||||
|
||||
@Get("trends")
|
||||
@UseGuards(OptionalAuthGuard)
|
||||
@UseInterceptors(CacheInterceptor)
|
||||
@CacheTTL(300)
|
||||
@Header("Cache-Control", "public, max-age=300")
|
||||
trends(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
@Query("limit", new DefaultValuePipe(10), ParseIntPipe) limit: number,
|
||||
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
|
||||
) {
|
||||
return this.contentsService.findAll({ limit, offset, sortBy: "trend" });
|
||||
return this.contentsService.findAll({
|
||||
limit,
|
||||
offset,
|
||||
sortBy: "trend",
|
||||
userId: req.user?.sub,
|
||||
});
|
||||
}
|
||||
|
||||
@Get("recent")
|
||||
@UseGuards(OptionalAuthGuard)
|
||||
@UseInterceptors(CacheInterceptor)
|
||||
@CacheTTL(60)
|
||||
@Header("Cache-Control", "public, max-age=60")
|
||||
recent(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
@Query("limit", new DefaultValuePipe(10), ParseIntPipe) limit: number,
|
||||
@Query("offset", new DefaultValuePipe(0), ParseIntPipe) offset: number,
|
||||
) {
|
||||
return this.contentsService.findAll({ limit, offset, sortBy: "recent" });
|
||||
return this.contentsService.findAll({
|
||||
limit,
|
||||
offset,
|
||||
sortBy: "recent",
|
||||
userId: req.user?.sub,
|
||||
});
|
||||
}
|
||||
|
||||
@Get(":idOrSlug")
|
||||
@UseGuards(OptionalAuthGuard)
|
||||
@UseInterceptors(CacheInterceptor)
|
||||
@CacheTTL(3600)
|
||||
@Header("Cache-Control", "public, max-age=3600")
|
||||
async findOne(
|
||||
@Param("idOrSlug") idOrSlug: string,
|
||||
@Req() req: Request,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
@Res() res: Response,
|
||||
) {
|
||||
const content = await this.contentsService.findOne(idOrSlug);
|
||||
const content = await this.contentsService.findOne(idOrSlug, req.user?.sub);
|
||||
if (!content) {
|
||||
throw new NotFoundException("Contenu non trouvé");
|
||||
}
|
||||
@@ -158,4 +178,11 @@ export class ContentsController {
|
||||
remove(@Param("id") id: string, @Req() req: AuthenticatedRequest) {
|
||||
return this.contentsService.remove(id, req.user.sub);
|
||||
}
|
||||
|
||||
@Delete(":id/admin")
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Roles("admin")
|
||||
removeAdmin(@Param("id") id: string) {
|
||||
return this.contentsService.removeAdmin(id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { CryptoModule } from "../crypto/crypto.module";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { MediaModule } from "../media/media.module";
|
||||
import { S3Module } from "../s3/s3.module";
|
||||
import { ContentsController } from "./contents.controller";
|
||||
@@ -9,8 +7,9 @@ import { ContentsService } from "./contents.service";
|
||||
import { ContentsRepository } from "./repositories/contents.repository";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, S3Module, AuthModule, CryptoModule, MediaModule],
|
||||
imports: [S3Module, AuthModule, MediaModule],
|
||||
controllers: [ContentsController],
|
||||
providers: [ContentsService, ContentsRepository],
|
||||
exports: [ContentsRepository],
|
||||
})
|
||||
export class ContentsModule {}
|
||||
|
||||
@@ -2,11 +2,10 @@ jest.mock("uuid", () => ({
|
||||
v4: jest.fn(() => "mocked-uuid"),
|
||||
}));
|
||||
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { DatabaseService } from "../database/database.service";
|
||||
import { MediaService } from "../media/media.service";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
import { ContentsService } from "./contents.service";
|
||||
@@ -31,6 +30,7 @@ describe("ContentsService", () => {
|
||||
const mockS3Service = {
|
||||
getUploadUrl: jest.fn(),
|
||||
uploadFile: jest.fn(),
|
||||
getPublicUrl: jest.fn(),
|
||||
};
|
||||
|
||||
const mockMediaService = {
|
||||
@@ -44,9 +44,7 @@ describe("ContentsService", () => {
|
||||
};
|
||||
|
||||
const mockCacheManager = {
|
||||
store: {
|
||||
keys: jest.fn().mockResolvedValue([]),
|
||||
},
|
||||
clear: jest.fn(),
|
||||
del: jest.fn(),
|
||||
};
|
||||
|
||||
@@ -141,7 +139,9 @@ describe("ContentsService", () => {
|
||||
|
||||
describe("incrementViews", () => {
|
||||
it("should increment views", async () => {
|
||||
mockContentsRepository.incrementViews.mockResolvedValue([{ id: "1", views: 1 }]);
|
||||
mockContentsRepository.incrementViews.mockResolvedValue([
|
||||
{ id: "1", views: 1 },
|
||||
]);
|
||||
const result = await service.incrementViews("1");
|
||||
expect(mockContentsRepository.incrementViews).toHaveBeenCalledWith("1");
|
||||
expect(result[0].views).toBe(1);
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { Cache } from "cache-manager";
|
||||
import { Inject } from "@nestjs/common";
|
||||
import {
|
||||
BadRequestException,
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import type { Cache } from "cache-manager";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import type { IMediaService } from "../common/interfaces/media.interface";
|
||||
import type {
|
||||
IMediaService,
|
||||
MediaProcessingResult,
|
||||
} from "../common/interfaces/media.interface";
|
||||
import type { IStorageService } from "../common/interfaces/storage.interface";
|
||||
import { MediaService } from "../media/media.service";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
import { CreateContentDto } from "./dto/create-content.dto";
|
||||
import { UploadContentDto } from "./dto/upload-content.dto";
|
||||
import { ContentsRepository } from "./repositories/contents.repository";
|
||||
|
||||
@Injectable()
|
||||
@@ -24,11 +33,7 @@ export class ContentsService {
|
||||
|
||||
private async clearContentsCache() {
|
||||
this.logger.log("Clearing contents cache");
|
||||
const keys = await this.cacheManager.store.keys();
|
||||
const contentsKeys = keys.filter((key) => key.startsWith("contents/"));
|
||||
for (const key of contentsKeys) {
|
||||
await this.cacheManager.del(key);
|
||||
}
|
||||
await this.cacheManager.clear();
|
||||
}
|
||||
|
||||
async getUploadUrl(userId: string, fileName: string) {
|
||||
@@ -40,12 +45,7 @@ export class ContentsService {
|
||||
async uploadAndProcess(
|
||||
userId: string,
|
||||
file: Express.Multer.File,
|
||||
data: {
|
||||
title: string;
|
||||
type: "meme" | "gif";
|
||||
categoryId?: string;
|
||||
tags?: string[];
|
||||
},
|
||||
data: UploadContentDto,
|
||||
) {
|
||||
this.logger.log(`Uploading and processing file for user ${userId}`);
|
||||
// 0. Validation du format et de la taille
|
||||
@@ -86,7 +86,7 @@ export class ContentsService {
|
||||
}
|
||||
|
||||
// 2. Transcodage
|
||||
let processed;
|
||||
let processed: MediaProcessingResult;
|
||||
if (file.mimetype.startsWith("image/")) {
|
||||
// Image ou GIF -> WebP (format moderne, bien supporté)
|
||||
processed = await this.mediaService.processImage(file.buffer, "webp");
|
||||
@@ -100,6 +100,7 @@ export class ContentsService {
|
||||
// 3. Upload vers S3
|
||||
const key = `contents/${userId}/${Date.now()}-${uuidv4()}.${processed.extension}`;
|
||||
await this.s3Service.uploadFile(key, processed.buffer, processed.mimeType);
|
||||
this.logger.log(`File uploaded successfully to S3: ${key}`);
|
||||
|
||||
// 4. Création en base de données
|
||||
return await this.create(userId, {
|
||||
@@ -126,10 +127,21 @@ export class ContentsService {
|
||||
this.contentsRepository.count(options),
|
||||
]);
|
||||
|
||||
return { data, totalCount };
|
||||
const processedData = data.map((content) => ({
|
||||
...content,
|
||||
url: this.s3Service.getPublicUrl(content.storageKey),
|
||||
author: {
|
||||
...content.author,
|
||||
avatarUrl: content.author?.avatarUrl
|
||||
? this.s3Service.getPublicUrl(content.author.avatarUrl)
|
||||
: null,
|
||||
},
|
||||
}));
|
||||
|
||||
return { data: processedData, totalCount };
|
||||
}
|
||||
|
||||
async create(userId: string, data: any) {
|
||||
async create(userId: string, data: CreateContentDto) {
|
||||
this.logger.log(`Creating content for user ${userId}: ${data.title}`);
|
||||
const { tags: tagNames, ...contentData } = data;
|
||||
|
||||
@@ -162,12 +174,34 @@ export class ContentsService {
|
||||
return deleted;
|
||||
}
|
||||
|
||||
async findOne(idOrSlug: string) {
|
||||
return this.contentsRepository.findOne(idOrSlug);
|
||||
async removeAdmin(id: string) {
|
||||
this.logger.log(`Removing content ${id} by admin`);
|
||||
const deleted = await this.contentsRepository.softDeleteAdmin(id);
|
||||
|
||||
if (deleted) {
|
||||
await this.clearContentsCache();
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
generateBotHtml(content: any): string {
|
||||
const imageUrl = this.getFileUrl(content.storageKey);
|
||||
async findOne(idOrSlug: string, userId?: string) {
|
||||
const content = await this.contentsRepository.findOne(idOrSlug, userId);
|
||||
if (!content) return null;
|
||||
|
||||
return {
|
||||
...content,
|
||||
url: this.s3Service.getPublicUrl(content.storageKey),
|
||||
author: {
|
||||
...content.author,
|
||||
avatarUrl: content.author?.avatarUrl
|
||||
? this.s3Service.getPublicUrl(content.author.avatarUrl)
|
||||
: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
generateBotHtml(content: { title: string; storageKey: string }): string {
|
||||
const imageUrl = this.s3Service.getPublicUrl(content.storageKey);
|
||||
return `<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
@@ -188,19 +222,6 @@ export class ContentsService {
|
||||
</html>`;
|
||||
}
|
||||
|
||||
getFileUrl(storageKey: string): string {
|
||||
const endpoint = this.configService.get("S3_ENDPOINT");
|
||||
const port = this.configService.get("S3_PORT");
|
||||
const protocol =
|
||||
this.configService.get("S3_USE_SSL") === true ? "https" : "http";
|
||||
const bucket = this.configService.get("S3_BUCKET_NAME");
|
||||
|
||||
if (endpoint === "localhost" || endpoint === "127.0.0.1") {
|
||||
return `${protocol}://${endpoint}:${port}/${bucket}/${storageKey}`;
|
||||
}
|
||||
return `${protocol}://${endpoint}/${bucket}/${storageKey}`;
|
||||
}
|
||||
|
||||
private generateSlug(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
MaxLength,
|
||||
} from "class-validator";
|
||||
|
||||
export enum ContentType {
|
||||
@@ -19,14 +20,17 @@ export class CreateContentDto {
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(255)
|
||||
title!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(512)
|
||||
storageKey!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(128)
|
||||
mimeType!: string;
|
||||
|
||||
@IsInt()
|
||||
@@ -39,5 +43,6 @@ export class CreateContentDto {
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@MaxLength(64, { each: true })
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import {
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
MaxLength,
|
||||
} from "class-validator";
|
||||
import { ContentType } from "./create-content.dto";
|
||||
|
||||
@@ -13,6 +15,7 @@ export class UploadContentDto {
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(255)
|
||||
title!: string;
|
||||
|
||||
@IsOptional()
|
||||
@@ -20,6 +23,8 @@ export class UploadContentDto {
|
||||
categoryId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@MaxLength(64, { each: true })
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
exists,
|
||||
ilike,
|
||||
isNull,
|
||||
sql,
|
||||
lte,
|
||||
type SQL,
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
import { DatabaseService } from "../../database/database.service";
|
||||
import {
|
||||
@@ -113,10 +113,7 @@ export class ContentsRepository {
|
||||
.select()
|
||||
.from(favorites)
|
||||
.where(
|
||||
and(
|
||||
eq(favorites.contentId, contents.id),
|
||||
eq(favorites.userId, userId),
|
||||
),
|
||||
and(eq(favorites.contentId, contents.id), eq(favorites.userId, userId)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -138,11 +135,19 @@ export class ContentsRepository {
|
||||
fileSize: contents.fileSize,
|
||||
views: contents.views,
|
||||
usageCount: contents.usageCount,
|
||||
favoritesCount:
|
||||
sql<number>`(SELECT count(*) FROM ${favorites} WHERE ${favorites.contentId} = ${contents.id})`.mapWith(
|
||||
Number,
|
||||
),
|
||||
isLiked: userId
|
||||
? sql<boolean>`EXISTS(SELECT 1 FROM ${favorites} WHERE ${favorites.contentId} = ${contents.id} AND ${favorites.userId} = ${userId})`
|
||||
: sql<boolean>`false`,
|
||||
createdAt: contents.createdAt,
|
||||
updatedAt: contents.updatedAt,
|
||||
author: {
|
||||
id: users.uuid,
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
},
|
||||
category: {
|
||||
@@ -173,18 +178,13 @@ export class ContentsRepository {
|
||||
|
||||
return results.map((r) => ({
|
||||
...r,
|
||||
tags: tagsForContents
|
||||
.filter((t) => t.contentId === r.id)
|
||||
.map((t) => t.name),
|
||||
tags: tagsForContents.filter((t) => t.contentId === r.id).map((t) => t.name),
|
||||
}));
|
||||
}
|
||||
|
||||
async create(data: NewContentInDb & { userId: string }, tagNames?: string[]) {
|
||||
return await this.databaseService.db.transaction(async (tx) => {
|
||||
const [newContent] = await tx
|
||||
.insert(contents)
|
||||
.values(data)
|
||||
.returning();
|
||||
const [newContent] = await tx.insert(contents).values(data).returning();
|
||||
|
||||
if (tagNames && tagNames.length > 0) {
|
||||
for (const tagName of tagNames) {
|
||||
@@ -224,7 +224,7 @@ export class ContentsRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async findOne(idOrSlug: string) {
|
||||
async findOne(idOrSlug: string, userId?: string) {
|
||||
const [result] = await this.databaseService.db
|
||||
.select({
|
||||
id: contents.id,
|
||||
@@ -236,11 +236,31 @@ export class ContentsRepository {
|
||||
fileSize: contents.fileSize,
|
||||
views: contents.views,
|
||||
usageCount: contents.usageCount,
|
||||
favoritesCount:
|
||||
sql<number>`(SELECT count(*) FROM ${favorites} WHERE ${favorites.contentId} = ${contents.id})`.mapWith(
|
||||
Number,
|
||||
),
|
||||
isLiked: userId
|
||||
? sql<boolean>`EXISTS(SELECT 1 FROM ${favorites} WHERE ${favorites.contentId} = ${contents.id} AND ${favorites.userId} = ${userId})`
|
||||
: sql<boolean>`false`,
|
||||
createdAt: contents.createdAt,
|
||||
updatedAt: contents.updatedAt,
|
||||
userId: contents.userId,
|
||||
author: {
|
||||
id: users.uuid,
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
},
|
||||
category: {
|
||||
id: categories.id,
|
||||
name: categories.name,
|
||||
slug: categories.slug,
|
||||
},
|
||||
})
|
||||
.from(contents)
|
||||
.leftJoin(users, eq(contents.userId, users.uuid))
|
||||
.leftJoin(categories, eq(contents.categoryId, categories.id))
|
||||
.where(
|
||||
and(
|
||||
isNull(contents.deletedAt),
|
||||
@@ -249,7 +269,20 @@ export class ContentsRepository {
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
return result;
|
||||
if (!result) return null;
|
||||
|
||||
const tagsForContent = await this.databaseService.db
|
||||
.select({
|
||||
name: tags.name,
|
||||
})
|
||||
.from(contentsToTags)
|
||||
.innerJoin(tags, eq(contentsToTags.tagId, tags.id))
|
||||
.where(eq(contentsToTags.contentId, result.id));
|
||||
|
||||
return {
|
||||
...result,
|
||||
tags: tagsForContent.map((t) => t.name),
|
||||
};
|
||||
}
|
||||
|
||||
async count(options: {
|
||||
@@ -325,10 +358,7 @@ export class ContentsRepository {
|
||||
.select()
|
||||
.from(favorites)
|
||||
.where(
|
||||
and(
|
||||
eq(favorites.contentId, contents.id),
|
||||
eq(favorites.userId, userId),
|
||||
),
|
||||
and(eq(favorites.contentId, contents.id), eq(favorites.userId, userId)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -365,6 +395,15 @@ export class ContentsRepository {
|
||||
return deleted;
|
||||
}
|
||||
|
||||
async softDeleteAdmin(id: string) {
|
||||
const [deleted] = await this.databaseService.db
|
||||
.update(contents)
|
||||
.set({ deletedAt: new Date() })
|
||||
.where(eq(contents.id, id))
|
||||
.returning();
|
||||
return deleted;
|
||||
}
|
||||
|
||||
async findBySlug(slug: string) {
|
||||
const [result] = await this.databaseService.db
|
||||
.select()
|
||||
@@ -377,7 +416,12 @@ export class ContentsRepository {
|
||||
async purgeSoftDeleted(before: Date) {
|
||||
return await this.databaseService.db
|
||||
.delete(contents)
|
||||
.where(and(sql`${contents.deletedAt} IS NOT NULL`, lte(contents.deletedAt, before)))
|
||||
.where(
|
||||
and(
|
||||
sql`${contents.deletedAt} IS NOT NULL`,
|
||||
lte(contents.deletedAt, before),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { CryptoService } from "./crypto.service";
|
||||
import { EncryptionService } from "./services/encryption.service";
|
||||
import { HashingService } from "./services/hashing.service";
|
||||
import { JwtService } from "./services/jwt.service";
|
||||
import { EncryptionService } from "./services/encryption.service";
|
||||
import { PostQuantumService } from "./services/post-quantum.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [
|
||||
CryptoService,
|
||||
|
||||
@@ -64,9 +64,9 @@ jest.mock("jose", () => ({
|
||||
}));
|
||||
|
||||
import { CryptoService } from "./crypto.service";
|
||||
import { EncryptionService } from "./services/encryption.service";
|
||||
import { HashingService } from "./services/hashing.service";
|
||||
import { JwtService } from "./services/jwt.service";
|
||||
import { EncryptionService } from "./services/encryption.service";
|
||||
import { PostQuantumService } from "./services/post-quantum.service";
|
||||
|
||||
describe("CryptoService", () => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { Global, Module } from "@nestjs/common";
|
||||
import { ConfigModule } from "@nestjs/config";
|
||||
import { DatabaseService } from "./database.service";
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
imports: [ConfigModule],
|
||||
providers: [DatabaseService],
|
||||
|
||||
@@ -3,9 +3,9 @@ export * from "./audit_logs";
|
||||
export * from "./categories";
|
||||
export * from "./content";
|
||||
export * from "./favorites";
|
||||
export * from "./pgp";
|
||||
export * from "./rbac";
|
||||
export * from "./reports";
|
||||
export * from "./sessions";
|
||||
export * from "./tags";
|
||||
export * from "./users";
|
||||
export * from "./pgp";
|
||||
|
||||
@@ -55,6 +55,9 @@ export function pgpSymEncrypt(value: string | SQL, key: string | SQL) {
|
||||
/**
|
||||
* @deprecated Utiliser directement les colonnes de type pgpEncrypted qui gèrent maintenant le déchiffrement automatiquement.
|
||||
*/
|
||||
export function pgpSymDecrypt(column: AnyPgColumn, key: string | SQL): SQL<string> {
|
||||
export function pgpSymDecrypt(
|
||||
column: AnyPgColumn,
|
||||
key: string | SQL,
|
||||
): SQL<string> {
|
||||
return sql`pgp_sym_decrypt(${column}, ${key})`.mapWith(column) as SQL<string>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { SQL, sql } from "drizzle-orm";
|
||||
import {
|
||||
boolean,
|
||||
index,
|
||||
@@ -30,7 +29,9 @@ export const users = pgTable(
|
||||
displayName: varchar("display_name", { length: 32 }),
|
||||
|
||||
username: varchar("username", { length: 32 }).notNull().unique(),
|
||||
passwordHash: varchar("password_hash", { length: 72 }).notNull(),
|
||||
passwordHash: varchar("password_hash", { length: 100 }).notNull(),
|
||||
avatarUrl: varchar("avatar_url", { length: 512 }),
|
||||
bio: varchar("bio", { length: 255 }),
|
||||
|
||||
// Sécurité
|
||||
twoFactorSecret: pgpEncrypted("two_factor_secret"),
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { FavoritesController } from "./favorites.controller";
|
||||
import { FavoritesService } from "./favorites.service";
|
||||
import { FavoritesRepository } from "./repositories/favorites.repository";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule],
|
||||
imports: [AuthModule],
|
||||
controllers: [FavoritesController],
|
||||
providers: [FavoritesService, FavoritesRepository],
|
||||
exports: [FavoritesService],
|
||||
exports: [FavoritesService, FavoritesRepository],
|
||||
})
|
||||
export class FavoritesModule {}
|
||||
|
||||
@@ -34,7 +34,9 @@ describe("FavoritesService", () => {
|
||||
|
||||
describe("addFavorite", () => {
|
||||
it("should add a favorite", async () => {
|
||||
mockFavoritesRepository.findContentById.mockResolvedValue({ id: "content1" });
|
||||
mockFavoritesRepository.findContentById.mockResolvedValue({
|
||||
id: "content1",
|
||||
});
|
||||
mockFavoritesRepository.add.mockResolvedValue([
|
||||
{ userId: "u1", contentId: "content1" },
|
||||
]);
|
||||
@@ -53,7 +55,9 @@ describe("FavoritesService", () => {
|
||||
});
|
||||
|
||||
it("should throw ConflictException on duplicate favorite", async () => {
|
||||
mockFavoritesRepository.findContentById.mockResolvedValue({ id: "content1" });
|
||||
mockFavoritesRepository.findContentById.mockResolvedValue({
|
||||
id: "content1",
|
||||
});
|
||||
mockFavoritesRepository.add.mockRejectedValue(new Error("Duplicate"));
|
||||
await expect(service.addFavorite("u1", "content1")).rejects.toThrow(
|
||||
ConflictException,
|
||||
@@ -63,7 +67,9 @@ describe("FavoritesService", () => {
|
||||
|
||||
describe("removeFavorite", () => {
|
||||
it("should remove a favorite", async () => {
|
||||
mockFavoritesRepository.remove.mockResolvedValue([{ userId: "u1", contentId: "c1" }]);
|
||||
mockFavoritesRepository.remove.mockResolvedValue([
|
||||
{ userId: "u1", contentId: "c1" },
|
||||
]);
|
||||
const result = await service.removeFavorite("u1", "c1");
|
||||
expect(result).toEqual({ userId: "u1", contentId: "c1" });
|
||||
expect(repository.remove).toHaveBeenCalledWith("u1", "c1");
|
||||
|
||||
@@ -14,7 +14,7 @@ export class FavoritesService {
|
||||
|
||||
async addFavorite(userId: string, contentId: string) {
|
||||
this.logger.log(`Adding favorite: user ${userId}, content ${contentId}`);
|
||||
|
||||
|
||||
const content = await this.favoritesRepository.findContentById(contentId);
|
||||
if (!content) {
|
||||
throw new NotFoundException("Content not found");
|
||||
|
||||
@@ -24,14 +24,31 @@ async function bootstrap() {
|
||||
}
|
||||
|
||||
// Sécurité
|
||||
app.use(helmet());
|
||||
app.enableCors({
|
||||
origin:
|
||||
configService.get("NODE_ENV") === "production"
|
||||
? [configService.get("DOMAIN_NAME") as string]
|
||||
: true,
|
||||
credentials: true,
|
||||
});
|
||||
app.use(
|
||||
helmet({
|
||||
crossOriginResourcePolicy: { policy: "cross-origin" },
|
||||
}),
|
||||
);
|
||||
const corsEnabled = Boolean(configService.get<boolean>("ENABLE_CORS"));
|
||||
if (corsEnabled) {
|
||||
const domainName = configService.get<string>("CORS_DOMAIN_NAME");
|
||||
app.enableCors({
|
||||
origin: (origin, callback) => {
|
||||
if (!origin || domainName === "*") {
|
||||
callback(null, true);
|
||||
return;
|
||||
}
|
||||
|
||||
const allowedOrigins = domainName?.split(",").map((o) => o.trim()) || [];
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
callback(null, true);
|
||||
} else {
|
||||
callback(null, false);
|
||||
}
|
||||
},
|
||||
credentials: true,
|
||||
});
|
||||
}
|
||||
|
||||
// Validation Globale
|
||||
app.useGlobalPipes(
|
||||
@@ -49,4 +66,4 @@ async function bootstrap() {
|
||||
await app.listen(port);
|
||||
logger.log(`Application is running on: http://localhost:${port}`);
|
||||
}
|
||||
bootstrap();
|
||||
bootstrap().then();
|
||||
|
||||
61
backend/src/media/media.controller.spec.ts
Normal file
61
backend/src/media/media.controller.spec.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { Readable } from "node:stream";
|
||||
import { NotFoundException } from "@nestjs/common";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import type { Response } from "express";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
import { MediaController } from "./media.controller";
|
||||
|
||||
describe("MediaController", () => {
|
||||
let controller: MediaController;
|
||||
|
||||
const mockS3Service = {
|
||||
getFileInfo: jest.fn(),
|
||||
getFile: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [MediaController],
|
||||
providers: [{ provide: S3Service, useValue: mockS3Service }],
|
||||
}).compile();
|
||||
|
||||
controller = module.get<MediaController>(MediaController);
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
expect(controller).toBeDefined();
|
||||
});
|
||||
|
||||
describe("getFile", () => {
|
||||
it("should stream the file and set headers with path containing slashes", async () => {
|
||||
const res = {
|
||||
setHeader: jest.fn(),
|
||||
} as unknown as Response;
|
||||
const stream = new Readable();
|
||||
stream.pipe = jest.fn();
|
||||
const key = "contents/user-id/test.webp";
|
||||
|
||||
mockS3Service.getFileInfo.mockResolvedValue({
|
||||
size: 100,
|
||||
metaData: { "content-type": "image/webp" },
|
||||
});
|
||||
mockS3Service.getFile.mockResolvedValue(stream);
|
||||
|
||||
await controller.getFile(key, res);
|
||||
|
||||
expect(mockS3Service.getFileInfo).toHaveBeenCalledWith(key);
|
||||
expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "image/webp");
|
||||
expect(res.setHeader).toHaveBeenCalledWith("Content-Length", 100);
|
||||
expect(stream.pipe).toHaveBeenCalledWith(res);
|
||||
});
|
||||
|
||||
it("should throw NotFoundException if file is not found", async () => {
|
||||
mockS3Service.getFileInfo.mockRejectedValue(new Error("Not found"));
|
||||
const res = {} as unknown as Response;
|
||||
|
||||
await expect(controller.getFile("invalid", res)).rejects.toThrow(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
30
backend/src/media/media.controller.ts
Normal file
30
backend/src/media/media.controller.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { Controller, Get, NotFoundException, Param, Res } from "@nestjs/common";
|
||||
import type { Response } from "express";
|
||||
import type { BucketItemStat } from "minio";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
|
||||
@Controller("media")
|
||||
export class MediaController {
|
||||
constructor(private readonly s3Service: S3Service) {}
|
||||
|
||||
@Get("*key")
|
||||
async getFile(@Param("key") key: string, @Res() res: Response) {
|
||||
try {
|
||||
const stats = (await this.s3Service.getFileInfo(key)) as BucketItemStat;
|
||||
const stream = await this.s3Service.getFile(key);
|
||||
|
||||
const contentType =
|
||||
stats.metaData?.["content-type"] ||
|
||||
stats.metadata?.["content-type"] ||
|
||||
"application/octet-stream";
|
||||
|
||||
res.setHeader("Content-Type", contentType);
|
||||
res.setHeader("Content-Length", stats.size);
|
||||
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||
|
||||
stream.pipe(res);
|
||||
} catch (_error) {
|
||||
throw new NotFoundException("Fichier non trouvé");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { S3Module } from "../s3/s3.module";
|
||||
import { MediaController } from "./media.controller";
|
||||
import { MediaService } from "./media.service";
|
||||
import { ImageProcessorStrategy } from "./strategies/image-processor.strategy";
|
||||
import { VideoProcessorStrategy } from "./strategies/video-processor.strategy";
|
||||
|
||||
@Module({
|
||||
imports: [S3Module],
|
||||
controllers: [MediaController],
|
||||
providers: [MediaService, ImageProcessorStrategy, VideoProcessorStrategy],
|
||||
exports: [MediaService],
|
||||
})
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
Logger,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import * as NodeClam from "clamscan";
|
||||
import NodeClam from "clamscan";
|
||||
import type {
|
||||
IMediaService,
|
||||
MediaProcessingResult,
|
||||
@@ -83,8 +83,9 @@ export class MediaService implements IMediaService {
|
||||
async processImage(
|
||||
buffer: Buffer,
|
||||
format: "webp" | "avif" = "webp",
|
||||
resize?: { width?: number; height?: number },
|
||||
): Promise<MediaProcessingResult> {
|
||||
return this.imageProcessor.process(buffer, { format });
|
||||
return this.imageProcessor.process(buffer, { format, resize });
|
||||
}
|
||||
|
||||
async processVideo(
|
||||
|
||||
@@ -13,11 +13,22 @@ export class ImageProcessorStrategy implements IMediaProcessorStrategy {
|
||||
|
||||
async process(
|
||||
buffer: Buffer,
|
||||
options: { format: "webp" | "avif" } = { format: "webp" },
|
||||
options: {
|
||||
format: "webp" | "avif";
|
||||
resize?: { width?: number; height?: number };
|
||||
} = { format: "webp" },
|
||||
): Promise<MediaProcessingResult> {
|
||||
try {
|
||||
const { format } = options;
|
||||
const { format, resize } = options;
|
||||
let pipeline = sharp(buffer);
|
||||
|
||||
if (resize) {
|
||||
pipeline = pipeline.resize(resize.width, resize.height, {
|
||||
fit: "cover",
|
||||
position: "center",
|
||||
});
|
||||
}
|
||||
|
||||
const metadata = await pipeline.metadata();
|
||||
|
||||
if (format === "webp") {
|
||||
|
||||
@@ -2,5 +2,8 @@ import type { MediaProcessingResult } from "../../common/interfaces/media.interf
|
||||
|
||||
export interface IMediaProcessorStrategy {
|
||||
canHandle(mimeType: string): boolean;
|
||||
process(buffer: Buffer, options?: any): Promise<MediaProcessingResult>;
|
||||
process(
|
||||
buffer: Buffer,
|
||||
options?: Record<string, unknown>,
|
||||
): Promise<MediaProcessingResult>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { IsEnum, IsOptional, IsString, IsUUID } from "class-validator";
|
||||
import {
|
||||
IsEnum,
|
||||
IsOptional,
|
||||
IsString,
|
||||
IsUUID,
|
||||
MaxLength,
|
||||
} from "class-validator";
|
||||
|
||||
export enum ReportReason {
|
||||
INAPPROPRIATE = "inappropriate",
|
||||
@@ -21,5 +27,6 @@ export class CreateReportDto {
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(1000)
|
||||
description?: string;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { forwardRef, Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { CryptoModule } from "../crypto/crypto.module";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { ReportsController } from "./reports.controller";
|
||||
import { ReportsService } from "./reports.service";
|
||||
import { ReportsRepository } from "./repositories/reports.repository";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, AuthModule, CryptoModule],
|
||||
imports: [forwardRef(() => AuthModule)],
|
||||
controllers: [ReportsController],
|
||||
providers: [ReportsService, ReportsRepository],
|
||||
exports: [ReportsRepository, ReportsService],
|
||||
})
|
||||
export class ReportsModule {}
|
||||
|
||||
@@ -33,8 +33,12 @@ describe("ReportsService", () => {
|
||||
describe("create", () => {
|
||||
it("should create a report", async () => {
|
||||
const reporterId = "u1";
|
||||
const data = { contentId: "c1", reason: "spam" };
|
||||
mockReportsRepository.create.mockResolvedValue({ id: "r1", ...data, reporterId });
|
||||
const data = { contentId: "c1", reason: "spam" } as const;
|
||||
mockReportsRepository.create.mockResolvedValue({
|
||||
id: "r1",
|
||||
...data,
|
||||
reporterId,
|
||||
});
|
||||
|
||||
const result = await service.create(reporterId, data);
|
||||
|
||||
@@ -54,7 +58,9 @@ describe("ReportsService", () => {
|
||||
|
||||
describe("updateStatus", () => {
|
||||
it("should update report status", async () => {
|
||||
mockReportsRepository.updateStatus.mockResolvedValue([{ id: "r1", status: "resolved" }]);
|
||||
mockReportsRepository.updateStatus.mockResolvedValue([
|
||||
{ id: "r1", status: "resolved" },
|
||||
]);
|
||||
const result = await service.updateStatus("r1", "resolved");
|
||||
expect(result[0].status).toBe("resolved");
|
||||
expect(repository.updateStatus).toHaveBeenCalledWith("r1", "resolved");
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { ReportsRepository } from "./repositories/reports.repository";
|
||||
import { CreateReportDto } from "./dto/create-report.dto";
|
||||
import { ReportsRepository } from "./repositories/reports.repository";
|
||||
|
||||
@Injectable()
|
||||
export class ReportsService {
|
||||
|
||||
@@ -11,7 +11,7 @@ export class ReportsRepository {
|
||||
reporterId: string;
|
||||
contentId?: string;
|
||||
tagId?: string;
|
||||
reason: string;
|
||||
reason: "inappropriate" | "spam" | "copyright" | "other";
|
||||
description?: string;
|
||||
}) {
|
||||
const [newReport] = await this.databaseService.db
|
||||
|
||||
@@ -7,7 +7,7 @@ jest.mock("minio");
|
||||
|
||||
describe("S3Service", () => {
|
||||
let service: S3Service;
|
||||
let _configService: ConfigService;
|
||||
let configService: ConfigService;
|
||||
// biome-ignore lint/suspicious/noExplicitAny: Fine for testing purposes
|
||||
let minioClient: any;
|
||||
|
||||
@@ -42,7 +42,7 @@ describe("S3Service", () => {
|
||||
}).compile();
|
||||
|
||||
service = module.get<S3Service>(S3Service);
|
||||
_configService = module.get<ConfigService>(ConfigService);
|
||||
configService = module.get<ConfigService>(ConfigService);
|
||||
});
|
||||
|
||||
it("should be defined", () => {
|
||||
@@ -185,35 +185,39 @@ describe("S3Service", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("moveFile", () => {
|
||||
it("should move file within default bucket", async () => {
|
||||
const source = "source.txt";
|
||||
const dest = "dest.txt";
|
||||
await service.moveFile(source, dest);
|
||||
|
||||
expect(minioClient.copyObject).toHaveBeenCalledWith(
|
||||
"memegoat",
|
||||
dest,
|
||||
"/memegoat/source.txt",
|
||||
expect.any(Minio.CopyConditions),
|
||||
);
|
||||
expect(minioClient.removeObject).toHaveBeenCalledWith("memegoat", source);
|
||||
describe("getPublicUrl", () => {
|
||||
it("should use API_URL if provided", () => {
|
||||
(configService.get as jest.Mock).mockImplementation((key: string) => {
|
||||
if (key === "API_URL") return "https://api.test.com";
|
||||
return null;
|
||||
});
|
||||
const url = service.getPublicUrl("test.webp");
|
||||
expect(url).toBe("https://api.test.com/media/test.webp");
|
||||
});
|
||||
|
||||
it("should move file between different buckets", async () => {
|
||||
const source = "source.txt";
|
||||
const dest = "dest.txt";
|
||||
const sBucket = "source-bucket";
|
||||
const dBucket = "dest-bucket";
|
||||
await service.moveFile(source, dest, sBucket, dBucket);
|
||||
|
||||
expect(minioClient.copyObject).toHaveBeenCalledWith(
|
||||
dBucket,
|
||||
dest,
|
||||
`/${sBucket}/${source}`,
|
||||
expect.any(Minio.CopyConditions),
|
||||
it("should use DOMAIN_NAME and PORT for localhost", () => {
|
||||
(configService.get as jest.Mock).mockImplementation(
|
||||
(key: string, def: unknown) => {
|
||||
if (key === "API_URL") return null;
|
||||
if (key === "DOMAIN_NAME") return "localhost";
|
||||
if (key === "PORT") return 3000;
|
||||
return def;
|
||||
},
|
||||
);
|
||||
expect(minioClient.removeObject).toHaveBeenCalledWith(sBucket, source);
|
||||
const url = service.getPublicUrl("test.webp");
|
||||
expect(url).toBe("http://localhost:3000/media/test.webp");
|
||||
});
|
||||
|
||||
it("should use api.DOMAIN_NAME for production", () => {
|
||||
(configService.get as jest.Mock).mockImplementation(
|
||||
(key: string, def: unknown) => {
|
||||
if (key === "API_URL") return null;
|
||||
if (key === "DOMAIN_NAME") return "memegoat.fr";
|
||||
return def;
|
||||
},
|
||||
);
|
||||
const url = service.getPublicUrl("test.webp");
|
||||
expect(url).toBe("https://api.memegoat.fr/media/test.webp");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -54,6 +54,7 @@ export class S3Service implements OnModuleInit, IStorageService {
|
||||
...metaData,
|
||||
"Content-Type": mimeType,
|
||||
});
|
||||
this.logger.log(`File uploaded successfully: ${fileName} to ${bucketName}`);
|
||||
return fileName;
|
||||
} catch (error) {
|
||||
this.logger.error(`Error uploading file to ${bucketName}: ${error.message}`);
|
||||
@@ -113,6 +114,7 @@ export class S3Service implements OnModuleInit, IStorageService {
|
||||
async deleteFile(fileName: string, bucketName: string = this.bucketName) {
|
||||
try {
|
||||
await this.minioClient.removeObject(bucketName, fileName);
|
||||
this.logger.log(`File deleted successfully: ${fileName} from ${bucketName}`);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Error deleting file from ${bucketName}: ${error.message}`,
|
||||
@@ -155,4 +157,22 @@ export class S3Service implements OnModuleInit, IStorageService {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
getPublicUrl(storageKey: string): string {
|
||||
const apiUrl = this.configService.get<string>("API_URL");
|
||||
const domain = this.configService.get<string>("DOMAIN_NAME", "localhost");
|
||||
const port = this.configService.get<number>("PORT", 3000);
|
||||
|
||||
let baseUrl: string;
|
||||
|
||||
if (apiUrl) {
|
||||
baseUrl = apiUrl.replace(/\/$/, "");
|
||||
} else if (domain === "localhost" || domain === "127.0.0.1") {
|
||||
baseUrl = `http://${domain}:${port}`;
|
||||
} else {
|
||||
baseUrl = `https://api.${domain}`;
|
||||
}
|
||||
|
||||
return `${baseUrl}/media/${storageKey}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ export class SessionsRepository {
|
||||
return result[0] || null;
|
||||
}
|
||||
|
||||
async update(sessionId: string, data: any) {
|
||||
async update(sessionId: string, data: Record<string, unknown>) {
|
||||
const [updatedSession] = await this.databaseService.db
|
||||
.update(sessions)
|
||||
.set({ ...data, updatedAt: new Date() })
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { CryptoModule } from "../crypto/crypto.module";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { SessionsService } from "./sessions.service";
|
||||
import { SessionsRepository } from "./repositories/sessions.repository";
|
||||
import { SessionsService } from "./sessions.service";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, CryptoModule],
|
||||
providers: [SessionsService, SessionsRepository],
|
||||
exports: [SessionsService],
|
||||
exports: [SessionsService, SessionsRepository],
|
||||
})
|
||||
export class SessionsModule {}
|
||||
|
||||
@@ -15,8 +15,8 @@ import { UnauthorizedException } from "@nestjs/common";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { HashingService } from "../crypto/services/hashing.service";
|
||||
import { JwtService } from "../crypto/services/jwt.service";
|
||||
import { SessionsService } from "./sessions.service";
|
||||
import { SessionsRepository } from "./repositories/sessions.repository";
|
||||
import { SessionsService } from "./sessions.service";
|
||||
|
||||
describe("SessionsService", () => {
|
||||
let service: SessionsService;
|
||||
@@ -76,7 +76,10 @@ describe("SessionsService", () => {
|
||||
userId: "u1",
|
||||
expiresAt,
|
||||
});
|
||||
mockSessionsRepository.update.mockResolvedValue({ id: "s1", refreshToken: "new-token" });
|
||||
mockSessionsRepository.update.mockResolvedValue({
|
||||
id: "s1",
|
||||
refreshToken: "new-token",
|
||||
});
|
||||
|
||||
const result = await service.refreshSession("old-token");
|
||||
|
||||
|
||||
@@ -30,7 +30,8 @@ export class SessionsService {
|
||||
}
|
||||
|
||||
async refreshSession(oldRefreshToken: string) {
|
||||
const session = await this.sessionsRepository.findValidByRefreshToken(oldRefreshToken);
|
||||
const session =
|
||||
await this.sessionsRepository.findValidByRefreshToken(oldRefreshToken);
|
||||
|
||||
if (!session || session.expiresAt < new Date()) {
|
||||
if (session) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { CacheInterceptor, CacheTTL } from "@nestjs/cache-manager";
|
||||
import {
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
@@ -6,7 +7,6 @@ import {
|
||||
Query,
|
||||
UseInterceptors,
|
||||
} from "@nestjs/common";
|
||||
import { CacheInterceptor, CacheTTL } from "@nestjs/cache-manager";
|
||||
import { TagsService } from "./tags.service";
|
||||
|
||||
@Controller("tags")
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { TagsRepository } from "./repositories/tags.repository";
|
||||
import { TagsController } from "./tags.controller";
|
||||
import { TagsService } from "./tags.service";
|
||||
import { TagsRepository } from "./repositories/tags.repository";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule],
|
||||
imports: [AuthModule],
|
||||
controllers: [TagsController],
|
||||
providers: [TagsService, TagsRepository],
|
||||
exports: [TagsService],
|
||||
exports: [TagsService, TagsRepository],
|
||||
})
|
||||
export class TagsModule {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { TagsService } from "./tags.service";
|
||||
import { TagsRepository } from "./repositories/tags.repository";
|
||||
import { TagsService } from "./tags.service";
|
||||
|
||||
describe("TagsService", () => {
|
||||
let service: TagsService;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { IsNotEmpty, IsString } from "class-validator";
|
||||
import { IsNotEmpty, IsString, MaxLength } from "class-validator";
|
||||
|
||||
export class UpdateConsentDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(16)
|
||||
termsVersion!: string;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(16)
|
||||
privacyVersion!: string;
|
||||
}
|
||||
|
||||
@@ -5,4 +5,13 @@ export class UpdateUserDto {
|
||||
@IsString()
|
||||
@MaxLength(32)
|
||||
displayName?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
bio?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
avatarUrl?: string;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { and, eq, lte, sql } from "drizzle-orm";
|
||||
import { DatabaseService } from "../../database/database.service";
|
||||
import { users, contents, favorites } from "../../database/schemas";
|
||||
import type { UpdateUserDto } from "../dto/update-user.dto";
|
||||
import { contents, favorites, users } from "../../database/schemas";
|
||||
|
||||
@Injectable()
|
||||
export class UsersRepository {
|
||||
@@ -44,6 +43,8 @@ export class UsersRepository {
|
||||
username: users.username,
|
||||
email: users.email,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
bio: users.bio,
|
||||
status: users.status,
|
||||
isTwoFactorEnabled: users.isTwoFactorEnabled,
|
||||
createdAt: users.createdAt,
|
||||
@@ -67,7 +68,9 @@ export class UsersRepository {
|
||||
.select({
|
||||
uuid: users.uuid,
|
||||
username: users.username,
|
||||
email: users.email,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
status: users.status,
|
||||
createdAt: users.createdAt,
|
||||
})
|
||||
@@ -82,6 +85,8 @@ export class UsersRepository {
|
||||
uuid: users.uuid,
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
avatarUrl: users.avatarUrl,
|
||||
bio: users.bio,
|
||||
createdAt: users.createdAt,
|
||||
})
|
||||
.from(users)
|
||||
@@ -99,7 +104,7 @@ export class UsersRepository {
|
||||
return result[0] || null;
|
||||
}
|
||||
|
||||
async update(uuid: string, data: any) {
|
||||
async update(uuid: string, data: Partial<typeof users.$inferInsert>) {
|
||||
return await this.databaseService.db
|
||||
.update(users)
|
||||
.set({ ...data, updatedAt: new Date() })
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { CacheInterceptor, CacheTTL } from "@nestjs/cache-manager";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
DefaultValuePipe,
|
||||
Delete,
|
||||
forwardRef,
|
||||
Get,
|
||||
Inject,
|
||||
Param,
|
||||
ParseIntPipe,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UploadedFile,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
} from "@nestjs/common";
|
||||
import { CacheInterceptor, CacheKey, CacheTTL } from "@nestjs/cache-manager";
|
||||
import { FileInterceptor } from "@nestjs/platform-express";
|
||||
import { AuthService } from "../auth/auth.service";
|
||||
import { Roles } from "../auth/decorators/roles.decorator";
|
||||
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||
@@ -27,6 +31,7 @@ import { UsersService } from "./users.service";
|
||||
export class UsersController {
|
||||
constructor(
|
||||
private readonly usersService: UsersService,
|
||||
@Inject(forwardRef(() => AuthService))
|
||||
private readonly authService: AuthService,
|
||||
) {}
|
||||
|
||||
@@ -71,6 +76,16 @@ export class UsersController {
|
||||
return this.usersService.update(req.user.sub, updateUserDto);
|
||||
}
|
||||
|
||||
@Post("me/avatar")
|
||||
@UseGuards(AuthGuard)
|
||||
@UseInterceptors(FileInterceptor("file"))
|
||||
updateAvatar(
|
||||
@Req() req: AuthenticatedRequest,
|
||||
@UploadedFile() file: Express.Multer.File,
|
||||
) {
|
||||
return this.usersService.updateAvatar(req.user.sub, file);
|
||||
}
|
||||
|
||||
@Patch("me/consent")
|
||||
@UseGuards(AuthGuard)
|
||||
updateConsent(
|
||||
@@ -90,6 +105,13 @@ export class UsersController {
|
||||
return this.usersService.remove(req.user.sub);
|
||||
}
|
||||
|
||||
@Delete(":uuid")
|
||||
@UseGuards(AuthGuard, RolesGuard)
|
||||
@Roles("admin")
|
||||
removeAdmin(@Param("uuid") uuid: string) {
|
||||
return this.usersService.remove(uuid);
|
||||
}
|
||||
|
||||
// Double Authentification (2FA)
|
||||
@Post("me/2fa/setup")
|
||||
@UseGuards(AuthGuard)
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { forwardRef, Module } from "@nestjs/common";
|
||||
import { AuthModule } from "../auth/auth.module";
|
||||
import { CryptoModule } from "../crypto/crypto.module";
|
||||
import { DatabaseModule } from "../database/database.module";
|
||||
import { MediaModule } from "../media/media.module";
|
||||
import { S3Module } from "../s3/s3.module";
|
||||
import { UsersRepository } from "./repositories/users.repository";
|
||||
import { UsersController } from "./users.controller";
|
||||
import { UsersService } from "./users.service";
|
||||
import { UsersRepository } from "./repositories/users.repository";
|
||||
|
||||
@Module({
|
||||
imports: [DatabaseModule, CryptoModule, AuthModule],
|
||||
imports: [forwardRef(() => AuthModule), MediaModule, S3Module],
|
||||
controllers: [UsersController],
|
||||
providers: [UsersService, UsersRepository],
|
||||
exports: [UsersService],
|
||||
exports: [UsersService, UsersRepository],
|
||||
})
|
||||
export class UsersModule {}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
jest.mock("uuid", () => ({
|
||||
v4: jest.fn(() => "mocked-uuid"),
|
||||
}));
|
||||
|
||||
jest.mock("@noble/post-quantum/ml-kem.js", () => ({
|
||||
ml_kem768: {
|
||||
keygen: jest.fn(),
|
||||
@@ -11,10 +15,14 @@ jest.mock("jose", () => ({
|
||||
jwtVerify: jest.fn(),
|
||||
}));
|
||||
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { UsersService } from "./users.service";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { Test, TestingModule } from "@nestjs/testing";
|
||||
import { RbacService } from "../auth/rbac.service";
|
||||
import { MediaService } from "../media/media.service";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
import { UsersRepository } from "./repositories/users.repository";
|
||||
import { UsersService } from "./users.service";
|
||||
|
||||
describe("UsersService", () => {
|
||||
let service: UsersService;
|
||||
@@ -39,6 +47,24 @@ describe("UsersService", () => {
|
||||
del: jest.fn(),
|
||||
};
|
||||
|
||||
const mockRbacService = {
|
||||
getUserRoles: jest.fn(),
|
||||
};
|
||||
|
||||
const mockMediaService = {
|
||||
scanFile: jest.fn(),
|
||||
processImage: jest.fn(),
|
||||
};
|
||||
|
||||
const mockS3Service = {
|
||||
uploadFile: jest.fn(),
|
||||
getPublicUrl: jest.fn(),
|
||||
};
|
||||
|
||||
const mockConfigService = {
|
||||
get: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
@@ -47,6 +73,10 @@ describe("UsersService", () => {
|
||||
UsersService,
|
||||
{ provide: UsersRepository, useValue: mockUsersRepository },
|
||||
{ provide: CACHE_MANAGER, useValue: mockCacheManager },
|
||||
{ provide: RbacService, useValue: mockRbacService },
|
||||
{ provide: MediaService, useValue: mockMediaService },
|
||||
{ provide: S3Service, useValue: mockS3Service },
|
||||
{ provide: ConfigService, useValue: mockConfigService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
@@ -91,7 +121,9 @@ describe("UsersService", () => {
|
||||
|
||||
describe("update", () => {
|
||||
it("should update a user", async () => {
|
||||
mockUsersRepository.update.mockResolvedValue([{ uuid: "uuid1", displayName: "New" }]);
|
||||
mockUsersRepository.update.mockResolvedValue([
|
||||
{ uuid: "uuid1", displayName: "New" },
|
||||
]);
|
||||
const result = await service.update("uuid1", { displayName: "New" });
|
||||
expect(result[0].displayName).toBe("New");
|
||||
});
|
||||
|
||||
@@ -1,8 +1,20 @@
|
||||
import { Injectable, Logger, Inject } from "@nestjs/common";
|
||||
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||
import { Cache } from "cache-manager";
|
||||
import { UsersRepository } from "./repositories/users.repository";
|
||||
import {
|
||||
BadRequestException,
|
||||
forwardRef,
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
} from "@nestjs/common";
|
||||
import type { Cache } from "cache-manager";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { RbacService } from "../auth/rbac.service";
|
||||
import type { IMediaService } from "../common/interfaces/media.interface";
|
||||
import type { IStorageService } from "../common/interfaces/storage.interface";
|
||||
import { MediaService } from "../media/media.service";
|
||||
import { S3Service } from "../s3/s3.service";
|
||||
import { UpdateUserDto } from "./dto/update-user.dto";
|
||||
import { UsersRepository } from "./repositories/users.repository";
|
||||
|
||||
@Injectable()
|
||||
export class UsersService {
|
||||
@@ -11,6 +23,10 @@ export class UsersService {
|
||||
constructor(
|
||||
private readonly usersRepository: UsersRepository,
|
||||
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
||||
@Inject(forwardRef(() => RbacService))
|
||||
private readonly rbacService: RbacService,
|
||||
@Inject(MediaService) private readonly mediaService: IMediaService,
|
||||
@Inject(S3Service) private readonly s3Service: IStorageService,
|
||||
) {}
|
||||
|
||||
private async clearUserCache(username?: string) {
|
||||
@@ -33,7 +49,21 @@ export class UsersService {
|
||||
}
|
||||
|
||||
async findOneWithPrivateData(uuid: string) {
|
||||
return await this.usersRepository.findOneWithPrivateData(uuid);
|
||||
const [user, roles] = await Promise.all([
|
||||
this.usersRepository.findOneWithPrivateData(uuid),
|
||||
this.rbacService.getUserRoles(uuid),
|
||||
]);
|
||||
|
||||
if (!user) return null;
|
||||
|
||||
return {
|
||||
...user,
|
||||
avatarUrl: user.avatarUrl
|
||||
? this.s3Service.getPublicUrl(user.avatarUrl)
|
||||
: null,
|
||||
role: roles.includes("admin") ? "admin" : "user",
|
||||
roles,
|
||||
};
|
||||
}
|
||||
|
||||
async findAll(limit: number, offset: number) {
|
||||
@@ -42,11 +72,26 @@ export class UsersService {
|
||||
this.usersRepository.countAll(),
|
||||
]);
|
||||
|
||||
return { data, totalCount };
|
||||
const processedData = data.map((user) => ({
|
||||
...user,
|
||||
avatarUrl: user.avatarUrl
|
||||
? this.s3Service.getPublicUrl(user.avatarUrl)
|
||||
: null,
|
||||
}));
|
||||
|
||||
return { data: processedData, totalCount };
|
||||
}
|
||||
|
||||
async findPublicProfile(username: string) {
|
||||
return await this.usersRepository.findByUsername(username);
|
||||
const user = await this.usersRepository.findByUsername(username);
|
||||
if (!user) return null;
|
||||
|
||||
return {
|
||||
...user,
|
||||
avatarUrl: user.avatarUrl
|
||||
? this.s3Service.getPublicUrl(user.avatarUrl)
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
async findOne(uuid: string) {
|
||||
@@ -63,6 +108,48 @@ export class UsersService {
|
||||
return result;
|
||||
}
|
||||
|
||||
async updateAvatar(uuid: string, file: Express.Multer.File) {
|
||||
this.logger.log(`Updating avatar for user ${uuid}`);
|
||||
|
||||
// Validation du format et de la taille
|
||||
const allowedMimeTypes = ["image/png", "image/jpeg", "image/webp"];
|
||||
if (!allowedMimeTypes.includes(file.mimetype)) {
|
||||
throw new BadRequestException(
|
||||
"Format d'image non supporté. Formats acceptés: png, jpeg, webp.",
|
||||
);
|
||||
}
|
||||
|
||||
if (file.size > 2 * 1024 * 1024) {
|
||||
throw new BadRequestException("Image trop volumineuse. Limite: 2 Mo.");
|
||||
}
|
||||
|
||||
// 1. Scan Antivirus
|
||||
const scanResult = await this.mediaService.scanFile(
|
||||
file.buffer,
|
||||
file.originalname,
|
||||
);
|
||||
if (scanResult.isInfected) {
|
||||
throw new BadRequestException(
|
||||
`Le fichier est infecté par ${scanResult.virusName}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 2. Traitement (WebP + Redimensionnement 512x512)
|
||||
const processed = await this.mediaService.processImage(file.buffer, "webp", {
|
||||
width: 512,
|
||||
height: 512,
|
||||
});
|
||||
|
||||
// 3. Upload vers S3
|
||||
const key = `avatars/${uuid}/${Date.now()}-${uuidv4()}.${processed.extension}`;
|
||||
await this.s3Service.uploadFile(key, processed.buffer, processed.mimeType);
|
||||
this.logger.log(`Avatar uploaded successfully to S3: ${key}`);
|
||||
|
||||
// 4. Mise à jour de la base de données
|
||||
const user = await this.update(uuid, { avatarUrl: key });
|
||||
return user[0];
|
||||
}
|
||||
|
||||
async updateConsent(
|
||||
uuid: string,
|
||||
termsVersion: string,
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
createCuid: () => () => 'mocked-cuid',
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
module.exports = {
|
||||
SignJWT: class {
|
||||
constructor() { return this; }
|
||||
setProtectedHeader() { return this; }
|
||||
setIssuedAt() { return this; }
|
||||
setExpirationTime() { return this; }
|
||||
sign() { return Promise.resolve('mocked-token'); }
|
||||
},
|
||||
jwtVerify: () => Promise.resolve({ payload: { sub: 'mocked-user' } }),
|
||||
importJWK: () => Promise.resolve({}),
|
||||
exportJWK: () => Promise.resolve({}),
|
||||
generateKeyPair: () => Promise.resolve({ publicKey: {}, privateKey: {} }),
|
||||
};
|
||||
@@ -1,7 +0,0 @@
|
||||
module.exports = {
|
||||
ml_kem768: {
|
||||
keygen: () => ({ publicKey: Buffer.alloc(1184), secretKey: Buffer.alloc(2400) }),
|
||||
encapsulate: () => ({ cipherText: Buffer.alloc(1088), sharedSecret: Buffer.alloc(32) }),
|
||||
decapsulate: () => Buffer.alloc(32),
|
||||
}
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
module.exports = {
|
||||
sha3_256: () => ({ update: () => ({ digest: () => Buffer.alloc(32) }) }),
|
||||
sha3_512: () => ({ update: () => ({ digest: () => Buffer.alloc(64) }) }),
|
||||
shake256: () => ({ update: () => ({ digest: () => Buffer.alloc(32) }) }),
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user