Compare commits
81 Commits
3ffc5b6fde
...
v1.9.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f34fd644b8
|
||
|
|
c827c2e58d
|
||
|
|
30bcfdb436
|
||
|
|
0b4753c47b
|
||
|
|
69b90849fd
|
||
|
|
f2950ecf86
|
||
|
|
1e17308aab
|
||
|
|
ca4b594828
|
||
|
|
2ea16773c8
|
||
|
|
616d7f76d7
|
||
|
|
f882a70343
|
||
|
|
779bb5c112
|
||
|
|
5753477717
|
||
|
|
7615ec670e
|
||
|
|
40cfff683d
|
||
|
|
bb52782226
|
||
|
|
6a70274623
|
||
|
|
aabc615b89
|
||
|
|
f9b202375f
|
||
|
|
6398965f16
|
||
|
|
9e9b1db012
|
||
|
|
62bf03d07a
|
||
|
|
c83ba6eb7d
|
||
|
|
05a05a1940
|
||
|
|
7c065a2fb9
|
||
|
|
001cdaff8f
|
||
|
|
0eb940c5ce
|
||
|
|
f0617c8ba5
|
||
|
|
27ea6fa413
|
||
|
|
e2146f4502
|
||
|
|
484b775923
|
||
|
|
5b05a14932
|
||
|
|
2704f7d5c5
|
||
|
|
d271cc215b
|
||
|
|
9eb5a60fb2
|
||
|
|
950646a426
|
||
|
|
a9b80e66cd
|
||
|
|
307655371d
|
||
|
|
8eb0cba050
|
||
|
|
50787c9357
|
||
|
|
0972ed951f
|
||
|
|
f852835c59
|
||
|
|
2c18fd1c1a
|
||
|
|
6d80795e44
|
||
|
|
ace438be6b
|
||
|
|
ea1afa7688
|
||
|
|
0976850c0c
|
||
|
|
ed3ed66cab
|
||
|
|
46ffdd809c
|
||
|
|
2dcd277347
|
||
|
|
9486803aeb
|
||
|
|
1e0bb03182
|
||
|
|
f1d1359dcb
|
||
|
|
7b76942795
|
||
|
|
1be8571f26
|
||
|
|
29b1db4aed
|
||
|
|
9db3067721
|
||
|
|
27f8c7148a
|
||
|
|
209711195b
|
||
|
|
fafdaee668
|
||
|
|
01117aad6d
|
||
|
|
e73ae80fc5
|
||
|
|
9ccbd2ceb1
|
||
|
|
3edf5cc070
|
||
|
|
2d670ad9cf
|
||
|
|
fc2f5214b1
|
||
|
|
aa17c57e26
|
||
|
|
004021ff84
|
||
|
|
586d827552
|
||
|
|
17fc8d4b68
|
||
|
|
4a66676fcb
|
||
|
|
48db40b3d4
|
||
|
|
c32d4e7203
|
||
|
|
9b7c2c8e5b
|
||
|
|
0584c46190
|
||
|
|
13ccdbc2ab
|
||
| a4d0c6aa8c | |||
|
|
ba0234fd13
|
||
|
|
81461d04e9
|
||
| c4e6be4452 | |||
| 18288cf8f3 |
BIN
REAC_CDA_V04_24052023.pdf
Normal file
BIN
REAC_CDA_V04_24052023.pdf
Normal file
Binary file not shown.
26
README.md
26
README.md
@@ -59,12 +59,28 @@ Pour approfondir vos connaissances techniques sur le projet :
|
|||||||
|
|
||||||
## Comment l'utiliser ?
|
## Comment l'utiliser ?
|
||||||
|
|
||||||
### Installation locale
|
### Déploiement en Production
|
||||||
|
|
||||||
1. Clonez le dépôt.
|
Le projet est prêt pour la production via Docker Compose.
|
||||||
2. Installez les dépendances avec `pnpm install`.
|
|
||||||
3. Configurez les variables d'environnement (voir `.env.example`).
|
1. **Prérequis** : Docker et Docker Compose installés.
|
||||||
4. Lancez les services via Docker ou manuellement.
|
2. **Variables d'environnement** : Copiez `.env.example` en `.env.prod` et ajustez les valeurs (clés secrètes, hosts, Sentry DSN, etc.).
|
||||||
|
3. **Lancement** :
|
||||||
|
```bash
|
||||||
|
docker-compose -f docker-compose.prod.yml up -d
|
||||||
|
```
|
||||||
|
4. **Services inclus** :
|
||||||
|
- **Frontend** : Next.js en mode standalone optimisé.
|
||||||
|
- **Backend** : NestJS avec clustering et monitoring Sentry.
|
||||||
|
- **Caddy** : Gestion automatique du SSL/TLS.
|
||||||
|
- **ClamAV** : Scan antivirus en temps réel des médias.
|
||||||
|
- **Redis** : Cache, sessions et limitation de débit (Throttling/Bot detection).
|
||||||
|
- **MinIO** : Stockage compatible S3.
|
||||||
|
|
||||||
|
### Sécurité et Performance
|
||||||
|
- **Transcodage Auto** : Toutes les images sont converties en WebP et les vidéos en WebM pour minimiser la bande passante.
|
||||||
|
- **Bot Detection** : Système intégré de détection et de bannissement automatique des crawlers malveillants via Redis.
|
||||||
|
- **Monitoring** : Tracking d'erreurs et profilage de performance via Sentry (Node.js et Next.js).
|
||||||
|
|
||||||
### Clés API
|
### Clés API
|
||||||
|
|
||||||
|
|||||||
54
backend/.migrations/0008_bitter_darwin.sql
Normal file
54
backend/.migrations/0008_bitter_darwin.sql
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
CREATE TABLE "comment_likes" (
|
||||||
|
"comment_id" uuid NOT NULL,
|
||||||
|
"user_id" uuid NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "comment_likes_comment_id_user_id_pk" PRIMARY KEY("comment_id","user_id")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "comments" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"content_id" uuid NOT NULL,
|
||||||
|
"user_id" uuid NOT NULL,
|
||||||
|
"parent_id" uuid,
|
||||||
|
"text" text 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
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "conversation_participants" (
|
||||||
|
"conversation_id" uuid NOT NULL,
|
||||||
|
"user_id" uuid NOT NULL,
|
||||||
|
"joined_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "conversation_participants_conversation_id_user_id_pk" PRIMARY KEY("conversation_id","user_id")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "conversations" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "messages" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"conversation_id" uuid NOT NULL,
|
||||||
|
"sender_id" uuid NOT NULL,
|
||||||
|
"text" text NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"read_at" timestamp with time zone
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "comment_likes" ADD CONSTRAINT "comment_likes_comment_id_comments_id_fk" FOREIGN KEY ("comment_id") REFERENCES "public"."comments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "comment_likes" ADD CONSTRAINT "comment_likes_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "comments" ADD CONSTRAINT "comments_content_id_contents_id_fk" FOREIGN KEY ("content_id") REFERENCES "public"."contents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "comments" ADD CONSTRAINT "comments_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "comments" ADD CONSTRAINT "comments_parent_id_comments_id_fk" FOREIGN KEY ("parent_id") REFERENCES "public"."comments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "conversation_participants" ADD CONSTRAINT "conversation_participants_conversation_id_conversations_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "conversation_participants" ADD CONSTRAINT "conversation_participants_user_id_users_uuid_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "messages" ADD CONSTRAINT "messages_conversation_id_conversations_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "messages" ADD CONSTRAINT "messages_sender_id_users_uuid_fk" FOREIGN KEY ("sender_id") REFERENCES "public"."users"("uuid") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "comments_content_id_idx" ON "comments" USING btree ("content_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "comments_user_id_idx" ON "comments" USING btree ("user_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "comments_parent_id_idx" ON "comments" USING btree ("parent_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "messages_conversation_id_idx" ON "messages" USING btree ("conversation_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "messages_sender_id_idx" ON "messages" USING btree ("sender_id");
|
||||||
2
backend/.migrations/0009_add_privacy_settings.sql
Normal file
2
backend/.migrations/0009_add_privacy_settings.sql
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE "users" ADD COLUMN "show_online_status" boolean DEFAULT true NOT NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "users" ADD COLUMN "show_read_receipts" boolean DEFAULT true NOT NULL;
|
||||||
1
backend/.migrations/0010_update_password_hash_length.sql
Normal file
1
backend/.migrations/0010_update_password_hash_length.sql
Normal file
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "users" ALTER COLUMN "password_hash" SET DATA TYPE varchar(255);
|
||||||
2080
backend/.migrations/meta/0008_snapshot.json
Normal file
2080
backend/.migrations/meta/0008_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
2094
backend/.migrations/meta/0009_snapshot.json
Normal file
2094
backend/.migrations/meta/0009_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
2094
backend/.migrations/meta/0010_snapshot.json
Normal file
2094
backend/.migrations/meta/0010_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -57,6 +57,27 @@
|
|||||||
"when": 1769605995410,
|
"when": 1769605995410,
|
||||||
"tag": "0007_melodic_synch",
|
"tag": "0007_melodic_synch",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 8,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1769696731978,
|
||||||
|
"tag": "0008_bitter_darwin",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 9,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1769717126917,
|
||||||
|
"tag": "0009_add_privacy_settings",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 10,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1769718997591,
|
||||||
|
"tag": "0010_update_password_hash_length",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -15,13 +15,13 @@ COPY documentation/package.json ./documentation/
|
|||||||
|
|
||||||
# Utilisation du cache pour pnpm et installation figée
|
# Utilisation du cache pour pnpm et installation figée
|
||||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||||
pnpm install --frozen-lockfile
|
pnpm install --frozen-lockfile --force
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Deuxième passe avec cache pour les scripts/liens
|
# Deuxième passe avec cache pour les scripts/liens
|
||||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||||
pnpm install --frozen-lockfile
|
pnpm install --frozen-lockfile --force
|
||||||
|
|
||||||
RUN pnpm run --filter @memegoat/backend build
|
RUN pnpm run --filter @memegoat/backend build
|
||||||
RUN pnpm deploy --filter=@memegoat/backend --prod --legacy /app
|
RUN pnpm deploy --filter=@memegoat/backend --prod --legacy /app
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@memegoat/backend",
|
"name": "@memegoat/backend",
|
||||||
"version": "1.7.0",
|
"version": "1.9.5",
|
||||||
"description": "",
|
"description": "",
|
||||||
"author": "",
|
"author": "",
|
||||||
"private": true,
|
"private": true,
|
||||||
@@ -36,8 +36,10 @@
|
|||||||
"@nestjs/core": "^11.0.1",
|
"@nestjs/core": "^11.0.1",
|
||||||
"@nestjs/mapped-types": "^2.1.0",
|
"@nestjs/mapped-types": "^2.1.0",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"@nestjs/platform-socket.io": "^11.1.12",
|
||||||
"@nestjs/schedule": "^6.1.0",
|
"@nestjs/schedule": "^6.1.0",
|
||||||
"@nestjs/throttler": "^6.5.0",
|
"@nestjs/throttler": "^6.5.0",
|
||||||
|
"@nestjs/websockets": "^11.1.12",
|
||||||
"@noble/post-quantum": "^0.5.4",
|
"@noble/post-quantum": "^0.5.4",
|
||||||
"@node-rs/argon2": "^2.0.2",
|
"@node-rs/argon2": "^2.0.2",
|
||||||
"@sentry/nestjs": "^10.32.1",
|
"@sentry/nestjs": "^10.32.1",
|
||||||
@@ -48,6 +50,7 @@
|
|||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.3",
|
"class-validator": "^0.14.3",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
|
"drizzle-kit": "^0.31.8",
|
||||||
"drizzle-orm": "^0.45.1",
|
"drizzle-orm": "^0.45.1",
|
||||||
"fluent-ffmpeg": "^2.1.3",
|
"fluent-ffmpeg": "^2.1.3",
|
||||||
"helmet": "^8.1.0",
|
"helmet": "^8.1.0",
|
||||||
@@ -61,23 +64,12 @@
|
|||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
"sharp": "^0.34.5",
|
"sharp": "^0.34.5",
|
||||||
|
"socket.io": "^4.8.3",
|
||||||
"uuid": "^13.0.0",
|
"uuid": "^13.0.0",
|
||||||
"zod": "^4.3.5",
|
"zod": "^4.3.5"
|
||||||
"drizzle-kit": "^0.31.8"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@nestjs/cli": "^11.0.0",
|
"@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/schematics": "^11.0.0",
|
||||||
"@nestjs/testing": "^11.0.1",
|
"@nestjs/testing": "^11.0.1",
|
||||||
"@types/express": "^5.0.0",
|
"@types/express": "^5.0.0",
|
||||||
@@ -89,9 +81,21 @@
|
|||||||
"@types/pg": "^8.16.0",
|
"@types/pg": "^8.16.0",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
"@types/sharp": "^0.32.0",
|
"@types/sharp": "^0.32.0",
|
||||||
|
"@types/socket.io": "^3.0.2",
|
||||||
"@types/supertest": "^6.0.2",
|
"@types/supertest": "^6.0.2",
|
||||||
"@types/uuid": "^11.0.0",
|
"@types/uuid": "^11.0.0",
|
||||||
"drizzle-kit": "^0.31.8"
|
"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"
|
||||||
},
|
},
|
||||||
"jest": {
|
"jest": {
|
||||||
"moduleFileExtensions": [
|
"moduleFileExtensions": [
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { AppController } from "./app.controller";
|
|||||||
import { AppService } from "./app.service";
|
import { AppService } from "./app.service";
|
||||||
import { AuthModule } from "./auth/auth.module";
|
import { AuthModule } from "./auth/auth.module";
|
||||||
import { CategoriesModule } from "./categories/categories.module";
|
import { CategoriesModule } from "./categories/categories.module";
|
||||||
|
import { CommentsModule } from "./comments/comments.module";
|
||||||
import { CommonModule } from "./common/common.module";
|
import { CommonModule } from "./common/common.module";
|
||||||
import { CrawlerDetectionMiddleware } from "./common/middlewares/crawler-detection.middleware";
|
import { CrawlerDetectionMiddleware } from "./common/middlewares/crawler-detection.middleware";
|
||||||
import { HTTPLoggerMiddleware } from "./common/middlewares/http-logger.middleware";
|
import { HTTPLoggerMiddleware } from "./common/middlewares/http-logger.middleware";
|
||||||
@@ -21,6 +22,8 @@ import { FavoritesModule } from "./favorites/favorites.module";
|
|||||||
import { HealthController } from "./health.controller";
|
import { HealthController } from "./health.controller";
|
||||||
import { MailModule } from "./mail/mail.module";
|
import { MailModule } from "./mail/mail.module";
|
||||||
import { MediaModule } from "./media/media.module";
|
import { MediaModule } from "./media/media.module";
|
||||||
|
import { MessagesModule } from "./messages/messages.module";
|
||||||
|
import { RealtimeModule } from "./realtime/realtime.module";
|
||||||
import { ReportsModule } from "./reports/reports.module";
|
import { ReportsModule } from "./reports/reports.module";
|
||||||
import { S3Module } from "./s3/s3.module";
|
import { S3Module } from "./s3/s3.module";
|
||||||
import { SessionsModule } from "./sessions/sessions.module";
|
import { SessionsModule } from "./sessions/sessions.module";
|
||||||
@@ -37,12 +40,15 @@ import { UsersModule } from "./users/users.module";
|
|||||||
UsersModule,
|
UsersModule,
|
||||||
AuthModule,
|
AuthModule,
|
||||||
CategoriesModule,
|
CategoriesModule,
|
||||||
|
CommentsModule,
|
||||||
ContentsModule,
|
ContentsModule,
|
||||||
FavoritesModule,
|
FavoritesModule,
|
||||||
TagsModule,
|
TagsModule,
|
||||||
MediaModule,
|
MediaModule,
|
||||||
|
MessagesModule,
|
||||||
SessionsModule,
|
SessionsModule,
|
||||||
ReportsModule,
|
ReportsModule,
|
||||||
|
RealtimeModule,
|
||||||
ApiKeysModule,
|
ApiKeysModule,
|
||||||
AdminModule,
|
AdminModule,
|
||||||
ScheduleModule.forRoot(),
|
ScheduleModule.forRoot(),
|
||||||
|
|||||||
@@ -148,7 +148,7 @@ describe("AuthService", () => {
|
|||||||
const dto = {
|
const dto = {
|
||||||
username: "test",
|
username: "test",
|
||||||
email: "test@example.com",
|
email: "test@example.com",
|
||||||
password: "password",
|
password: "Password1!",
|
||||||
};
|
};
|
||||||
mockHashingService.hashPassword.mockResolvedValue("hashed-password");
|
mockHashingService.hashPassword.mockResolvedValue("hashed-password");
|
||||||
mockHashingService.hashEmail.mockResolvedValue("hashed-email");
|
mockHashingService.hashEmail.mockResolvedValue("hashed-email");
|
||||||
@@ -165,7 +165,7 @@ describe("AuthService", () => {
|
|||||||
|
|
||||||
describe("login", () => {
|
describe("login", () => {
|
||||||
it("should login a user", async () => {
|
it("should login a user", async () => {
|
||||||
const dto = { email: "test@example.com", password: "password" };
|
const dto = { email: "test@example.com", password: "Password1!" };
|
||||||
const user = {
|
const user = {
|
||||||
uuid: "user-id",
|
uuid: "user-id",
|
||||||
username: "test",
|
username: "test",
|
||||||
|
|||||||
@@ -136,6 +136,7 @@ export class AuthService {
|
|||||||
const accessToken = await this.jwtService.generateJwt({
|
const accessToken = await this.jwtService.generateJwt({
|
||||||
sub: user.uuid,
|
sub: user.uuid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
|
role: user.role,
|
||||||
});
|
});
|
||||||
|
|
||||||
const session = await this.sessionsService.createSession(
|
const session = await this.sessionsService.createSession(
|
||||||
@@ -178,6 +179,7 @@ export class AuthService {
|
|||||||
const accessToken = await this.jwtService.generateJwt({
|
const accessToken = await this.jwtService.generateJwt({
|
||||||
sub: user.uuid,
|
sub: user.uuid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
|
role: user.role,
|
||||||
});
|
});
|
||||||
|
|
||||||
const session = await this.sessionsService.createSession(
|
const session = await this.sessionsService.createSession(
|
||||||
@@ -205,6 +207,7 @@ export class AuthService {
|
|||||||
const accessToken = await this.jwtService.generateJwt({
|
const accessToken = await this.jwtService.generateJwt({
|
||||||
sub: user.uuid,
|
sub: user.uuid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
|
role: user.role,
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
IsEmail,
|
IsEmail,
|
||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsString,
|
IsString,
|
||||||
|
Matches,
|
||||||
MaxLength,
|
MaxLength,
|
||||||
MinLength,
|
MinLength,
|
||||||
} from "class-validator";
|
} from "class-validator";
|
||||||
@@ -10,6 +11,10 @@ export class RegisterDto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
@MaxLength(32)
|
@MaxLength(32)
|
||||||
|
@Matches(/^[a-z0-9_]+$/, {
|
||||||
|
message:
|
||||||
|
"username must contain only lowercase letters, numbers, and underscores",
|
||||||
|
})
|
||||||
username!: string;
|
username!: string;
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -21,5 +26,15 @@ export class RegisterDto {
|
|||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
@MinLength(8)
|
@MinLength(8)
|
||||||
|
@Matches(/[A-Z]/, {
|
||||||
|
message: "password must contain at least one uppercase letter",
|
||||||
|
})
|
||||||
|
@Matches(/[a-z]/, {
|
||||||
|
message: "password must contain at least one lowercase letter",
|
||||||
|
})
|
||||||
|
@Matches(/[0-9]/, { message: "password must contain at least one number" })
|
||||||
|
@Matches(/[^A-Za-z0-9]/, {
|
||||||
|
message: "password must contain at least one special character",
|
||||||
|
})
|
||||||
password!: string;
|
password!: string;
|
||||||
}
|
}
|
||||||
|
|||||||
80
backend/src/comments/comments.controller.ts
Normal file
80
backend/src/comments/comments.controller.ts
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
UseGuards,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import { getIronSession } from "iron-session";
|
||||||
|
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||||
|
import { getSessionOptions } from "../auth/session.config";
|
||||||
|
import type { AuthenticatedRequest } from "../common/interfaces/request.interface";
|
||||||
|
import { JwtService } from "../crypto/services/jwt.service";
|
||||||
|
import { CommentsService } from "./comments.service";
|
||||||
|
import { CreateCommentDto } from "./dto/create-comment.dto";
|
||||||
|
|
||||||
|
@Controller()
|
||||||
|
export class CommentsController {
|
||||||
|
constructor(
|
||||||
|
private readonly commentsService: CommentsService,
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get("contents/:contentId/comments")
|
||||||
|
async findAllByContentId(
|
||||||
|
@Param("contentId") contentId: string,
|
||||||
|
@Req() req: any,
|
||||||
|
) {
|
||||||
|
// Tentative de récupération de l'utilisateur pour isLiked (optionnel)
|
||||||
|
let userId: string | undefined;
|
||||||
|
try {
|
||||||
|
const session = await getIronSession<any>(
|
||||||
|
req,
|
||||||
|
req.res,
|
||||||
|
getSessionOptions(this.configService.get("SESSION_PASSWORD") as string),
|
||||||
|
);
|
||||||
|
if (session.accessToken) {
|
||||||
|
const payload = await this.jwtService.verifyJwt(session.accessToken);
|
||||||
|
userId = payload.sub;
|
||||||
|
}
|
||||||
|
} catch (_e) {
|
||||||
|
// Ignorer les erreurs de session
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.commentsService.findAllByContentId(contentId, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("contents/:contentId/comments")
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
create(
|
||||||
|
@Req() req: AuthenticatedRequest,
|
||||||
|
@Param("contentId") contentId: string,
|
||||||
|
@Body() dto: CreateCommentDto,
|
||||||
|
) {
|
||||||
|
return this.commentsService.create(req.user.sub, contentId, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete("comments/:id")
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
remove(@Req() req: AuthenticatedRequest, @Param("id") id: string) {
|
||||||
|
const isAdmin = req.user.role === "admin" || req.user.role === "moderator";
|
||||||
|
return this.commentsService.remove(req.user.sub, id, isAdmin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("comments/:id/like")
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
like(@Req() req: AuthenticatedRequest, @Param("id") id: string) {
|
||||||
|
return this.commentsService.like(req.user.sub, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete("comments/:id/like")
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
unlike(@Req() req: AuthenticatedRequest, @Param("id") id: string) {
|
||||||
|
return this.commentsService.unlike(req.user.sub, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
22
backend/src/comments/comments.module.ts
Normal file
22
backend/src/comments/comments.module.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { forwardRef, Module } from "@nestjs/common";
|
||||||
|
import { AuthModule } from "../auth/auth.module";
|
||||||
|
import { ContentsModule } from "../contents/contents.module";
|
||||||
|
import { RealtimeModule } from "../realtime/realtime.module";
|
||||||
|
import { S3Module } from "../s3/s3.module";
|
||||||
|
import { CommentsController } from "./comments.controller";
|
||||||
|
import { CommentsService } from "./comments.service";
|
||||||
|
import { CommentLikesRepository } from "./repositories/comment-likes.repository";
|
||||||
|
import { CommentsRepository } from "./repositories/comments.repository";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
AuthModule,
|
||||||
|
S3Module,
|
||||||
|
RealtimeModule,
|
||||||
|
forwardRef(() => ContentsModule),
|
||||||
|
],
|
||||||
|
controllers: [CommentsController],
|
||||||
|
providers: [CommentsService, CommentsRepository, CommentLikesRepository],
|
||||||
|
exports: [CommentsService],
|
||||||
|
})
|
||||||
|
export class CommentsModule {}
|
||||||
151
backend/src/comments/comments.service.spec.ts
Normal file
151
backend/src/comments/comments.service.spec.ts
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
import { ForbiddenException, NotFoundException } from "@nestjs/common";
|
||||||
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
|
import { ContentsRepository } from "../contents/repositories/contents.repository";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
|
import { S3Service } from "../s3/s3.service";
|
||||||
|
import { CommentsService } from "./comments.service";
|
||||||
|
import { CommentLikesRepository } from "./repositories/comment-likes.repository";
|
||||||
|
import { CommentsRepository } from "./repositories/comments.repository";
|
||||||
|
|
||||||
|
describe("CommentsService", () => {
|
||||||
|
let service: CommentsService;
|
||||||
|
let repository: CommentsRepository;
|
||||||
|
|
||||||
|
const mockCommentsRepository = {
|
||||||
|
create: jest.fn(),
|
||||||
|
findAllByContentId: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
findOneEnriched: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockCommentLikesRepository = {
|
||||||
|
addLike: jest.fn(),
|
||||||
|
removeLike: jest.fn(),
|
||||||
|
countByCommentId: jest.fn(),
|
||||||
|
isLikedByUser: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockContentsRepository = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockS3Service = {
|
||||||
|
getPublicUrl: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockEventsGateway = {
|
||||||
|
sendToContent: jest.fn(),
|
||||||
|
sendToUser: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
jest.clearAllMocks();
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
CommentsService,
|
||||||
|
{ provide: CommentsRepository, useValue: mockCommentsRepository },
|
||||||
|
{ provide: CommentLikesRepository, useValue: mockCommentLikesRepository },
|
||||||
|
{ provide: ContentsRepository, useValue: mockContentsRepository },
|
||||||
|
{ provide: S3Service, useValue: mockS3Service },
|
||||||
|
{ provide: EventsGateway, useValue: mockEventsGateway },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<CommentsService>(CommentsService);
|
||||||
|
repository = module.get<CommentsRepository>(CommentsRepository);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be defined", () => {
|
||||||
|
expect(service).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("create", () => {
|
||||||
|
it("should create a comment", async () => {
|
||||||
|
const userId = "user1";
|
||||||
|
const contentId = "content1";
|
||||||
|
const dto = { text: "Nice meme", parentId: undefined };
|
||||||
|
const createdComment = { id: "c1", ...dto, user: { username: "u1" } };
|
||||||
|
mockCommentsRepository.create.mockResolvedValue(createdComment);
|
||||||
|
mockCommentsRepository.findOneEnriched.mockResolvedValue(createdComment);
|
||||||
|
mockCommentLikesRepository.countByCommentId.mockResolvedValue(0);
|
||||||
|
mockCommentLikesRepository.isLikedByUser.mockResolvedValue(false);
|
||||||
|
|
||||||
|
const result = await service.create(userId, contentId, dto);
|
||||||
|
expect(result.id).toBe("c1");
|
||||||
|
expect(repository.create).toHaveBeenCalledWith({
|
||||||
|
userId,
|
||||||
|
contentId,
|
||||||
|
text: dto.text,
|
||||||
|
parentId: undefined,
|
||||||
|
});
|
||||||
|
expect(mockEventsGateway.sendToContent).toHaveBeenCalledWith(
|
||||||
|
contentId,
|
||||||
|
"new_comment",
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("findAllByContentId", () => {
|
||||||
|
it("should return comments for a content", async () => {
|
||||||
|
mockCommentsRepository.findAllByContentId.mockResolvedValue([
|
||||||
|
{ id: "c1", user: { avatarUrl: "path" } },
|
||||||
|
]);
|
||||||
|
mockCommentLikesRepository.countByCommentId.mockResolvedValue(5);
|
||||||
|
mockCommentLikesRepository.isLikedByUser.mockResolvedValue(true);
|
||||||
|
mockS3Service.getPublicUrl.mockReturnValue("url");
|
||||||
|
|
||||||
|
const result = await service.findAllByContentId("content1", "u1");
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0].likesCount).toBe(5);
|
||||||
|
expect(result[0].isLiked).toBe(true);
|
||||||
|
expect(result[0].user.avatarUrl).toBe("url");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("remove", () => {
|
||||||
|
it("should remove comment if owner", async () => {
|
||||||
|
mockCommentsRepository.findOne.mockResolvedValue({ userId: "u1" });
|
||||||
|
await service.remove("u1", "c1");
|
||||||
|
expect(repository.delete).toHaveBeenCalledWith("c1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove comment if admin", async () => {
|
||||||
|
mockCommentsRepository.findOne.mockResolvedValue({ userId: "u1" });
|
||||||
|
await service.remove("other", "c1", true);
|
||||||
|
expect(repository.delete).toHaveBeenCalledWith("c1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw NotFoundException if comment does not exist", async () => {
|
||||||
|
mockCommentsRepository.findOne.mockResolvedValue(null);
|
||||||
|
await expect(service.remove("u1", "c1")).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw ForbiddenException if not owner and not admin", async () => {
|
||||||
|
mockCommentsRepository.findOne.mockResolvedValue({ userId: "u1" });
|
||||||
|
await expect(service.remove("other", "c1")).rejects.toThrow(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("like", () => {
|
||||||
|
it("should add like", async () => {
|
||||||
|
mockCommentsRepository.findOne.mockResolvedValue({ id: "c1" });
|
||||||
|
await service.like("u1", "c1");
|
||||||
|
expect(mockCommentLikesRepository.addLike).toHaveBeenCalledWith("c1", "u1");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("unlike", () => {
|
||||||
|
it("should remove like", async () => {
|
||||||
|
mockCommentsRepository.findOne.mockResolvedValue({ id: "c1" });
|
||||||
|
await service.unlike("u1", "c1");
|
||||||
|
expect(mockCommentLikesRepository.removeLike).toHaveBeenCalledWith(
|
||||||
|
"c1",
|
||||||
|
"u1",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
177
backend/src/comments/comments.service.ts
Normal file
177
backend/src/comments/comments.service.ts
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
import {
|
||||||
|
ForbiddenException,
|
||||||
|
forwardRef,
|
||||||
|
Inject,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { ContentsRepository } from "../contents/repositories/contents.repository";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
|
import { S3Service } from "../s3/s3.service";
|
||||||
|
import type { CreateCommentDto } from "./dto/create-comment.dto";
|
||||||
|
import { CommentLikesRepository } from "./repositories/comment-likes.repository";
|
||||||
|
import { CommentsRepository } from "./repositories/comments.repository";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CommentsService {
|
||||||
|
constructor(
|
||||||
|
private readonly commentsRepository: CommentsRepository,
|
||||||
|
private readonly commentLikesRepository: CommentLikesRepository,
|
||||||
|
@Inject(forwardRef(() => ContentsRepository))
|
||||||
|
private readonly contentsRepository: ContentsRepository,
|
||||||
|
private readonly s3Service: S3Service,
|
||||||
|
private readonly eventsGateway: EventsGateway,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async create(userId: string, contentId: string, dto: CreateCommentDto) {
|
||||||
|
const comment = await this.commentsRepository.create({
|
||||||
|
userId,
|
||||||
|
contentId,
|
||||||
|
text: dto.text,
|
||||||
|
parentId: dto.parentId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Récupérer le commentaire avec les infos utilisateur pour le WebSocket
|
||||||
|
const enrichedComment = await this.findOneEnriched(comment.id, userId);
|
||||||
|
if (!enrichedComment) return null;
|
||||||
|
|
||||||
|
// Notifier les autres utilisateurs sur ce contenu (room de contenu)
|
||||||
|
this.eventsGateway.sendToContent(contentId, "new_comment", enrichedComment);
|
||||||
|
|
||||||
|
// Notifications ciblées
|
||||||
|
try {
|
||||||
|
// 1. Notifier l'auteur du post
|
||||||
|
const content = await this.contentsRepository.findOne(contentId);
|
||||||
|
if (content && content.userId !== userId) {
|
||||||
|
this.eventsGateway.sendToUser(content.userId, "notification", {
|
||||||
|
type: "comment",
|
||||||
|
userId: userId,
|
||||||
|
username: enrichedComment.user.username,
|
||||||
|
contentId: contentId,
|
||||||
|
commentId: comment.id,
|
||||||
|
text: `a commenté votre post : "${dto.text.substring(0, 30)}${dto.text.length > 30 ? "..." : ""}"`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Si c'est une réponse, notifier l'auteur du commentaire parent
|
||||||
|
if (dto.parentId) {
|
||||||
|
const parentComment = await this.commentsRepository.findOne(dto.parentId);
|
||||||
|
if (
|
||||||
|
parentComment &&
|
||||||
|
parentComment.userId !== userId &&
|
||||||
|
(!content || parentComment.userId !== content.userId)
|
||||||
|
) {
|
||||||
|
this.eventsGateway.sendToUser(parentComment.userId, "notification", {
|
||||||
|
type: "reply",
|
||||||
|
userId: userId,
|
||||||
|
username: enrichedComment.user.username,
|
||||||
|
contentId: contentId,
|
||||||
|
commentId: comment.id,
|
||||||
|
text: `a répondu à votre commentaire : "${dto.text.substring(0, 30)}${dto.text.length > 30 ? "..." : ""}"`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to send notification:", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return enrichedComment;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOneEnriched(commentId: string, currentUserId?: string) {
|
||||||
|
const comment = await this.commentsRepository.findOneEnriched(commentId);
|
||||||
|
if (!comment) return null;
|
||||||
|
|
||||||
|
const [likesCount, isLiked] = await Promise.all([
|
||||||
|
this.commentLikesRepository.countByCommentId(comment.id),
|
||||||
|
currentUserId
|
||||||
|
? this.commentLikesRepository.isLikedByUser(comment.id, currentUserId)
|
||||||
|
: Promise.resolve(false),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...comment,
|
||||||
|
likesCount,
|
||||||
|
isLiked,
|
||||||
|
user: {
|
||||||
|
...comment.user,
|
||||||
|
avatarUrl: comment.user.avatarUrl
|
||||||
|
? this.s3Service.getPublicUrl(comment.user.avatarUrl)
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllByContentId(contentId: string, userId?: string) {
|
||||||
|
const comments = await this.commentsRepository.findAllByContentId(contentId);
|
||||||
|
|
||||||
|
return Promise.all(
|
||||||
|
comments.map(async (comment) => {
|
||||||
|
const [likesCount, isLiked] = await Promise.all([
|
||||||
|
this.commentLikesRepository.countByCommentId(comment.id),
|
||||||
|
userId
|
||||||
|
? this.commentLikesRepository.isLikedByUser(comment.id, userId)
|
||||||
|
: Promise.resolve(false),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
...comment,
|
||||||
|
likesCount,
|
||||||
|
isLiked,
|
||||||
|
user: {
|
||||||
|
...comment.user,
|
||||||
|
avatarUrl: comment.user.avatarUrl
|
||||||
|
? this.s3Service.getPublicUrl(comment.user.avatarUrl)
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(userId: string, commentId: string, isAdmin = false) {
|
||||||
|
const comment = await this.commentsRepository.findOne(commentId);
|
||||||
|
if (!comment) {
|
||||||
|
throw new NotFoundException("Comment not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAdmin && comment.userId !== userId) {
|
||||||
|
throw new ForbiddenException("You cannot delete this comment");
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.commentsRepository.delete(commentId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async like(userId: string, commentId: string) {
|
||||||
|
const comment = await this.commentsRepository.findOne(commentId);
|
||||||
|
if (!comment) {
|
||||||
|
throw new NotFoundException("Comment not found");
|
||||||
|
}
|
||||||
|
await this.commentLikesRepository.addLike(commentId, userId);
|
||||||
|
|
||||||
|
// Notifier l'auteur du commentaire
|
||||||
|
if (comment.userId !== userId) {
|
||||||
|
try {
|
||||||
|
const liker = await this.findOneEnriched(commentId, userId);
|
||||||
|
this.eventsGateway.sendToUser(comment.userId, "notification", {
|
||||||
|
type: "like_comment",
|
||||||
|
userId: userId,
|
||||||
|
username: liker?.user.username,
|
||||||
|
contentId: comment.contentId,
|
||||||
|
commentId: commentId,
|
||||||
|
text: "a aimé votre commentaire",
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to send like notification:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async unlike(userId: string, commentId: string) {
|
||||||
|
const comment = await this.commentsRepository.findOne(commentId);
|
||||||
|
if (!comment) {
|
||||||
|
throw new NotFoundException("Comment not found");
|
||||||
|
}
|
||||||
|
await this.commentLikesRepository.removeLike(commentId, userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
18
backend/src/comments/dto/create-comment.dto.ts
Normal file
18
backend/src/comments/dto/create-comment.dto.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import {
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsUUID,
|
||||||
|
MaxLength,
|
||||||
|
} from "class-validator";
|
||||||
|
|
||||||
|
export class CreateCommentDto {
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
@MaxLength(1000)
|
||||||
|
text!: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsUUID()
|
||||||
|
parentId?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { and, eq, sql } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { commentLikes } from "../../database/schemas/comment_likes";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CommentLikesRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async addLike(commentId: string, userId: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.insert(commentLikes)
|
||||||
|
.values({ commentId, userId })
|
||||||
|
.onConflictDoNothing();
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeLike(commentId: string, userId: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.delete(commentLikes)
|
||||||
|
.where(
|
||||||
|
and(eq(commentLikes.commentId, commentId), eq(commentLikes.userId, userId)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async countByCommentId(commentId: string) {
|
||||||
|
const results = await this.databaseService.db
|
||||||
|
.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(commentLikes)
|
||||||
|
.where(eq(commentLikes.commentId, commentId));
|
||||||
|
return Number(results[0]?.count || 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
async isLikedByUser(commentId: string, userId: string) {
|
||||||
|
const results = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(commentLikes)
|
||||||
|
.where(
|
||||||
|
and(eq(commentLikes.commentId, commentId), eq(commentLikes.userId, userId)),
|
||||||
|
);
|
||||||
|
return !!results[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
75
backend/src/comments/repositories/comments.repository.ts
Normal file
75
backend/src/comments/repositories/comments.repository.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import { comments, users } from "../../database/schemas";
|
||||||
|
import type { NewCommentInDb } from "../../database/schemas/comments";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CommentsRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async create(data: NewCommentInDb) {
|
||||||
|
const results = await this.databaseService.db
|
||||||
|
.insert(comments)
|
||||||
|
.values(data)
|
||||||
|
.returning();
|
||||||
|
return results[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllByContentId(contentId: string) {
|
||||||
|
return this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: comments.id,
|
||||||
|
text: comments.text,
|
||||||
|
parentId: comments.parentId,
|
||||||
|
createdAt: comments.createdAt,
|
||||||
|
updatedAt: comments.updatedAt,
|
||||||
|
user: {
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
displayName: users.displayName,
|
||||||
|
avatarUrl: users.avatarUrl,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.from(comments)
|
||||||
|
.innerJoin(users, eq(comments.userId, users.uuid))
|
||||||
|
.where(and(eq(comments.contentId, contentId), isNull(comments.deletedAt)))
|
||||||
|
.orderBy(desc(comments.createdAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(id: string) {
|
||||||
|
const results = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(comments)
|
||||||
|
.where(and(eq(comments.id, id), isNull(comments.deletedAt)));
|
||||||
|
return results[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOneEnriched(id: string) {
|
||||||
|
const results = await this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: comments.id,
|
||||||
|
text: comments.text,
|
||||||
|
parentId: comments.parentId,
|
||||||
|
createdAt: comments.createdAt,
|
||||||
|
updatedAt: comments.updatedAt,
|
||||||
|
user: {
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
displayName: users.displayName,
|
||||||
|
avatarUrl: users.avatarUrl,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.from(comments)
|
||||||
|
.innerJoin(users, eq(comments.userId, users.uuid))
|
||||||
|
.where(and(eq(comments.id, id), isNull(comments.deletedAt)));
|
||||||
|
return results[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(id: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.update(comments)
|
||||||
|
.set({ deletedAt: new Date() })
|
||||||
|
.where(eq(comments.id, id));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,5 +4,6 @@ export interface AuthenticatedRequest extends Request {
|
|||||||
user: {
|
user: {
|
||||||
sub: string;
|
sub: string;
|
||||||
username: string;
|
username: string;
|
||||||
|
role: string;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
|
import { CACHE_MANAGER } from "@nestjs/cache-manager";
|
||||||
|
import { Inject, Injectable, Logger, NestMiddleware } from "@nestjs/common";
|
||||||
|
import type { Cache } from "cache-manager";
|
||||||
import type { NextFunction, Request, Response } from "express";
|
import type { NextFunction, Request, Response } from "express";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CrawlerDetectionMiddleware implements NestMiddleware {
|
export class CrawlerDetectionMiddleware implements NestMiddleware {
|
||||||
private readonly logger = new Logger("CrawlerDetection");
|
private readonly logger = new Logger("CrawlerDetection");
|
||||||
|
|
||||||
|
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
|
||||||
|
|
||||||
private readonly SUSPICIOUS_PATTERNS = [
|
private readonly SUSPICIOUS_PATTERNS = [
|
||||||
/\.env/,
|
/\.env/,
|
||||||
/wp-admin/,
|
/wp-admin/,
|
||||||
@@ -24,7 +28,7 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
|
|||||||
/db\./,
|
/db\./,
|
||||||
/backup\./,
|
/backup\./,
|
||||||
/cgi-bin/,
|
/cgi-bin/,
|
||||||
/\.well-known\/security\.txt/, // Bien que légitime, souvent scanné
|
/\.well-known\/security\.txt/,
|
||||||
];
|
];
|
||||||
|
|
||||||
private readonly BOT_USER_AGENTS = [
|
private readonly BOT_USER_AGENTS = [
|
||||||
@@ -40,11 +44,21 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
|
|||||||
/masscan/i,
|
/masscan/i,
|
||||||
];
|
];
|
||||||
|
|
||||||
use(req: Request, res: Response, next: NextFunction) {
|
async use(req: Request, res: Response, next: NextFunction) {
|
||||||
const { method, url, ip } = req;
|
const { method, url, ip } = req;
|
||||||
const userAgent = req.get("user-agent") || "unknown";
|
const userAgent = req.get("user-agent") || "unknown";
|
||||||
|
|
||||||
res.on("finish", () => {
|
// Vérifier si l'IP est bannie
|
||||||
|
const isBanned = await this.cacheManager.get(`banned_ip:${ip}`);
|
||||||
|
if (isBanned) {
|
||||||
|
this.logger.warn(`Banned IP attempt: ${ip} -> ${method} ${url}`);
|
||||||
|
res.status(403).json({
|
||||||
|
message: "Access denied: Your IP has been temporarily banned.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.on("finish", async () => {
|
||||||
if (res.statusCode === 404) {
|
if (res.statusCode === 404) {
|
||||||
const isSuspiciousPath = this.SUSPICIOUS_PATTERNS.some((pattern) =>
|
const isSuspiciousPath = this.SUSPICIOUS_PATTERNS.some((pattern) =>
|
||||||
pattern.test(url),
|
pattern.test(url),
|
||||||
@@ -57,7 +71,9 @@ export class CrawlerDetectionMiddleware implements NestMiddleware {
|
|||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
`Potential crawler detected: [${ip}] ${method} ${url} - User-Agent: ${userAgent}`,
|
`Potential crawler detected: [${ip}] ${method} ${url} - User-Agent: ${userAgent}`,
|
||||||
);
|
);
|
||||||
// Ici, on pourrait ajouter une logique pour bannir l'IP temporairement via Redis
|
|
||||||
|
// Bannir l'IP pour 24h via Redis
|
||||||
|
await this.cacheManager.set(`banned_ip:${ip}`, true, 86400000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { AuthModule } from "../auth/auth.module";
|
import { AuthModule } from "../auth/auth.module";
|
||||||
import { MediaModule } from "../media/media.module";
|
import { MediaModule } from "../media/media.module";
|
||||||
|
import { RealtimeModule } from "../realtime/realtime.module";
|
||||||
import { S3Module } from "../s3/s3.module";
|
import { S3Module } from "../s3/s3.module";
|
||||||
import { ContentsController } from "./contents.controller";
|
import { ContentsController } from "./contents.controller";
|
||||||
import { ContentsService } from "./contents.service";
|
import { ContentsService } from "./contents.service";
|
||||||
import { ContentsRepository } from "./repositories/contents.repository";
|
import { ContentsRepository } from "./repositories/contents.repository";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [S3Module, AuthModule, MediaModule],
|
imports: [S3Module, AuthModule, MediaModule, RealtimeModule],
|
||||||
controllers: [ContentsController],
|
controllers: [ContentsController],
|
||||||
providers: [ContentsService, ContentsRepository],
|
providers: [ContentsService, ContentsRepository],
|
||||||
exports: [ContentsRepository],
|
exports: [ContentsRepository],
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { BadRequestException } from "@nestjs/common";
|
|||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { MediaService } from "../media/media.service";
|
import { MediaService } from "../media/media.service";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
import { S3Service } from "../s3/s3.service";
|
import { S3Service } from "../s3/s3.service";
|
||||||
import { ContentsService } from "./contents.service";
|
import { ContentsService } from "./contents.service";
|
||||||
import { ContentsRepository } from "./repositories/contents.repository";
|
import { ContentsRepository } from "./repositories/contents.repository";
|
||||||
@@ -49,6 +50,10 @@ describe("ContentsService", () => {
|
|||||||
del: jest.fn(),
|
del: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const mockEventsGateway = {
|
||||||
|
sendToUser: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
@@ -60,6 +65,7 @@ describe("ContentsService", () => {
|
|||||||
{ provide: MediaService, useValue: mockMediaService },
|
{ provide: MediaService, useValue: mockMediaService },
|
||||||
{ provide: ConfigService, useValue: mockConfigService },
|
{ provide: ConfigService, useValue: mockConfigService },
|
||||||
{ provide: CACHE_MANAGER, useValue: mockCacheManager },
|
{ provide: CACHE_MANAGER, useValue: mockCacheManager },
|
||||||
|
{ provide: EventsGateway, useValue: mockEventsGateway },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import type {
|
|||||||
} from "../common/interfaces/media.interface";
|
} from "../common/interfaces/media.interface";
|
||||||
import type { IStorageService } from "../common/interfaces/storage.interface";
|
import type { IStorageService } from "../common/interfaces/storage.interface";
|
||||||
import { MediaService } from "../media/media.service";
|
import { MediaService } from "../media/media.service";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
import { S3Service } from "../s3/s3.service";
|
import { S3Service } from "../s3/s3.service";
|
||||||
import { CreateContentDto } from "./dto/create-content.dto";
|
import { CreateContentDto } from "./dto/create-content.dto";
|
||||||
import { UploadContentDto } from "./dto/upload-content.dto";
|
import { UploadContentDto } from "./dto/upload-content.dto";
|
||||||
@@ -29,6 +30,7 @@ export class ContentsService {
|
|||||||
@Inject(MediaService) private readonly mediaService: IMediaService,
|
@Inject(MediaService) private readonly mediaService: IMediaService,
|
||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
@Inject(CACHE_MANAGER) private cacheManager: Cache,
|
||||||
|
private readonly eventsGateway: EventsGateway,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async clearContentsCache() {
|
private async clearContentsCache() {
|
||||||
@@ -48,6 +50,11 @@ export class ContentsService {
|
|||||||
data: UploadContentDto,
|
data: UploadContentDto,
|
||||||
) {
|
) {
|
||||||
this.logger.log(`Uploading and processing file for user ${userId}`);
|
this.logger.log(`Uploading and processing file for user ${userId}`);
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "starting",
|
||||||
|
progress: 0,
|
||||||
|
});
|
||||||
|
|
||||||
// 0. Validation du format et de la taille
|
// 0. Validation du format et de la taille
|
||||||
const allowedMimeTypes = [
|
const allowedMimeTypes = [
|
||||||
"image/png",
|
"image/png",
|
||||||
@@ -60,13 +67,25 @@ export class ContentsService {
|
|||||||
];
|
];
|
||||||
|
|
||||||
if (!allowedMimeTypes.includes(file.mimetype)) {
|
if (!allowedMimeTypes.includes(file.mimetype)) {
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "error",
|
||||||
|
message: "Format de fichier non supporté",
|
||||||
|
});
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
"Format de fichier non supporté. Formats acceptés: png, jpeg, jpg, webp, webm, mp4, mov, gif.",
|
"Format de fichier non supporté. Formats acceptés: png, jpeg, jpg, webp, webm, mp4, mov, gif.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const isGif = file.mimetype === "image/gif";
|
// Autodétermination du type si non fourni ou pour valider
|
||||||
const isVideo = file.mimetype.startsWith("video/");
|
let contentType: "meme" | "gif" | "video" = "meme";
|
||||||
|
if (file.mimetype === "image/gif") {
|
||||||
|
contentType = "gif";
|
||||||
|
} else if (file.mimetype.startsWith("video/")) {
|
||||||
|
contentType = "video";
|
||||||
|
}
|
||||||
|
|
||||||
|
const isGif = contentType === "gif";
|
||||||
|
const isVideo = contentType === "video";
|
||||||
let maxSizeKb: number;
|
let maxSizeKb: number;
|
||||||
|
|
||||||
if (isGif) {
|
if (isGif) {
|
||||||
@@ -78,23 +97,39 @@ export class ContentsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (file.size > maxSizeKb * 1024) {
|
if (file.size > maxSizeKb * 1024) {
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "error",
|
||||||
|
message: "Fichier trop volumineux",
|
||||||
|
});
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
`Fichier trop volumineux. Limite pour ${isGif ? "GIF" : isVideo ? "vidéo" : "image"}: ${maxSizeKb} Ko.`,
|
`Fichier trop volumineux. Limite pour ${isGif ? "GIF" : isVideo ? "vidéo" : "image"}: ${maxSizeKb} Ko.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. Scan Antivirus
|
// 1. Scan Antivirus
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "scanning",
|
||||||
|
progress: 20,
|
||||||
|
});
|
||||||
const scanResult = await this.mediaService.scanFile(
|
const scanResult = await this.mediaService.scanFile(
|
||||||
file.buffer,
|
file.buffer,
|
||||||
file.originalname,
|
file.originalname,
|
||||||
);
|
);
|
||||||
if (scanResult.isInfected) {
|
if (scanResult.isInfected) {
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "error",
|
||||||
|
message: "Fichier infecté",
|
||||||
|
});
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
`Le fichier est infecté par ${scanResult.virusName}`,
|
`Le fichier est infecté par ${scanResult.virusName}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Transcodage
|
// 2. Transcodage
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "processing",
|
||||||
|
progress: 40,
|
||||||
|
});
|
||||||
let processed: MediaProcessingResult;
|
let processed: MediaProcessingResult;
|
||||||
if (file.mimetype.startsWith("image/") && file.mimetype !== "image/gif") {
|
if (file.mimetype.startsWith("image/") && file.mimetype !== "image/gif") {
|
||||||
// Image -> WebP (format moderne, bien supporté)
|
// Image -> WebP (format moderne, bien supporté)
|
||||||
@@ -110,17 +145,34 @@ export class ContentsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. Upload vers S3
|
// 3. Upload vers S3
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "uploading_s3",
|
||||||
|
progress: 70,
|
||||||
|
});
|
||||||
const key = `contents/${userId}/${Date.now()}-${uuidv4()}.${processed.extension}`;
|
const key = `contents/${userId}/${Date.now()}-${uuidv4()}.${processed.extension}`;
|
||||||
await this.s3Service.uploadFile(key, processed.buffer, processed.mimeType);
|
await this.s3Service.uploadFile(key, processed.buffer, processed.mimeType);
|
||||||
this.logger.log(`File uploaded successfully to S3: ${key}`);
|
this.logger.log(`File uploaded successfully to S3: ${key}`);
|
||||||
|
|
||||||
// 4. Création en base de données
|
// 4. Création en base de données
|
||||||
return await this.create(userId, {
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "saving",
|
||||||
|
progress: 90,
|
||||||
|
});
|
||||||
|
const content = await this.create(userId, {
|
||||||
...data,
|
...data,
|
||||||
|
type: contentType, // Utiliser le type autodéterminé
|
||||||
storageKey: key,
|
storageKey: key,
|
||||||
mimeType: processed.mimeType,
|
mimeType: processed.mimeType,
|
||||||
fileSize: processed.size,
|
fileSize: processed.size,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.eventsGateway.sendToUser(userId, "upload_progress", {
|
||||||
|
status: "completed",
|
||||||
|
progress: 100,
|
||||||
|
contentId: content.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
return content;
|
||||||
}
|
}
|
||||||
|
|
||||||
async findAll(options: {
|
async findAll(options: {
|
||||||
|
|||||||
21
backend/src/database/schemas/comment_likes.ts
Normal file
21
backend/src/database/schemas/comment_likes.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { pgTable, primaryKey, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||||
|
import { comments } from "./comments";
|
||||||
|
import { users } from "./users";
|
||||||
|
|
||||||
|
export const commentLikes = pgTable(
|
||||||
|
"comment_likes",
|
||||||
|
{
|
||||||
|
commentId: uuid("comment_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => comments.id, { onDelete: "cascade" }),
|
||||||
|
userId: uuid("user_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => users.uuid, { onDelete: "cascade" }),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
},
|
||||||
|
(t) => ({
|
||||||
|
pk: primaryKey({ columns: [t.commentId, t.userId] }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
35
backend/src/database/schemas/comments.ts
Normal file
35
backend/src/database/schemas/comments.ts
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
import { index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||||
|
import { contents } from "./content";
|
||||||
|
import { users } from "./users";
|
||||||
|
|
||||||
|
export const comments = pgTable(
|
||||||
|
"comments",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
contentId: uuid("content_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => contents.id, { onDelete: "cascade" }),
|
||||||
|
userId: uuid("user_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => users.uuid, { onDelete: "cascade" }),
|
||||||
|
parentId: uuid("parent_id").references(() => comments.id, {
|
||||||
|
onDelete: "cascade",
|
||||||
|
}),
|
||||||
|
text: text("text").notNull(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
deletedAt: timestamp("deleted_at", { withTimezone: true }),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
contentIdIdx: index("comments_content_id_idx").on(table.contentId),
|
||||||
|
userIdIdx: index("comments_user_id_idx").on(table.userId),
|
||||||
|
parentIdIdx: index("comments_parent_id_idx").on(table.parentId),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export type CommentInDb = typeof comments.$inferSelect;
|
||||||
|
export type NewCommentInDb = typeof comments.$inferInsert;
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
export * from "./api_keys";
|
export * from "./api_keys";
|
||||||
export * from "./audit_logs";
|
export * from "./audit_logs";
|
||||||
export * from "./categories";
|
export * from "./categories";
|
||||||
|
export * from "./comment_likes";
|
||||||
|
export * from "./comments";
|
||||||
export * from "./content";
|
export * from "./content";
|
||||||
export * from "./favorites";
|
export * from "./favorites";
|
||||||
|
export * from "./messages";
|
||||||
export * from "./pgp";
|
export * from "./pgp";
|
||||||
export * from "./rbac";
|
export * from "./rbac";
|
||||||
export * from "./reports";
|
export * from "./reports";
|
||||||
|
|||||||
66
backend/src/database/schemas/messages.ts
Normal file
66
backend/src/database/schemas/messages.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import {
|
||||||
|
index,
|
||||||
|
pgTable,
|
||||||
|
primaryKey,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
uuid,
|
||||||
|
} from "drizzle-orm/pg-core";
|
||||||
|
import { users } from "./users";
|
||||||
|
|
||||||
|
export const conversations = pgTable("conversations", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const conversationParticipants = pgTable(
|
||||||
|
"conversation_participants",
|
||||||
|
{
|
||||||
|
conversationId: uuid("conversation_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => conversations.id, { onDelete: "cascade" }),
|
||||||
|
userId: uuid("user_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => users.uuid, { onDelete: "cascade" }),
|
||||||
|
joinedAt: timestamp("joined_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
},
|
||||||
|
(t) => ({
|
||||||
|
pk: primaryKey({ columns: [t.conversationId, t.userId] }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const messages = pgTable(
|
||||||
|
"messages",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
conversationId: uuid("conversation_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => conversations.id, { onDelete: "cascade" }),
|
||||||
|
senderId: uuid("sender_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => users.uuid, { onDelete: "cascade" }),
|
||||||
|
text: text("text").notNull(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
readAt: timestamp("read_at", { withTimezone: true }),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
conversationIdIdx: index("messages_conversation_id_idx").on(
|
||||||
|
table.conversationId,
|
||||||
|
),
|
||||||
|
senderIdIdx: index("messages_sender_id_idx").on(table.senderId),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
export type ConversationInDb = typeof conversations.$inferSelect;
|
||||||
|
export type NewConversationInDb = typeof conversations.$inferInsert;
|
||||||
|
export type MessageInDb = typeof messages.$inferSelect;
|
||||||
|
export type NewMessageInDb = typeof messages.$inferInsert;
|
||||||
@@ -21,14 +21,19 @@ const getPgpKey = () => process.env.PGP_ENCRYPTION_KEY || "default-pgp-key";
|
|||||||
* withAutomaticPgpDecrypt(users.email);
|
* withAutomaticPgpDecrypt(users.email);
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export const pgpEncrypted = customType<{ data: string; driverData: Buffer }>({
|
export const pgpEncrypted = customType<{
|
||||||
|
data: string | null;
|
||||||
|
driverData: Buffer | string | null | SQL;
|
||||||
|
}>({
|
||||||
dataType() {
|
dataType() {
|
||||||
return "bytea";
|
return "bytea";
|
||||||
},
|
},
|
||||||
toDriver(value: string): SQL {
|
toDriver(value: string | null): SQL | null {
|
||||||
|
if (value === null) return null;
|
||||||
return sql`pgp_sym_encrypt(${value}, ${getPgpKey()})`;
|
return sql`pgp_sym_encrypt(${value}, ${getPgpKey()})`;
|
||||||
},
|
},
|
||||||
fromDriver(value: Buffer | string): string {
|
fromDriver(value: Buffer | string | null | any): string | null {
|
||||||
|
if (value === null || value === undefined) return null;
|
||||||
if (typeof value === "string") return value;
|
if (typeof value === "string") return value;
|
||||||
return value.toString();
|
return value.toString();
|
||||||
},
|
},
|
||||||
@@ -41,7 +46,9 @@ export const pgpEncrypted = customType<{ data: string; driverData: Buffer }>({
|
|||||||
export function withAutomaticPgpDecrypt<T extends AnyPgColumn>(column: T): T {
|
export function withAutomaticPgpDecrypt<T extends AnyPgColumn>(column: T): T {
|
||||||
const originalGetSQL = column.getSQL.bind(column);
|
const originalGetSQL = column.getSQL.bind(column);
|
||||||
column.getSQL = () =>
|
column.getSQL = () =>
|
||||||
sql`pgp_sym_decrypt(${originalGetSQL()}, ${getPgpKey()})`.mapWith(column);
|
sql`pgp_sym_decrypt(${originalGetSQL()}, ${getPgpKey()})::text`.mapWith(
|
||||||
|
column,
|
||||||
|
);
|
||||||
return column;
|
return column;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,5 +66,7 @@ export function pgpSymDecrypt(
|
|||||||
column: AnyPgColumn,
|
column: AnyPgColumn,
|
||||||
key: string | SQL,
|
key: string | SQL,
|
||||||
): SQL<string> {
|
): SQL<string> {
|
||||||
return sql`pgp_sym_decrypt(${column}, ${key})`.mapWith(column) as SQL<string>;
|
return sql`pgp_sym_decrypt(${column}, ${key})::text`.mapWith(
|
||||||
|
column,
|
||||||
|
) as SQL<string>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,13 +29,15 @@ export const users = pgTable(
|
|||||||
displayName: varchar("display_name", { length: 32 }),
|
displayName: varchar("display_name", { length: 32 }),
|
||||||
|
|
||||||
username: varchar("username", { length: 32 }).notNull().unique(),
|
username: varchar("username", { length: 32 }).notNull().unique(),
|
||||||
passwordHash: varchar("password_hash", { length: 100 }).notNull(),
|
passwordHash: varchar("password_hash", { length: 255 }).notNull(),
|
||||||
avatarUrl: varchar("avatar_url", { length: 512 }),
|
avatarUrl: varchar("avatar_url", { length: 512 }),
|
||||||
bio: varchar("bio", { length: 255 }),
|
bio: varchar("bio", { length: 255 }),
|
||||||
|
|
||||||
// Sécurité
|
// Sécurité
|
||||||
twoFactorSecret: pgpEncrypted("two_factor_secret"),
|
twoFactorSecret: pgpEncrypted("two_factor_secret"),
|
||||||
isTwoFactorEnabled: boolean("is_two_factor_enabled").notNull().default(false),
|
isTwoFactorEnabled: boolean("is_two_factor_enabled").notNull().default(false),
|
||||||
|
showOnlineStatus: boolean("show_online_status").notNull().default(true),
|
||||||
|
showReadReceipts: boolean("show_read_receipts").notNull().default(true),
|
||||||
|
|
||||||
// RGPD & Conformité
|
// RGPD & Conformité
|
||||||
termsVersion: varchar("terms_version", { length: 16 }), // Version des CGU acceptées
|
termsVersion: varchar("terms_version", { length: 16 }), // Version des CGU acceptées
|
||||||
|
|||||||
11
backend/src/messages/dto/create-message.dto.ts
Normal file
11
backend/src/messages/dto/create-message.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { IsNotEmpty, IsString, IsUUID, MaxLength } from "class-validator";
|
||||||
|
|
||||||
|
export class CreateMessageDto {
|
||||||
|
@IsUUID()
|
||||||
|
recipientId!: string;
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
@MaxLength(2000)
|
||||||
|
text!: string;
|
||||||
|
}
|
||||||
53
backend/src/messages/messages.controller.ts
Normal file
53
backend/src/messages/messages.controller.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Req,
|
||||||
|
UseGuards,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||||
|
import type { AuthenticatedRequest } from "../common/interfaces/request.interface";
|
||||||
|
import { CreateMessageDto } from "./dto/create-message.dto";
|
||||||
|
import { MessagesService } from "./messages.service";
|
||||||
|
|
||||||
|
@Controller("messages")
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
export class MessagesController {
|
||||||
|
constructor(private readonly messagesService: MessagesService) {}
|
||||||
|
|
||||||
|
@Get("conversations")
|
||||||
|
getConversations(@Req() req: AuthenticatedRequest) {
|
||||||
|
return this.messagesService.getConversations(req.user.sub);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("unread-count")
|
||||||
|
getUnreadCount(@Req() req: AuthenticatedRequest) {
|
||||||
|
return this.messagesService.getUnreadCount(req.user.sub);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("conversations/with/:userId")
|
||||||
|
getConversationWithUser(
|
||||||
|
@Req() req: AuthenticatedRequest,
|
||||||
|
@Param("userId") targetUserId: string,
|
||||||
|
) {
|
||||||
|
return this.messagesService.getConversationWithUser(
|
||||||
|
req.user.sub,
|
||||||
|
targetUserId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("conversations/:id")
|
||||||
|
getMessages(
|
||||||
|
@Req() req: AuthenticatedRequest,
|
||||||
|
@Param("id") conversationId: string,
|
||||||
|
) {
|
||||||
|
return this.messagesService.getMessages(req.user.sub, conversationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
sendMessage(@Req() req: AuthenticatedRequest, @Body() dto: CreateMessageDto) {
|
||||||
|
return this.messagesService.sendMessage(req.user.sub, dto);
|
||||||
|
}
|
||||||
|
}
|
||||||
15
backend/src/messages/messages.module.ts
Normal file
15
backend/src/messages/messages.module.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { forwardRef, Module } from "@nestjs/common";
|
||||||
|
import { AuthModule } from "../auth/auth.module";
|
||||||
|
import { RealtimeModule } from "../realtime/realtime.module";
|
||||||
|
import { UsersModule } from "../users/users.module";
|
||||||
|
import { MessagesController } from "./messages.controller";
|
||||||
|
import { MessagesService } from "./messages.service";
|
||||||
|
import { MessagesRepository } from "./repositories/messages.repository";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AuthModule, RealtimeModule, forwardRef(() => UsersModule)],
|
||||||
|
controllers: [MessagesController],
|
||||||
|
providers: [MessagesService, MessagesRepository],
|
||||||
|
exports: [MessagesService],
|
||||||
|
})
|
||||||
|
export class MessagesModule {}
|
||||||
105
backend/src/messages/messages.service.spec.ts
Normal file
105
backend/src/messages/messages.service.spec.ts
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
import { ForbiddenException } from "@nestjs/common";
|
||||||
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
|
import { UsersService } from "../users/users.service";
|
||||||
|
import { MessagesService } from "./messages.service";
|
||||||
|
import { MessagesRepository } from "./repositories/messages.repository";
|
||||||
|
|
||||||
|
describe("MessagesService", () => {
|
||||||
|
let service: MessagesService;
|
||||||
|
let _repository: MessagesRepository;
|
||||||
|
let _eventsGateway: EventsGateway;
|
||||||
|
|
||||||
|
const mockMessagesRepository = {
|
||||||
|
findConversationBetweenUsers: jest.fn(),
|
||||||
|
createConversation: jest.fn(),
|
||||||
|
addParticipant: jest.fn(),
|
||||||
|
createMessage: jest.fn(),
|
||||||
|
findAllConversations: jest.fn(),
|
||||||
|
isParticipant: jest.fn(),
|
||||||
|
getParticipants: jest.fn(),
|
||||||
|
findMessagesByConversationId: jest.fn(),
|
||||||
|
markAsRead: jest.fn(),
|
||||||
|
countUnreadMessages: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockEventsGateway = {
|
||||||
|
sendToUser: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockUsersService = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
MessagesService,
|
||||||
|
{ provide: MessagesRepository, useValue: mockMessagesRepository },
|
||||||
|
{ provide: EventsGateway, useValue: mockEventsGateway },
|
||||||
|
{ provide: UsersService, useValue: mockUsersService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
service = module.get<MessagesService>(MessagesService);
|
||||||
|
_repository = module.get<MessagesRepository>(MessagesRepository);
|
||||||
|
_eventsGateway = module.get<EventsGateway>(EventsGateway);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendMessage", () => {
|
||||||
|
it("should send message to existing conversation", async () => {
|
||||||
|
const senderId = "s1";
|
||||||
|
const dto = { recipientId: "r1", text: "hello" };
|
||||||
|
mockMessagesRepository.findConversationBetweenUsers.mockResolvedValue({
|
||||||
|
id: "conv1",
|
||||||
|
});
|
||||||
|
mockMessagesRepository.createMessage.mockResolvedValue({
|
||||||
|
id: "m1",
|
||||||
|
text: "hello",
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await service.sendMessage(senderId, dto);
|
||||||
|
|
||||||
|
expect(result.id).toBe("m1");
|
||||||
|
expect(mockEventsGateway.sendToUser).toHaveBeenCalledWith(
|
||||||
|
"r1",
|
||||||
|
"new_message",
|
||||||
|
expect.anything(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should create new conversation if not exists", async () => {
|
||||||
|
const senderId = "s1";
|
||||||
|
const dto = { recipientId: "r1", text: "hello" };
|
||||||
|
mockMessagesRepository.findConversationBetweenUsers.mockResolvedValue(null);
|
||||||
|
mockMessagesRepository.createConversation.mockResolvedValue({
|
||||||
|
id: "new_conv",
|
||||||
|
});
|
||||||
|
mockMessagesRepository.createMessage.mockResolvedValue({ id: "m1" });
|
||||||
|
|
||||||
|
await service.sendMessage(senderId, dto);
|
||||||
|
|
||||||
|
expect(mockMessagesRepository.createConversation).toHaveBeenCalled();
|
||||||
|
expect(mockMessagesRepository.addParticipant).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getMessages", () => {
|
||||||
|
it("should return messages if user is participant", async () => {
|
||||||
|
mockMessagesRepository.isParticipant.mockResolvedValue(true);
|
||||||
|
mockMessagesRepository.findMessagesByConversationId.mockResolvedValue([
|
||||||
|
{ id: "m1" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const result = await service.getMessages("u1", "conv1");
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should throw ForbiddenException if user is not participant", async () => {
|
||||||
|
mockMessagesRepository.isParticipant.mockResolvedValue(false);
|
||||||
|
await expect(service.getMessages("u1", "conv1")).rejects.toThrow(
|
||||||
|
ForbiddenException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
125
backend/src/messages/messages.service.ts
Normal file
125
backend/src/messages/messages.service.ts
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
import {
|
||||||
|
ForbiddenException,
|
||||||
|
forwardRef,
|
||||||
|
Inject,
|
||||||
|
Injectable,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
|
import { UsersService } from "../users/users.service";
|
||||||
|
import type { CreateMessageDto } from "./dto/create-message.dto";
|
||||||
|
import { MessagesRepository } from "./repositories/messages.repository";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MessagesService {
|
||||||
|
constructor(
|
||||||
|
private readonly messagesRepository: MessagesRepository,
|
||||||
|
private readonly eventsGateway: EventsGateway,
|
||||||
|
@Inject(forwardRef(() => UsersService))
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async sendMessage(senderId: string, dto: CreateMessageDto) {
|
||||||
|
let conversation = await this.messagesRepository.findConversationBetweenUsers(
|
||||||
|
senderId,
|
||||||
|
dto.recipientId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!conversation) {
|
||||||
|
const newConv = await this.messagesRepository.createConversation();
|
||||||
|
await this.messagesRepository.addParticipant(newConv.id, senderId);
|
||||||
|
await this.messagesRepository.addParticipant(newConv.id, dto.recipientId);
|
||||||
|
conversation = newConv;
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = await this.messagesRepository.createMessage({
|
||||||
|
conversationId: conversation.id,
|
||||||
|
senderId,
|
||||||
|
text: dto.text,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Notify recipient via WebSocket
|
||||||
|
this.eventsGateway.sendToUser(dto.recipientId, "new_message", {
|
||||||
|
conversationId: conversation.id,
|
||||||
|
message,
|
||||||
|
});
|
||||||
|
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getConversations(userId: string) {
|
||||||
|
return this.messagesRepository.findAllConversations(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUnreadCount(userId: string) {
|
||||||
|
return this.messagesRepository.countUnreadMessages(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getConversationWithUser(userId: string, targetUserId: string) {
|
||||||
|
return this.messagesRepository.findConversationBetweenUsers(
|
||||||
|
userId,
|
||||||
|
targetUserId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMessages(userId: string, conversationId: string) {
|
||||||
|
const isParticipant = await this.messagesRepository.isParticipant(
|
||||||
|
conversationId,
|
||||||
|
userId,
|
||||||
|
);
|
||||||
|
if (!isParticipant) {
|
||||||
|
throw new ForbiddenException("You are not part of this conversation");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Récupérer les préférences de l'utilisateur actuel
|
||||||
|
const user = await this.usersService.findOne(userId);
|
||||||
|
|
||||||
|
// Marquer comme lus seulement si l'utilisateur l'autorise
|
||||||
|
if (user?.showReadReceipts) {
|
||||||
|
await this.messagesRepository.markAsRead(conversationId, userId);
|
||||||
|
|
||||||
|
// Notifier l'expéditeur que les messages ont été lus
|
||||||
|
const participants =
|
||||||
|
await this.messagesRepository.getParticipants(conversationId);
|
||||||
|
const otherParticipant = participants.find((p) => p.userId !== userId);
|
||||||
|
if (otherParticipant) {
|
||||||
|
this.eventsGateway.sendToUser(otherParticipant.userId, "messages_read", {
|
||||||
|
conversationId,
|
||||||
|
readerId: userId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.messagesRepository.findMessagesByConversationId(conversationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async markAsRead(userId: string, conversationId: string) {
|
||||||
|
const isParticipant = await this.messagesRepository.isParticipant(
|
||||||
|
conversationId,
|
||||||
|
userId,
|
||||||
|
);
|
||||||
|
if (!isParticipant) {
|
||||||
|
throw new ForbiddenException("You are not part of this conversation");
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await this.usersService.findOne(userId);
|
||||||
|
if (!user?.showReadReceipts) return;
|
||||||
|
|
||||||
|
const result = await this.messagesRepository.markAsRead(
|
||||||
|
conversationId,
|
||||||
|
userId,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Notifier l'autre participant
|
||||||
|
const participants =
|
||||||
|
await this.messagesRepository.getParticipants(conversationId);
|
||||||
|
const otherParticipant = participants.find((p) => p.userId !== userId);
|
||||||
|
if (otherParticipant) {
|
||||||
|
this.eventsGateway.sendToUser(otherParticipant.userId, "messages_read", {
|
||||||
|
conversationId,
|
||||||
|
readerId: userId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
167
backend/src/messages/repositories/messages.repository.ts
Normal file
167
backend/src/messages/repositories/messages.repository.ts
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
||||||
|
import { DatabaseService } from "../../database/database.service";
|
||||||
|
import {
|
||||||
|
conversationParticipants,
|
||||||
|
conversations,
|
||||||
|
messages,
|
||||||
|
users,
|
||||||
|
} from "../../database/schemas";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MessagesRepository {
|
||||||
|
constructor(private readonly databaseService: DatabaseService) {}
|
||||||
|
|
||||||
|
async findConversationBetweenUsers(userId1: string, userId2: string) {
|
||||||
|
const results = await this.databaseService.db
|
||||||
|
.select({ id: conversations.id })
|
||||||
|
.from(conversations)
|
||||||
|
.innerJoin(
|
||||||
|
conversationParticipants,
|
||||||
|
eq(conversations.id, conversationParticipants.conversationId),
|
||||||
|
)
|
||||||
|
.where(inArray(conversationParticipants.userId, [userId1, userId2]))
|
||||||
|
.groupBy(conversations.id)
|
||||||
|
.having(sql`count(${conversations.id}) = 2`);
|
||||||
|
|
||||||
|
return results[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
async createConversation() {
|
||||||
|
const [conv] = await this.databaseService.db
|
||||||
|
.insert(conversations)
|
||||||
|
.values({})
|
||||||
|
.returning();
|
||||||
|
return conv;
|
||||||
|
}
|
||||||
|
|
||||||
|
async addParticipant(conversationId: string, userId: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.insert(conversationParticipants)
|
||||||
|
.values({ conversationId, userId });
|
||||||
|
}
|
||||||
|
|
||||||
|
async createMessage(data: {
|
||||||
|
conversationId: string;
|
||||||
|
senderId: string;
|
||||||
|
text: string;
|
||||||
|
}) {
|
||||||
|
const [msg] = await this.databaseService.db
|
||||||
|
.insert(messages)
|
||||||
|
.values(data)
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
// Update conversation updatedAt
|
||||||
|
await this.databaseService.db
|
||||||
|
.update(conversations)
|
||||||
|
.set({ updatedAt: new Date() })
|
||||||
|
.where(eq(conversations.id, data.conversationId));
|
||||||
|
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAllConversations(userId: string) {
|
||||||
|
// Sous-requête pour trouver les IDs des conversations de l'utilisateur
|
||||||
|
const userConvs = this.databaseService.db
|
||||||
|
.select({ id: conversationParticipants.conversationId })
|
||||||
|
.from(conversationParticipants)
|
||||||
|
.where(eq(conversationParticipants.userId, userId));
|
||||||
|
|
||||||
|
return this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: conversations.id,
|
||||||
|
updatedAt: conversations.updatedAt,
|
||||||
|
lastMessage: {
|
||||||
|
text: messages.text,
|
||||||
|
createdAt: messages.createdAt,
|
||||||
|
},
|
||||||
|
recipient: {
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
displayName: users.displayName,
|
||||||
|
avatarUrl: users.avatarUrl,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.from(conversations)
|
||||||
|
.innerJoin(
|
||||||
|
conversationParticipants,
|
||||||
|
eq(conversations.id, conversationParticipants.conversationId),
|
||||||
|
)
|
||||||
|
.innerJoin(users, eq(conversationParticipants.userId, users.uuid))
|
||||||
|
.leftJoin(messages, eq(conversations.id, messages.conversationId))
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
inArray(conversations.id, userConvs),
|
||||||
|
eq(conversationParticipants.userId, users.uuid),
|
||||||
|
sql`${users.uuid} != ${userId}`,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.orderBy(desc(conversations.updatedAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findMessagesByConversationId(conversationId: string, limit = 50) {
|
||||||
|
return this.databaseService.db
|
||||||
|
.select({
|
||||||
|
id: messages.id,
|
||||||
|
text: messages.text,
|
||||||
|
createdAt: messages.createdAt,
|
||||||
|
senderId: messages.senderId,
|
||||||
|
readAt: messages.readAt,
|
||||||
|
})
|
||||||
|
.from(messages)
|
||||||
|
.where(eq(messages.conversationId, conversationId))
|
||||||
|
.orderBy(desc(messages.createdAt))
|
||||||
|
.limit(limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
async isParticipant(conversationId: string, userId: string) {
|
||||||
|
const [participant] = await this.databaseService.db
|
||||||
|
.select()
|
||||||
|
.from(conversationParticipants)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(conversationParticipants.conversationId, conversationId),
|
||||||
|
eq(conversationParticipants.userId, userId),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return !!participant;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getParticipants(conversationId: string) {
|
||||||
|
return this.databaseService.db
|
||||||
|
.select({ userId: conversationParticipants.userId })
|
||||||
|
.from(conversationParticipants)
|
||||||
|
.where(eq(conversationParticipants.conversationId, conversationId));
|
||||||
|
}
|
||||||
|
|
||||||
|
async markAsRead(conversationId: string, userId: string) {
|
||||||
|
await this.databaseService.db
|
||||||
|
.update(messages)
|
||||||
|
.set({ readAt: new Date() })
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(messages.conversationId, conversationId),
|
||||||
|
sql`${messages.senderId} != ${userId}`,
|
||||||
|
sql`${messages.readAt} IS NULL`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async countUnreadMessages(userId: string) {
|
||||||
|
const result = await this.databaseService.db
|
||||||
|
.select({ count: sql<number>`count(*)` })
|
||||||
|
.from(messages)
|
||||||
|
.innerJoin(
|
||||||
|
conversationParticipants,
|
||||||
|
eq(messages.conversationId, conversationParticipants.conversationId),
|
||||||
|
)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(conversationParticipants.userId, userId),
|
||||||
|
sql`${messages.senderId} != ${userId}`,
|
||||||
|
sql`${messages.readAt} IS NULL`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return Number(result[0]?.count || 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
60
backend/src/realtime/events.gateway.spec.ts
Normal file
60
backend/src/realtime/events.gateway.spec.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
|
import { JwtService } from "../crypto/services/jwt.service";
|
||||||
|
import { UsersService } from "../users/users.service";
|
||||||
|
import { EventsGateway } from "./events.gateway";
|
||||||
|
|
||||||
|
describe("EventsGateway", () => {
|
||||||
|
let gateway: EventsGateway;
|
||||||
|
let _jwtService: JwtService;
|
||||||
|
|
||||||
|
const mockJwtService = {
|
||||||
|
verifyJwt: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockConfigService = {
|
||||||
|
get: jest.fn().mockReturnValue("secret-password-32-chars-long-!!!"),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mockUsersService = {
|
||||||
|
findOne: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
EventsGateway,
|
||||||
|
{ provide: JwtService, useValue: mockJwtService },
|
||||||
|
{ provide: ConfigService, useValue: mockConfigService },
|
||||||
|
{ provide: UsersService, useValue: mockUsersService },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
gateway = module.get<EventsGateway>(EventsGateway);
|
||||||
|
_jwtService = module.get<JwtService>(JwtService);
|
||||||
|
gateway.server = {
|
||||||
|
to: jest.fn().mockReturnThis(),
|
||||||
|
emit: jest.fn(),
|
||||||
|
} as any;
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should be defined", () => {
|
||||||
|
expect(gateway).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendToUser", () => {
|
||||||
|
it("should emit event to user room", () => {
|
||||||
|
const userId = "user123";
|
||||||
|
const event = "test_event";
|
||||||
|
const data = { foo: "bar" };
|
||||||
|
|
||||||
|
gateway.sendToUser(userId, event, data);
|
||||||
|
|
||||||
|
expect(gateway.server.to).toHaveBeenCalledWith(`user:${userId}`);
|
||||||
|
expect(gateway.server.to(`user:${userId}`).emit).toHaveBeenCalledWith(
|
||||||
|
event,
|
||||||
|
data,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
220
backend/src/realtime/events.gateway.ts
Normal file
220
backend/src/realtime/events.gateway.ts
Normal file
@@ -0,0 +1,220 @@
|
|||||||
|
import { forwardRef, Inject, Logger } from "@nestjs/common";
|
||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import {
|
||||||
|
ConnectedSocket,
|
||||||
|
MessageBody,
|
||||||
|
OnGatewayConnection,
|
||||||
|
OnGatewayDisconnect,
|
||||||
|
OnGatewayInit,
|
||||||
|
SubscribeMessage,
|
||||||
|
WebSocketGateway,
|
||||||
|
WebSocketServer,
|
||||||
|
} from "@nestjs/websockets";
|
||||||
|
import { getIronSession } from "iron-session";
|
||||||
|
import { Server, Socket } from "socket.io";
|
||||||
|
import { getSessionOptions, SessionData } from "../auth/session.config";
|
||||||
|
import { JwtService } from "../crypto/services/jwt.service";
|
||||||
|
import { UsersService } from "../users/users.service";
|
||||||
|
|
||||||
|
@WebSocketGateway({
|
||||||
|
transports: ["websocket"],
|
||||||
|
cors: {
|
||||||
|
origin: (
|
||||||
|
origin: string,
|
||||||
|
callback: (err: Error | null, allow?: boolean) => void,
|
||||||
|
) => {
|
||||||
|
// Autoriser si pas d'origine (ex: app mobile ou serveur à serveur)
|
||||||
|
// ou si on est en développement local
|
||||||
|
if (
|
||||||
|
!origin ||
|
||||||
|
origin.includes("localhost") ||
|
||||||
|
origin.includes("127.0.0.1")
|
||||||
|
) {
|
||||||
|
callback(null, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// En production, on peut restreindre via une variable d'environnement
|
||||||
|
const domainName = process.env.CORS_DOMAIN_NAME;
|
||||||
|
if (!domainName || domainName === "*") {
|
||||||
|
callback(null, true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowedOrigins = domainName.split(",").map((o) => o.trim());
|
||||||
|
if (allowedOrigins.includes(origin)) {
|
||||||
|
callback(null, true);
|
||||||
|
} else {
|
||||||
|
callback(new Error("Not allowed by CORS"));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
credentials: true,
|
||||||
|
methods: ["GET", "POST"],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
export class EventsGateway
|
||||||
|
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
|
||||||
|
{
|
||||||
|
@WebSocketServer()
|
||||||
|
server!: Server;
|
||||||
|
|
||||||
|
private readonly logger = new Logger(EventsGateway.name);
|
||||||
|
private readonly onlineUsers = new Map<string, Set<string>>(); // userId -> Set of socketIds
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly configService: ConfigService,
|
||||||
|
@Inject(forwardRef(() => UsersService))
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
afterInit(_server: Server) {
|
||||||
|
this.logger.log("WebSocket Gateway initialized");
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleConnection(client: Socket) {
|
||||||
|
try {
|
||||||
|
// Simuler un objet Request/Response pour iron-session
|
||||||
|
const req: any = {
|
||||||
|
headers: client.handshake.headers,
|
||||||
|
};
|
||||||
|
const res: any = {
|
||||||
|
setHeader: () => {},
|
||||||
|
getHeader: () => {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const session = await getIronSession<SessionData>(
|
||||||
|
req,
|
||||||
|
res,
|
||||||
|
getSessionOptions(this.configService.get("SESSION_PASSWORD") as string),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!session.accessToken) {
|
||||||
|
this.logger.warn(`Client ${client.id} unauthorized connection`);
|
||||||
|
// Permettre les connexions anonymes pour voir les commentaires en temps réel ?
|
||||||
|
// Pour l'instant on déconnecte car le système actuel semble exiger l'auth
|
||||||
|
client.disconnect();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await this.jwtService.verifyJwt(session.accessToken);
|
||||||
|
if (!payload.sub) {
|
||||||
|
throw new Error("Invalid token payload: missing sub");
|
||||||
|
}
|
||||||
|
|
||||||
|
client.data.user = payload;
|
||||||
|
|
||||||
|
// Rejoindre une room personnelle pour les notifications
|
||||||
|
client.join(`user:${payload.sub}`);
|
||||||
|
|
||||||
|
// Gérer le statut en ligne
|
||||||
|
const userId = payload.sub as string;
|
||||||
|
|
||||||
|
if (!this.onlineUsers.has(userId)) {
|
||||||
|
this.onlineUsers.set(userId, new Set());
|
||||||
|
|
||||||
|
// Vérifier les préférences de l'utilisateur
|
||||||
|
const user = await this.usersService.findOne(userId);
|
||||||
|
if (user?.showOnlineStatus) {
|
||||||
|
this.broadcastStatus(userId, "online");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.onlineUsers.get(userId)?.add(client.id);
|
||||||
|
|
||||||
|
this.logger.log(`Client connected: ${client.id} (User: ${payload.sub})`);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(`Connection error for client ${client.id}: ${error}`);
|
||||||
|
client.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleDisconnect(client: Socket) {
|
||||||
|
const userId = client.data.user?.sub;
|
||||||
|
if (userId && this.onlineUsers.has(userId)) {
|
||||||
|
const sockets = this.onlineUsers.get(userId);
|
||||||
|
sockets?.delete(client.id);
|
||||||
|
if (sockets?.size === 0) {
|
||||||
|
this.onlineUsers.delete(userId);
|
||||||
|
|
||||||
|
const user = await this.usersService.findOne(userId);
|
||||||
|
if (user?.showOnlineStatus) {
|
||||||
|
this.broadcastStatus(userId, "offline");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.logger.log(`Client disconnected: ${client.id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
broadcastStatus(userId: string, status: "online" | "offline") {
|
||||||
|
this.server.emit("user_status", { userId, status });
|
||||||
|
}
|
||||||
|
|
||||||
|
isUserOnline(userId: string): boolean {
|
||||||
|
return this.onlineUsers.has(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage("join_content")
|
||||||
|
handleJoinContent(
|
||||||
|
@ConnectedSocket() client: Socket,
|
||||||
|
@MessageBody() contentId: string,
|
||||||
|
) {
|
||||||
|
client.join(`content:${contentId}`);
|
||||||
|
this.logger.log(`Client ${client.id} joined content room: ${contentId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage("leave_content")
|
||||||
|
handleLeaveContent(
|
||||||
|
@ConnectedSocket() client: Socket,
|
||||||
|
@MessageBody() contentId: string,
|
||||||
|
) {
|
||||||
|
client.leave(`content:${contentId}`);
|
||||||
|
this.logger.log(`Client ${client.id} left content room: ${contentId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage("typing")
|
||||||
|
async handleTyping(
|
||||||
|
@ConnectedSocket() client: Socket,
|
||||||
|
@MessageBody() data: { recipientId: string; isTyping: boolean },
|
||||||
|
) {
|
||||||
|
const userId = client.data.user?.sub;
|
||||||
|
if (!userId) return;
|
||||||
|
|
||||||
|
// Optionnel: vérifier si l'utilisateur autorise le statut en ligne avant d'émettre "typing"
|
||||||
|
// ou si on considère que typing est une interaction directe qui outrepasse le statut.
|
||||||
|
// Instagram affiche "Typing..." même si le statut en ligne est désactivé si on est dans le chat.
|
||||||
|
// Mais par souci de cohérence avec "showOnlineStatus", on peut le vérifier.
|
||||||
|
const user = await this.usersService.findOne(userId);
|
||||||
|
if (!user?.showOnlineStatus) return;
|
||||||
|
|
||||||
|
this.server.to(`user:${data.recipientId}`).emit("user_typing", {
|
||||||
|
userId,
|
||||||
|
isTyping: data.isTyping,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage("check_status")
|
||||||
|
async handleCheckStatus(
|
||||||
|
@ConnectedSocket() _client: Socket,
|
||||||
|
@MessageBody() userId: string,
|
||||||
|
) {
|
||||||
|
const isOnline = this.onlineUsers.has(userId);
|
||||||
|
if (!isOnline) return { userId, status: "offline" };
|
||||||
|
|
||||||
|
const user = await this.usersService.findOne(userId);
|
||||||
|
if (!user?.showOnlineStatus) return { userId, status: "offline" };
|
||||||
|
|
||||||
|
return {
|
||||||
|
userId,
|
||||||
|
status: "online",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Méthode utilitaire pour envoyer des messages à un utilisateur spécifique
|
||||||
|
sendToUser(userId: string, event: string, data: any) {
|
||||||
|
this.server.to(`user:${userId}`).emit(event, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
sendToContent(contentId: string, event: string, data: any) {
|
||||||
|
this.server.to(`content:${contentId}`).emit(event, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
12
backend/src/realtime/realtime.module.ts
Normal file
12
backend/src/realtime/realtime.module.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { forwardRef, Module } from "@nestjs/common";
|
||||||
|
import { ConfigModule } from "@nestjs/config";
|
||||||
|
import { CryptoModule } from "../crypto/crypto.module";
|
||||||
|
import { UsersModule } from "../users/users.module";
|
||||||
|
import { EventsGateway } from "./events.gateway";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [CryptoModule, ConfigModule, forwardRef(() => UsersModule)],
|
||||||
|
providers: [EventsGateway],
|
||||||
|
exports: [EventsGateway],
|
||||||
|
})
|
||||||
|
export class RealtimeModule {}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { IsOptional, IsString, MaxLength } from "class-validator";
|
import { IsBoolean, IsOptional, IsString, MaxLength } from "class-validator";
|
||||||
|
|
||||||
export class UpdateUserDto {
|
export class UpdateUserDto {
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@@ -22,4 +22,12 @@ export class UpdateUserDto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
role?: string;
|
role?: string;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
showOnlineStatus?: boolean;
|
||||||
|
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
showReadReceipts?: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
import { and, eq, lte, sql } from "drizzle-orm";
|
import { and, eq, ilike, lte, or, sql } from "drizzle-orm";
|
||||||
import { DatabaseService } from "../../database/database.service";
|
import { DatabaseService } from "../../database/database.service";
|
||||||
import { contents, favorites, users } from "../../database/schemas";
|
import { contents, favorites, users } from "../../database/schemas";
|
||||||
|
|
||||||
@@ -47,6 +47,8 @@ export class UsersRepository {
|
|||||||
bio: users.bio,
|
bio: users.bio,
|
||||||
status: users.status,
|
status: users.status,
|
||||||
isTwoFactorEnabled: users.isTwoFactorEnabled,
|
isTwoFactorEnabled: users.isTwoFactorEnabled,
|
||||||
|
showOnlineStatus: users.showOnlineStatus,
|
||||||
|
showReadReceipts: users.showReadReceipts,
|
||||||
createdAt: users.createdAt,
|
createdAt: users.createdAt,
|
||||||
updatedAt: users.updatedAt,
|
updatedAt: users.updatedAt,
|
||||||
})
|
})
|
||||||
@@ -97,6 +99,24 @@ export class UsersRepository {
|
|||||||
return result[0] || null;
|
return result[0] || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async search(query: string) {
|
||||||
|
return this.databaseService.db
|
||||||
|
.select({
|
||||||
|
uuid: users.uuid,
|
||||||
|
username: users.username,
|
||||||
|
displayName: users.displayName,
|
||||||
|
avatarUrl: users.avatarUrl,
|
||||||
|
})
|
||||||
|
.from(users)
|
||||||
|
.where(
|
||||||
|
or(
|
||||||
|
ilike(users.username, `%${query}%`),
|
||||||
|
ilike(users.displayName, `%${query}%`),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(10);
|
||||||
|
}
|
||||||
|
|
||||||
async findOne(uuid: string) {
|
async findOne(uuid: string) {
|
||||||
const result = await this.databaseService.db
|
const result = await this.databaseService.db
|
||||||
.select()
|
.select()
|
||||||
|
|||||||
@@ -54,6 +54,12 @@ export class UsersController {
|
|||||||
return this.usersService.findPublicProfile(username);
|
return this.usersService.findPublicProfile(username);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get("search")
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
|
search(@Query("q") query: string) {
|
||||||
|
return this.usersService.search(query);
|
||||||
|
}
|
||||||
|
|
||||||
// Gestion de son propre compte
|
// Gestion de son propre compte
|
||||||
@Get("me")
|
@Get("me")
|
||||||
@UseGuards(AuthGuard)
|
@UseGuards(AuthGuard)
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
import { forwardRef, Module } from "@nestjs/common";
|
import { forwardRef, Module } from "@nestjs/common";
|
||||||
import { AuthModule } from "../auth/auth.module";
|
import { AuthModule } from "../auth/auth.module";
|
||||||
import { MediaModule } from "../media/media.module";
|
import { MediaModule } from "../media/media.module";
|
||||||
|
import { RealtimeModule } from "../realtime/realtime.module";
|
||||||
import { S3Module } from "../s3/s3.module";
|
import { S3Module } from "../s3/s3.module";
|
||||||
import { UsersRepository } from "./repositories/users.repository";
|
import { UsersRepository } from "./repositories/users.repository";
|
||||||
import { UsersController } from "./users.controller";
|
import { UsersController } from "./users.controller";
|
||||||
import { UsersService } from "./users.service";
|
import { UsersService } from "./users.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [forwardRef(() => AuthModule), MediaModule, S3Module],
|
imports: [
|
||||||
|
forwardRef(() => AuthModule),
|
||||||
|
MediaModule,
|
||||||
|
S3Module,
|
||||||
|
forwardRef(() => RealtimeModule),
|
||||||
|
],
|
||||||
controllers: [UsersController],
|
controllers: [UsersController],
|
||||||
providers: [UsersService, UsersRepository],
|
providers: [UsersService, UsersRepository],
|
||||||
exports: [UsersService, UsersRepository],
|
exports: [UsersService, UsersRepository],
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import { ConfigService } from "@nestjs/config";
|
|||||||
import { Test, TestingModule } from "@nestjs/testing";
|
import { Test, TestingModule } from "@nestjs/testing";
|
||||||
import { RbacService } from "../auth/rbac.service";
|
import { RbacService } from "../auth/rbac.service";
|
||||||
import { MediaService } from "../media/media.service";
|
import { MediaService } from "../media/media.service";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
import { S3Service } from "../s3/s3.service";
|
import { S3Service } from "../s3/s3.service";
|
||||||
import { UsersRepository } from "./repositories/users.repository";
|
import { UsersRepository } from "./repositories/users.repository";
|
||||||
import { UsersService } from "./users.service";
|
import { UsersService } from "./users.service";
|
||||||
@@ -49,6 +50,7 @@ describe("UsersService", () => {
|
|||||||
|
|
||||||
const mockRbacService = {
|
const mockRbacService = {
|
||||||
getUserRoles: jest.fn(),
|
getUserRoles: jest.fn(),
|
||||||
|
assignRoleToUser: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
const mockMediaService = {
|
const mockMediaService = {
|
||||||
@@ -65,6 +67,11 @@ describe("UsersService", () => {
|
|||||||
get: jest.fn(),
|
get: jest.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const mockEventsGateway = {
|
||||||
|
isUserOnline: jest.fn(),
|
||||||
|
broadcastStatus: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
|
|
||||||
@@ -77,6 +84,7 @@ describe("UsersService", () => {
|
|||||||
{ provide: MediaService, useValue: mockMediaService },
|
{ provide: MediaService, useValue: mockMediaService },
|
||||||
{ provide: S3Service, useValue: mockS3Service },
|
{ provide: S3Service, useValue: mockS3Service },
|
||||||
{ provide: ConfigService, useValue: mockConfigService },
|
{ provide: ConfigService, useValue: mockConfigService },
|
||||||
|
{ provide: EventsGateway, useValue: mockEventsGateway },
|
||||||
],
|
],
|
||||||
}).compile();
|
}).compile();
|
||||||
|
|
||||||
@@ -108,6 +116,7 @@ describe("UsersService", () => {
|
|||||||
describe("findOne", () => {
|
describe("findOne", () => {
|
||||||
it("should find a user", async () => {
|
it("should find a user", async () => {
|
||||||
mockUsersRepository.findOne.mockResolvedValue({ uuid: "uuid1" });
|
mockUsersRepository.findOne.mockResolvedValue({ uuid: "uuid1" });
|
||||||
|
mockRbacService.getUserRoles.mockResolvedValue([]);
|
||||||
const result = await service.findOne("uuid1");
|
const result = await service.findOne("uuid1");
|
||||||
expect(result.uuid).toBe("uuid1");
|
expect(result.uuid).toBe("uuid1");
|
||||||
});
|
});
|
||||||
@@ -139,6 +148,7 @@ describe("UsersService", () => {
|
|||||||
describe("findByEmailHash", () => {
|
describe("findByEmailHash", () => {
|
||||||
it("should call repository.findByEmailHash", async () => {
|
it("should call repository.findByEmailHash", async () => {
|
||||||
mockUsersRepository.findByEmailHash.mockResolvedValue({ uuid: "u1" });
|
mockUsersRepository.findByEmailHash.mockResolvedValue({ uuid: "u1" });
|
||||||
|
mockRbacService.getUserRoles.mockResolvedValue([]);
|
||||||
const result = await service.findByEmailHash("hash");
|
const result = await service.findByEmailHash("hash");
|
||||||
expect(result.uuid).toBe("u1");
|
expect(result.uuid).toBe("u1");
|
||||||
expect(mockUsersRepository.findByEmailHash).toHaveBeenCalledWith("hash");
|
expect(mockUsersRepository.findByEmailHash).toHaveBeenCalledWith("hash");
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { RbacService } from "../auth/rbac.service";
|
|||||||
import type { IMediaService } from "../common/interfaces/media.interface";
|
import type { IMediaService } from "../common/interfaces/media.interface";
|
||||||
import type { IStorageService } from "../common/interfaces/storage.interface";
|
import type { IStorageService } from "../common/interfaces/storage.interface";
|
||||||
import { MediaService } from "../media/media.service";
|
import { MediaService } from "../media/media.service";
|
||||||
|
import { EventsGateway } from "../realtime/events.gateway";
|
||||||
import { S3Service } from "../s3/s3.service";
|
import { S3Service } from "../s3/s3.service";
|
||||||
import { UpdateUserDto } from "./dto/update-user.dto";
|
import { UpdateUserDto } from "./dto/update-user.dto";
|
||||||
import { UsersRepository } from "./repositories/users.repository";
|
import { UsersRepository } from "./repositories/users.repository";
|
||||||
@@ -27,6 +28,8 @@ export class UsersService {
|
|||||||
private readonly rbacService: RbacService,
|
private readonly rbacService: RbacService,
|
||||||
@Inject(MediaService) private readonly mediaService: IMediaService,
|
@Inject(MediaService) private readonly mediaService: IMediaService,
|
||||||
@Inject(S3Service) private readonly s3Service: IStorageService,
|
@Inject(S3Service) private readonly s3Service: IStorageService,
|
||||||
|
@Inject(forwardRef(() => EventsGateway))
|
||||||
|
private readonly eventsGateway: EventsGateway,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async clearUserCache(username?: string) {
|
private async clearUserCache(username?: string) {
|
||||||
@@ -45,7 +48,19 @@ export class UsersService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async findByEmailHash(emailHash: string) {
|
async findByEmailHash(emailHash: string) {
|
||||||
return await this.usersRepository.findByEmailHash(emailHash);
|
const user = await this.usersRepository.findByEmailHash(emailHash);
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
const roles = await this.rbacService.getUserRoles(user.uuid);
|
||||||
|
return {
|
||||||
|
...user,
|
||||||
|
role: roles.includes("admin")
|
||||||
|
? "admin"
|
||||||
|
: roles.includes("moderator")
|
||||||
|
? "moderator"
|
||||||
|
: "user",
|
||||||
|
roles,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async findOneWithPrivateData(uuid: string) {
|
async findOneWithPrivateData(uuid: string) {
|
||||||
@@ -94,8 +109,30 @@ export class UsersService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async search(query: string) {
|
||||||
|
const users = await this.usersRepository.search(query);
|
||||||
|
return users.map((user) => ({
|
||||||
|
...user,
|
||||||
|
avatarUrl: user.avatarUrl
|
||||||
|
? this.s3Service.getPublicUrl(user.avatarUrl)
|
||||||
|
: null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
async findOne(uuid: string) {
|
async findOne(uuid: string) {
|
||||||
return await this.usersRepository.findOne(uuid);
|
const user = await this.usersRepository.findOne(uuid);
|
||||||
|
if (!user) return null;
|
||||||
|
|
||||||
|
const roles = await this.rbacService.getUserRoles(user.uuid);
|
||||||
|
return {
|
||||||
|
...user,
|
||||||
|
role: roles.includes("admin")
|
||||||
|
? "admin"
|
||||||
|
: roles.includes("moderator")
|
||||||
|
? "moderator"
|
||||||
|
: "user",
|
||||||
|
roles,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async update(uuid: string, data: UpdateUserDto) {
|
async update(uuid: string, data: UpdateUserDto) {
|
||||||
@@ -103,6 +140,9 @@ export class UsersService {
|
|||||||
|
|
||||||
const { role, ...userData } = data;
|
const { role, ...userData } = data;
|
||||||
|
|
||||||
|
// On récupère l'utilisateur actuel avant mise à jour pour comparer les préférences
|
||||||
|
const oldUser = await this.usersRepository.findOne(uuid);
|
||||||
|
|
||||||
const result = await this.usersRepository.update(uuid, userData);
|
const result = await this.usersRepository.update(uuid, userData);
|
||||||
|
|
||||||
if (role) {
|
if (role) {
|
||||||
@@ -111,6 +151,21 @@ export class UsersService {
|
|||||||
|
|
||||||
if (result[0]) {
|
if (result[0]) {
|
||||||
await this.clearUserCache(result[0].username);
|
await this.clearUserCache(result[0].username);
|
||||||
|
|
||||||
|
// Gérer le changement de préférence de statut en ligne
|
||||||
|
if (
|
||||||
|
data.showOnlineStatus !== undefined &&
|
||||||
|
data.showOnlineStatus !== oldUser?.showOnlineStatus
|
||||||
|
) {
|
||||||
|
const isOnline = this.eventsGateway.isUserOnline(uuid);
|
||||||
|
if (isOnline) {
|
||||||
|
if (data.showOnlineStatus) {
|
||||||
|
this.eventsGateway.broadcastStatus(uuid, "online");
|
||||||
|
} else {
|
||||||
|
this.eventsGateway.broadcastStatus(uuid, "offline");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -131,6 +131,8 @@ services:
|
|||||||
environment:
|
environment:
|
||||||
NODE_ENV: production
|
NODE_ENV: production
|
||||||
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-https://api.memegoat.fr}
|
NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL:-https://api.memegoat.fr}
|
||||||
|
NEXT_PUBLIC_APP_URL: ${NEXT_PUBLIC_APP_URL:-https://memegoat.fr}
|
||||||
|
NEXT_PUBLIC_CONTACT_EMAIL: ${MAIL_FROM:-noreply@memegoat.fr}
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
- backend
|
||||||
|
|
||||||
|
|||||||
@@ -14,13 +14,13 @@ COPY documentation/package.json ./documentation/
|
|||||||
|
|
||||||
# Montage du cache pnpm
|
# Montage du cache pnpm
|
||||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||||
pnpm install --frozen-lockfile
|
pnpm install --frozen-lockfile --force
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Deuxième passe avec cache pour les scripts/liens
|
# Deuxième passe avec cache pour les scripts/liens
|
||||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||||
pnpm install --frozen-lockfile
|
pnpm install --frozen-lockfile --force
|
||||||
|
|
||||||
# Build avec cache Next.js
|
# Build avec cache Next.js
|
||||||
RUN --mount=type=cache,id=next-docs-cache,target=/usr/src/app/documentation/.next/cache \
|
RUN --mount=type=cache,id=next-docs-cache,target=/usr/src/app/documentation/.next/cache \
|
||||||
|
|||||||
@@ -14,13 +14,13 @@ COPY documentation/package.json ./documentation/
|
|||||||
|
|
||||||
# Montage du cache pnpm
|
# Montage du cache pnpm
|
||||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||||
pnpm install --frozen-lockfile
|
pnpm install --frozen-lockfile --force
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Deuxième passe avec cache pour les scripts/liens
|
# Deuxième passe avec cache pour les scripts/liens
|
||||||
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
|
||||||
pnpm install --frozen-lockfile
|
pnpm install --frozen-lockfile --force
|
||||||
|
|
||||||
# Build avec cache Next.js
|
# Build avec cache Next.js
|
||||||
RUN --mount=type=cache,id=next-cache,target=/usr/src/app/frontend/.next/cache \
|
RUN --mount=type=cache,id=next-cache,target=/usr/src/app/frontend/.next/cache \
|
||||||
|
|||||||
@@ -1,5 +1,16 @@
|
|||||||
import type { NextConfig } from "next";
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
|
const appUrl = process.env.NEXT_PUBLIC_APP_URL || "https://memegoat.fr";
|
||||||
|
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "https://api.memegoat.fr";
|
||||||
|
|
||||||
|
const getHostname = (url: string) => {
|
||||||
|
try {
|
||||||
|
return new URL(url).hostname;
|
||||||
|
} catch {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
/* config options here */
|
/* config options here */
|
||||||
reactCompiler: true,
|
reactCompiler: true,
|
||||||
@@ -7,11 +18,11 @@ const nextConfig: NextConfig = {
|
|||||||
remotePatterns: [
|
remotePatterns: [
|
||||||
{
|
{
|
||||||
protocol: "https",
|
protocol: "https",
|
||||||
hostname: "memegoat.fr",
|
hostname: getHostname(appUrl),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
protocol: "https",
|
protocol: "https",
|
||||||
hostname: "api.memegoat.fr",
|
hostname: getHostname(apiUrl),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@memegoat/frontend",
|
"name": "@memegoat/frontend",
|
||||||
"version": "1.7.0",
|
"version": "1.9.5",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
@@ -54,6 +54,7 @@
|
|||||||
"react-hook-form": "^7.71.1",
|
"react-hook-form": "^7.71.1",
|
||||||
"react-resizable-panels": "^4.4.1",
|
"react-resizable-panels": "^4.4.1",
|
||||||
"recharts": "2.15.4",
|
"recharts": "2.15.4",
|
||||||
|
"socket.io-client": "^4.8.3",
|
||||||
"sonner": "^2.0.7",
|
"sonner": "^2.0.7",
|
||||||
"tailwind-merge": "^3.4.0",
|
"tailwind-merge": "^3.4.0",
|
||||||
"vaul": "^1.1.2",
|
"vaul": "^1.1.2",
|
||||||
|
|||||||
@@ -24,20 +24,29 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from "@/components/ui/form";
|
} from "@/components/ui/form";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
|
import {
|
||||||
|
InputOTP,
|
||||||
|
InputOTPGroup,
|
||||||
|
InputOTPSeparator,
|
||||||
|
InputOTPSlot,
|
||||||
|
} from "@/components/ui/input-otp";
|
||||||
import { useAuth } from "@/providers/auth-provider";
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
|
|
||||||
const loginSchema = z.object({
|
const loginSchema = z.object({
|
||||||
email: z.string().email({ message: "Email invalide" }),
|
email: z.string().email({ message: "Email invalide" }),
|
||||||
password: z
|
password: z
|
||||||
.string()
|
.string()
|
||||||
.min(6, { message: "Le mot de passe doit faire au moins 6 caractères" }),
|
.min(8, { message: "Le mot de passe doit faire au moins 8 caractères" }),
|
||||||
});
|
});
|
||||||
|
|
||||||
type LoginFormValues = z.infer<typeof loginSchema>;
|
type LoginFormValues = z.infer<typeof loginSchema>;
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const { login } = useAuth();
|
const { login, verify2fa } = useAuth();
|
||||||
const [loading, setLoading] = React.useState(false);
|
const [loading, setLoading] = React.useState(false);
|
||||||
|
const [show2fa, setShow2fa] = React.useState(false);
|
||||||
|
const [userId, setUserId] = React.useState<string | null>(null);
|
||||||
|
const [otpValue, setOtpValue] = React.useState("");
|
||||||
|
|
||||||
const form = useForm<LoginFormValues>({
|
const form = useForm<LoginFormValues>({
|
||||||
resolver: zodResolver(loginSchema),
|
resolver: zodResolver(loginSchema),
|
||||||
@@ -50,7 +59,11 @@ export default function LoginPage() {
|
|||||||
async function onSubmit(values: LoginFormValues) {
|
async function onSubmit(values: LoginFormValues) {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
await login(values.email, values.password);
|
const res = await login(values.email, values.password);
|
||||||
|
if (res.userId && res.message === "Please provide 2FA token") {
|
||||||
|
setUserId(res.userId);
|
||||||
|
setShow2fa(true);
|
||||||
|
}
|
||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
// Error is handled in useAuth via toast
|
// Error is handled in useAuth via toast
|
||||||
} finally {
|
} finally {
|
||||||
@@ -58,6 +71,20 @@ export default function LoginPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function onOtpSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!userId || otpValue.length !== 6) return;
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
await verify2fa(userId, otpValue);
|
||||||
|
} catch (_error) {
|
||||||
|
// Error handled in useAuth
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center bg-zinc-50 dark:bg-zinc-950 p-4">
|
<div className="min-h-screen flex items-center justify-center bg-zinc-50 dark:bg-zinc-950 p-4">
|
||||||
<div className="w-full max-w-md space-y-4">
|
<div className="w-full max-w-md space-y-4">
|
||||||
@@ -70,45 +97,89 @@ export default function LoginPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-2xl">Connexion</CardTitle>
|
<CardTitle className="text-2xl">
|
||||||
|
{show2fa ? "Double Authentification" : "Connexion"}
|
||||||
|
</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Entrez vos identifiants pour accéder à votre compte MemeGoat.
|
{show2fa
|
||||||
|
? "Entrez le code à 6 chiffres de votre application d'authentification."
|
||||||
|
: "Entrez vos identifiants pour accéder à votre compte MemeGoat."}
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<Form {...form}>
|
{show2fa ? (
|
||||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
<form
|
||||||
<FormField
|
onSubmit={onOtpSubmit}
|
||||||
control={form.control}
|
className="space-y-6 flex flex-col items-center"
|
||||||
name="email"
|
>
|
||||||
render={({ field }) => (
|
<InputOTP
|
||||||
<FormItem>
|
maxLength={6}
|
||||||
<FormLabel>Email</FormLabel>
|
value={otpValue}
|
||||||
<FormControl>
|
onChange={(value) => setOtpValue(value)}
|
||||||
<Input placeholder="goat@example.com" {...field} />
|
>
|
||||||
</FormControl>
|
<InputOTPGroup>
|
||||||
<FormMessage />
|
<InputOTPSlot index={0} />
|
||||||
</FormItem>
|
<InputOTPSlot index={1} />
|
||||||
)}
|
<InputOTPSlot index={2} />
|
||||||
/>
|
</InputOTPGroup>
|
||||||
<FormField
|
<InputOTPSeparator />
|
||||||
control={form.control}
|
<InputOTPGroup>
|
||||||
name="password"
|
<InputOTPSlot index={3} />
|
||||||
render={({ field }) => (
|
<InputOTPSlot index={4} />
|
||||||
<FormItem>
|
<InputOTPSlot index={5} />
|
||||||
<FormLabel>Mot de passe</FormLabel>
|
</InputOTPGroup>
|
||||||
<FormControl>
|
</InputOTP>
|
||||||
<Input type="password" placeholder="••••••••" {...field} />
|
<Button
|
||||||
</FormControl>
|
type="submit"
|
||||||
<FormMessage />
|
className="w-full"
|
||||||
</FormItem>
|
disabled={loading || otpValue.length !== 6}
|
||||||
)}
|
>
|
||||||
/>
|
{loading ? "Vérification..." : "Vérifier le code"}
|
||||||
<Button type="submit" className="w-full" disabled={loading}>
|
</Button>
|
||||||
{loading ? "Connexion en cours..." : "Se connecter"}
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="w-full"
|
||||||
|
onClick={() => setShow2fa(false)}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
Retour
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</Form>
|
) : (
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="email"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Email</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="goat@example.com" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="password"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Mot de passe</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input type="password" placeholder="••••••••" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? "Connexion en cours..." : "Se connecter"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
)}
|
||||||
</CardContent>
|
</CardContent>
|
||||||
<CardFooter className="flex flex-col space-y-2">
|
<CardFooter className="flex flex-col space-y-2">
|
||||||
<p className="text-sm text-center text-muted-foreground">
|
<p className="text-sm text-center text-muted-foreground">
|
||||||
|
|||||||
@@ -29,11 +29,27 @@ import { useAuth } from "@/providers/auth-provider";
|
|||||||
const registerSchema = z.object({
|
const registerSchema = z.object({
|
||||||
username: z
|
username: z
|
||||||
.string()
|
.string()
|
||||||
.min(3, { message: "Le pseudo doit faire au moins 3 caractères" }),
|
.min(3, { message: "Le pseudo doit faire au moins 3 caractères" })
|
||||||
|
.regex(/^[a-z0-9_]+$/, {
|
||||||
|
message:
|
||||||
|
"Le pseudo ne doit contenir que des minuscules, chiffres et underscores",
|
||||||
|
}),
|
||||||
email: z.string().email({ message: "Email invalide" }),
|
email: z.string().email({ message: "Email invalide" }),
|
||||||
password: z
|
password: z
|
||||||
.string()
|
.string()
|
||||||
.min(6, { message: "Le mot de passe doit faire au moins 6 caractères" }),
|
.min(8, { message: "Le mot de passe doit faire au moins 8 caractères" })
|
||||||
|
.regex(/[A-Z]/, {
|
||||||
|
message: "Le mot de passe doit contenir au moins une majuscule",
|
||||||
|
})
|
||||||
|
.regex(/[a-z]/, {
|
||||||
|
message: "Le mot de passe doit contenir au moins une minuscule",
|
||||||
|
})
|
||||||
|
.regex(/[0-9]/, {
|
||||||
|
message: "Le mot de passe doit contenir au moins un chiffre",
|
||||||
|
})
|
||||||
|
.regex(/[^A-Za-z0-9]/, {
|
||||||
|
message: "Le mot de passe doit contenir au moins un caractère spécial",
|
||||||
|
}),
|
||||||
displayName: z.string().optional(),
|
displayName: z.string().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -84,12 +100,25 @@ export default function RegisterPage() {
|
|||||||
<CardContent>
|
<CardContent>
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="displayName"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem>
|
||||||
|
<FormLabel>Nom d'affichage (Optionnel)</FormLabel>
|
||||||
|
<FormControl>
|
||||||
|
<Input placeholder="Le Roi des Chèvres" {...field} />
|
||||||
|
</FormControl>
|
||||||
|
<FormMessage />
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="username"
|
name="username"
|
||||||
render={({ field }) => (
|
render={({ field }) => (
|
||||||
<FormItem>
|
<FormItem>
|
||||||
<FormLabel>Pseudo</FormLabel>
|
<FormLabel>Pseudo (minuscule)</FormLabel>
|
||||||
<FormControl>
|
<FormControl>
|
||||||
<Input placeholder="supergoat" {...field} />
|
<Input placeholder="supergoat" {...field} />
|
||||||
</FormControl>
|
</FormControl>
|
||||||
@@ -110,19 +139,6 @@ export default function RegisterPage() {
|
|||||||
</FormItem>
|
</FormItem>
|
||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
<FormField
|
|
||||||
control={form.control}
|
|
||||||
name="displayName"
|
|
||||||
render={({ field }) => (
|
|
||||||
<FormItem>
|
|
||||||
<FormLabel>Nom d'affichage (Optionnel)</FormLabel>
|
|
||||||
<FormControl>
|
|
||||||
<Input placeholder="Le Roi des Chèvres" {...field} />
|
|
||||||
</FormControl>
|
|
||||||
<FormMessage />
|
|
||||||
</FormItem>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
<FormField
|
<FormField
|
||||||
control={form.control}
|
control={form.control}
|
||||||
name="password"
|
name="password"
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
import { ViewCounter } from "@/components/view-counter";
|
|
||||||
import { ContentService } from "@/services/content.service";
|
import { ContentService } from "@/services/content.service";
|
||||||
import type { Content } from "@/types/content";
|
import type { Content } from "@/types/content";
|
||||||
|
|
||||||
@@ -46,7 +45,6 @@ export default function MemeModal({
|
|||||||
</div>
|
</div>
|
||||||
) : content ? (
|
) : content ? (
|
||||||
<div className="bg-white dark:bg-zinc-900 rounded-lg overflow-hidden">
|
<div className="bg-white dark:bg-zinc-900 rounded-lg overflow-hidden">
|
||||||
<ViewCounter contentId={content.id} />
|
|
||||||
<ContentCard content={content} />
|
<ContentCard content={content} />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { AlertCircle, FileText, LayoutGrid, Users } from "lucide-react";
|
import { AlertCircle, FileText, Flag, LayoutGrid, Users } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
@@ -54,6 +54,13 @@ export default function AdminDashboardPage() {
|
|||||||
href: "/admin/categories",
|
href: "/admin/categories",
|
||||||
color: "text-purple-500",
|
color: "text-purple-500",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: "Signalements",
|
||||||
|
value: "Voir",
|
||||||
|
icon: Flag,
|
||||||
|
href: "/admin/reports",
|
||||||
|
color: "text-red-500",
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
204
frontend/src/app/(dashboard)/admin/reports/page.tsx
Normal file
204
frontend/src/app/(dashboard)/admin/reports/page.tsx
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
AlertCircle,
|
||||||
|
ArrowLeft,
|
||||||
|
CheckCircle,
|
||||||
|
MoreHorizontal,
|
||||||
|
XCircle,
|
||||||
|
} from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import {
|
||||||
|
Table,
|
||||||
|
TableBody,
|
||||||
|
TableCell,
|
||||||
|
TableHead,
|
||||||
|
TableHeader,
|
||||||
|
TableRow,
|
||||||
|
} from "@/components/ui/table";
|
||||||
|
import { adminService } from "@/services/admin.service";
|
||||||
|
import { type Report, ReportStatus } from "@/services/report.service";
|
||||||
|
|
||||||
|
export default function AdminReportsPage() {
|
||||||
|
const [reports, setReports] = useState<Report[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
const fetchReports = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const data = await adminService.getReports();
|
||||||
|
setReports(data);
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors du chargement des signalements.");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchReports();
|
||||||
|
}, [fetchReports]);
|
||||||
|
|
||||||
|
const handleUpdateStatus = async (reportId: string, status: ReportStatus) => {
|
||||||
|
try {
|
||||||
|
await adminService.updateReportStatus(reportId, status);
|
||||||
|
toast.success("Statut mis à jour.");
|
||||||
|
fetchReports();
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors de la mise à jour du statut.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStatusBadge = (status: ReportStatus) => {
|
||||||
|
switch (status) {
|
||||||
|
case ReportStatus.PENDING:
|
||||||
|
return <Badge variant="outline">En attente</Badge>;
|
||||||
|
case ReportStatus.REVIEWED:
|
||||||
|
return <Badge variant="secondary">Examiné</Badge>;
|
||||||
|
case ReportStatus.RESOLVED:
|
||||||
|
return <Badge variant="success">Résolu</Badge>;
|
||||||
|
case ReportStatus.DISMISSED:
|
||||||
|
return <Badge variant="destructive">Rejeté</Badge>;
|
||||||
|
default:
|
||||||
|
return <Badge variant="default">{status}</Badge>;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex-1 space-y-8 p-4 pt-6 md:p-8">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<Button variant="ghost" size="icon" asChild>
|
||||||
|
<Link href="/admin">
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
<h2 className="text-3xl font-bold tracking-tight">Signalements</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Liste des signalements</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Gérez les signalements de contenu inapproprié.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>Signalé par</TableHead>
|
||||||
|
<TableHead>Cible</TableHead>
|
||||||
|
<TableHead>Raison</TableHead>
|
||||||
|
<TableHead>Description</TableHead>
|
||||||
|
<TableHead>Statut</TableHead>
|
||||||
|
<TableHead>Date</TableHead>
|
||||||
|
<TableHead className="text-right">Actions</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{loading ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={7} className="text-center py-8">
|
||||||
|
Chargement...
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : reports.length === 0 ? (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={7} className="text-center py-8">
|
||||||
|
Aucun signalement trouvé.
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
) : (
|
||||||
|
reports.map((report) => (
|
||||||
|
<TableRow key={report.uuid}>
|
||||||
|
<TableCell>{report.reporterId.substring(0, 8)}...</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{report.contentId ? (
|
||||||
|
<Link
|
||||||
|
href={`/meme/${report.contentId}`}
|
||||||
|
className="text-primary hover:underline"
|
||||||
|
>
|
||||||
|
Contenu
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
"Tag"
|
||||||
|
)}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="font-medium capitalize">
|
||||||
|
{report.reason}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="max-w-xs truncate">
|
||||||
|
{report.description || "-"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{getStatusBadge(report.status)}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{new Date(report.createdAt).toLocaleDateString()}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell className="text-right">
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon">
|
||||||
|
<MoreHorizontal className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
handleUpdateStatus(report.uuid, ReportStatus.REVIEWED)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<AlertCircle className="h-4 w-4 mr-2" />
|
||||||
|
Marquer comme examiné
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
handleUpdateStatus(report.uuid, ReportStatus.RESOLVED)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<CheckCircle className="h-4 w-4 mr-2" />
|
||||||
|
Marquer comme résolu
|
||||||
|
</DropdownMenuItem>
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() =>
|
||||||
|
handleUpdateStatus(report.uuid, ReportStatus.DISMISSED)
|
||||||
|
}
|
||||||
|
className="text-destructive"
|
||||||
|
>
|
||||||
|
<XCircle className="h-4 w-4 mr-2" />
|
||||||
|
Rejeter
|
||||||
|
</DropdownMenuItem>
|
||||||
|
{report.contentId && (
|
||||||
|
<DropdownMenuItem asChild>
|
||||||
|
<Link href={`/meme/${report.contentId}`}>Voir le contenu</Link>
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -63,7 +63,9 @@ export default function HelpPage() {
|
|||||||
<p className="text-muted-foreground">
|
<p className="text-muted-foreground">
|
||||||
N'hésitez pas à nous contacter sur nos réseaux sociaux ou par email.
|
N'hésitez pas à nous contacter sur nos réseaux sociaux ou par email.
|
||||||
</p>
|
</p>
|
||||||
<p className="font-semibold text-primary">contact@memegoat.fr</p>
|
<p className="font-semibold text-primary">
|
||||||
|
{process.env.NEXT_PUBLIC_CONTACT_EMAIL || "contact@memegoat.fr"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ import { ChevronLeft } from "lucide-react";
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
|
import { CommentSection } from "@/components/comment-section";
|
||||||
import { ContentCard } from "@/components/content-card";
|
import { ContentCard } from "@/components/content-card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { ViewCounter } from "@/components/view-counter";
|
|
||||||
import { ContentService } from "@/services/content.service";
|
import { ContentService } from "@/services/content.service";
|
||||||
|
|
||||||
export const revalidate = 3600; // ISR: Revalider toutes les heures
|
export const revalidate = 3600; // ISR: Revalider toutes les heures
|
||||||
@@ -41,7 +41,6 @@ export default async function MemePage({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-4xl mx-auto py-8 px-4">
|
<div className="max-w-4xl mx-auto py-8 px-4">
|
||||||
<ViewCounter contentId={content.id} />
|
|
||||||
<Link
|
<Link
|
||||||
href="/"
|
href="/"
|
||||||
className="inline-flex items-center text-sm mb-6 hover:text-primary transition-colors"
|
className="inline-flex items-center text-sm mb-6 hover:text-primary transition-colors"
|
||||||
@@ -53,6 +52,7 @@ export default async function MemePage({
|
|||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
|
||||||
<div className="lg:col-span-2">
|
<div className="lg:col-span-2">
|
||||||
<ContentCard content={content} />
|
<ContentCard content={content} />
|
||||||
|
<CommentSection contentId={content.id} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
|
|||||||
562
frontend/src/app/(dashboard)/messages/page.tsx
Normal file
562
frontend/src/app/(dashboard)/messages/page.tsx
Normal file
@@ -0,0 +1,562 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { formatDistanceToNow } from "date-fns";
|
||||||
|
import { fr } from "date-fns/locale";
|
||||||
|
import {
|
||||||
|
ArrowLeft,
|
||||||
|
Check,
|
||||||
|
CheckCheck,
|
||||||
|
Search,
|
||||||
|
Send,
|
||||||
|
UserPlus,
|
||||||
|
X,
|
||||||
|
} from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
|
import * as React from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
|
import { useSocket } from "@/providers/socket-provider";
|
||||||
|
import {
|
||||||
|
type Conversation,
|
||||||
|
type Message,
|
||||||
|
MessageService,
|
||||||
|
} from "@/services/message.service";
|
||||||
|
import { UserService } from "@/services/user.service";
|
||||||
|
import type { User } from "@/types/user";
|
||||||
|
|
||||||
|
export default function MessagesPage() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { socket } = useSocket();
|
||||||
|
const _router = useRouter();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const targetUserId = searchParams.get("user");
|
||||||
|
|
||||||
|
const [conversations, setConversations] = React.useState<Conversation[]>([]);
|
||||||
|
const [activeConv, setActiveConv] = React.useState<Conversation | null>(null);
|
||||||
|
const [messages, setMessages] = React.useState<Message[]>([]);
|
||||||
|
const [newMessage, setNewMessage] = React.useState("");
|
||||||
|
const typingTimeoutRef = React.useRef<NodeJS.Timeout | null>(null);
|
||||||
|
|
||||||
|
const handleTyping = () => {
|
||||||
|
if (!socket || !activeConv) return;
|
||||||
|
|
||||||
|
socket.emit("typing", {
|
||||||
|
recipientId: activeConv.recipient.uuid,
|
||||||
|
isTyping: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (typingTimeoutRef.current) clearTimeout(typingTimeoutRef.current);
|
||||||
|
|
||||||
|
typingTimeoutRef.current = setTimeout(() => {
|
||||||
|
socket.emit("typing", {
|
||||||
|
recipientId: activeConv.recipient.uuid,
|
||||||
|
isTyping: false,
|
||||||
|
});
|
||||||
|
}, 3000);
|
||||||
|
};
|
||||||
|
const [isLoadingConvs, setIsLoadingConvs] = React.useState(true);
|
||||||
|
const [isLoadingMsgs, setIsLoadingMsgs] = React.useState(false);
|
||||||
|
const [isOtherTyping, setIsOtherTyping] = React.useState(false);
|
||||||
|
const [onlineUsers, setOnlineUsers] = React.useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
const [searchQuery, setSearchQuery] = React.useState("");
|
||||||
|
const [searchResults, setSearchResults] = React.useState<User[]>([]);
|
||||||
|
const [isSearching, setIsSearching] = React.useState(false);
|
||||||
|
|
||||||
|
const scrollRef = React.useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Charger les conversations initiales
|
||||||
|
React.useEffect(() => {
|
||||||
|
const fetchConvs = async () => {
|
||||||
|
try {
|
||||||
|
const data = await MessageService.getConversations();
|
||||||
|
setConversations(data);
|
||||||
|
|
||||||
|
// Si un utilisateur est spécifié dans l'URL, essayer de trouver la conversation
|
||||||
|
if (targetUserId) {
|
||||||
|
const existing = data.find((c) => c.recipient.uuid === targetUserId);
|
||||||
|
if (existing) {
|
||||||
|
setActiveConv(existing);
|
||||||
|
} else {
|
||||||
|
// Chercher les infos de l'utilisateur pour afficher une interface de chat vide
|
||||||
|
try {
|
||||||
|
const conv = await MessageService.getConversationWith(targetUserId);
|
||||||
|
if (conv) {
|
||||||
|
setConversations((prev) => [conv, ...prev]);
|
||||||
|
setActiveConv(conv);
|
||||||
|
}
|
||||||
|
} catch (_e) {
|
||||||
|
// Peut-être que l'utilisateur n'existe pas ou erreur
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors du chargement des conversations");
|
||||||
|
} finally {
|
||||||
|
setIsLoadingConvs(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchConvs();
|
||||||
|
}, [targetUserId]);
|
||||||
|
|
||||||
|
// Recherche d'utilisateurs
|
||||||
|
React.useEffect(() => {
|
||||||
|
const delayDebounceFn = setTimeout(async () => {
|
||||||
|
if (searchQuery.length > 1) {
|
||||||
|
setIsSearching(true);
|
||||||
|
try {
|
||||||
|
const results = await UserService.search(searchQuery);
|
||||||
|
setSearchResults(results.filter((u) => u.uuid !== user?.uuid));
|
||||||
|
} catch (_error) {
|
||||||
|
console.error("Search failed");
|
||||||
|
} finally {
|
||||||
|
setIsSearching(false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setSearchResults([]);
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
return () => clearTimeout(delayDebounceFn);
|
||||||
|
}, [searchQuery, user?.uuid]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (activeConv) {
|
||||||
|
const fetchMsgs = async () => {
|
||||||
|
setIsLoadingMsgs(true);
|
||||||
|
try {
|
||||||
|
const data = await MessageService.getMessages(activeConv.id);
|
||||||
|
setMessages(data.reverse()); // Plus ancien au plus récent
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors du chargement des messages");
|
||||||
|
} finally {
|
||||||
|
setIsLoadingMsgs(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchMsgs();
|
||||||
|
}
|
||||||
|
}, [activeConv]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (socket) {
|
||||||
|
socket.on(
|
||||||
|
"new_message",
|
||||||
|
(data: { conversationId: string; message: Message }) => {
|
||||||
|
if (activeConv?.id === data.conversationId) {
|
||||||
|
setMessages((prev) => [...prev, data.message]);
|
||||||
|
setIsOtherTyping(false); // S'il a envoyé un message, il ne tape plus
|
||||||
|
// Marquer comme lu immédiatement si on est sur la conversation
|
||||||
|
MessageService.markAsRead(data.conversationId).catch(console.error);
|
||||||
|
}
|
||||||
|
// Mettre à jour la liste des conversations
|
||||||
|
setConversations((prev) => {
|
||||||
|
const index = prev.findIndex((c) => c.id === data.conversationId);
|
||||||
|
if (index !== -1) {
|
||||||
|
const updated = [...prev];
|
||||||
|
updated[index] = {
|
||||||
|
...updated[index],
|
||||||
|
lastMessage: {
|
||||||
|
text: data.message.text,
|
||||||
|
createdAt: data.message.createdAt,
|
||||||
|
},
|
||||||
|
updatedAt: data.message.createdAt,
|
||||||
|
};
|
||||||
|
return updated.sort(
|
||||||
|
(a, b) =>
|
||||||
|
new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on("user_status", (data: { userId: string; status: string }) => {
|
||||||
|
setOnlineUsers((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (data.status === "online") {
|
||||||
|
next.add(data.userId);
|
||||||
|
} else {
|
||||||
|
next.delete(data.userId);
|
||||||
|
}
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("user_typing", (data: { userId: string; isTyping: boolean }) => {
|
||||||
|
if (activeConv?.recipient.uuid === data.userId) {
|
||||||
|
setIsOtherTyping(data.isTyping);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on(
|
||||||
|
"messages_read",
|
||||||
|
(data: { conversationId: string; readerId: string }) => {
|
||||||
|
if (activeConv?.id === data.conversationId) {
|
||||||
|
setMessages((prev) =>
|
||||||
|
prev.map((msg) =>
|
||||||
|
msg.senderId !== data.readerId && !msg.readAt
|
||||||
|
? { ...msg, readAt: new Date().toISOString() }
|
||||||
|
: msg,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socket.off("new_message");
|
||||||
|
socket.off("user_status");
|
||||||
|
socket.off("user_typing");
|
||||||
|
socket.off("messages_read");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, [socket, activeConv]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (scrollRef.current) {
|
||||||
|
const scrollContainer = scrollRef.current.querySelector(
|
||||||
|
"[data-slot='scroll-area-viewport']",
|
||||||
|
);
|
||||||
|
if (scrollContainer) {
|
||||||
|
scrollContainer.scrollTop = scrollContainer.scrollHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSendMessage = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newMessage.trim() || !activeConv) return;
|
||||||
|
|
||||||
|
const text = newMessage.trim();
|
||||||
|
setNewMessage("");
|
||||||
|
|
||||||
|
try {
|
||||||
|
const msg = await MessageService.sendMessage(
|
||||||
|
activeConv.recipient.uuid,
|
||||||
|
text,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Si c'était une conv temporaire, on la remplace par la vraie
|
||||||
|
if (activeConv.id.startsWith("temp-")) {
|
||||||
|
const fetchConvs = async () => {
|
||||||
|
const data = await MessageService.getConversations();
|
||||||
|
setConversations(data);
|
||||||
|
const realConv = data.find(
|
||||||
|
(c) => c.recipient.uuid === activeConv.recipient.uuid,
|
||||||
|
);
|
||||||
|
if (realConv) setActiveConv(realConv);
|
||||||
|
};
|
||||||
|
fetchConvs();
|
||||||
|
} else {
|
||||||
|
setMessages((prev) => [...prev, msg]);
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors de l'envoi");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-[calc(100vh-4rem)] flex overflow-hidden bg-white dark:bg-zinc-950">
|
||||||
|
{/* Sidebar - Liste des conversations */}
|
||||||
|
<div
|
||||||
|
className={`w-full md:w-80 border-r flex flex-col ${
|
||||||
|
activeConv ? "hidden md:flex" : "flex"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="p-4 border-b">
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<h2 className="text-xl font-bold">Messages</h2>
|
||||||
|
<Button variant="ghost" size="icon" className="rounded-full">
|
||||||
|
<UserPlus className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="Rechercher un membre..."
|
||||||
|
className="pl-9"
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
{searchQuery && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSearchQuery("")}
|
||||||
|
className="absolute right-3 top-1/2 -translate-y-1/2 p-0.5 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-full"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3 text-muted-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ScrollArea className="flex-1">
|
||||||
|
<div className="p-2 space-y-1">
|
||||||
|
{searchQuery.length > 0 ? (
|
||||||
|
<>
|
||||||
|
<p className="px-3 py-2 text-[10px] font-bold uppercase tracking-wider text-muted-foreground">
|
||||||
|
Membres
|
||||||
|
</p>
|
||||||
|
{isSearching ? (
|
||||||
|
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
Recherche...
|
||||||
|
</div>
|
||||||
|
) : searchResults.length === 0 ? (
|
||||||
|
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
Aucun membre trouvé.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
searchResults.map((result) => (
|
||||||
|
<button
|
||||||
|
key={result.uuid}
|
||||||
|
type="button"
|
||||||
|
onClick={async () => {
|
||||||
|
setSearchQuery("");
|
||||||
|
// Chercher si une conv existe déjà
|
||||||
|
const existing = conversations.find(
|
||||||
|
(c) => c.recipient.uuid === result.uuid,
|
||||||
|
);
|
||||||
|
if (existing) {
|
||||||
|
setActiveConv(existing);
|
||||||
|
} else {
|
||||||
|
// Créer une interface de conv temporaire
|
||||||
|
const newConv: Conversation = {
|
||||||
|
id: `temp-${result.uuid}`,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
recipient: {
|
||||||
|
uuid: result.uuid,
|
||||||
|
username: result.username,
|
||||||
|
displayName: result.displayName,
|
||||||
|
avatarUrl: result.avatarUrl,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
setConversations((prev) => [newConv, ...prev]);
|
||||||
|
setActiveConv(newConv);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-zinc-100 dark:hover:bg-zinc-900 transition-colors"
|
||||||
|
>
|
||||||
|
<Avatar className="h-10 w-10">
|
||||||
|
<AvatarImage src={result.avatarUrl} />
|
||||||
|
<AvatarFallback>{result.username[0].toUpperCase()}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1 text-left overflow-hidden">
|
||||||
|
<span className="font-bold block truncate">
|
||||||
|
{result.displayName || result.username}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-muted-foreground block truncate">
|
||||||
|
@{result.username}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : isLoadingConvs ? (
|
||||||
|
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
Chargement...
|
||||||
|
</div>
|
||||||
|
) : conversations.length === 0 ? (
|
||||||
|
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
Aucune conversation.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
conversations.map((conv) => (
|
||||||
|
<button
|
||||||
|
key={conv.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setActiveConv(conv)}
|
||||||
|
className={`w-full flex items-center gap-3 p-3 rounded-xl transition-colors ${
|
||||||
|
activeConv?.id === conv.id
|
||||||
|
? "bg-primary/10 text-primary"
|
||||||
|
: "hover:bg-zinc-100 dark:hover:bg-zinc-900"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Avatar isOnline={onlineUsers.has(conv.recipient.uuid)}>
|
||||||
|
<AvatarImage src={conv.recipient.avatarUrl} />
|
||||||
|
<AvatarFallback>
|
||||||
|
{conv.recipient.username[0].toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1 text-left overflow-hidden">
|
||||||
|
<div className="flex justify-between items-baseline">
|
||||||
|
<span className="font-bold truncate">
|
||||||
|
{conv.recipient.displayName || conv.recipient.username}
|
||||||
|
</span>
|
||||||
|
{conv.lastMessage && (
|
||||||
|
<span className="text-[10px] text-muted-foreground whitespace-nowrap">
|
||||||
|
{formatDistanceToNow(new Date(conv.lastMessage.createdAt), {
|
||||||
|
locale: fr,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">
|
||||||
|
{conv.lastMessage?.text || "Démarrer une conversation"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Zone de chat */}
|
||||||
|
<div
|
||||||
|
className={`flex-1 flex flex-col ${
|
||||||
|
!activeConv ? "hidden md:flex" : "flex"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{activeConv ? (
|
||||||
|
<>
|
||||||
|
{/* Header */}
|
||||||
|
<div className="p-4 border-b flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="md:hidden rounded-full"
|
||||||
|
onClick={() => setActiveConv(null)}
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-5 w-5" />
|
||||||
|
</Button>
|
||||||
|
<Link
|
||||||
|
href={`/user/${activeConv.recipient.username}`}
|
||||||
|
className="flex-1 flex items-center gap-3 hover:opacity-80 transition-opacity"
|
||||||
|
>
|
||||||
|
<Avatar
|
||||||
|
className="h-8 w-8"
|
||||||
|
isOnline={onlineUsers.has(activeConv.recipient.uuid)}
|
||||||
|
>
|
||||||
|
<AvatarImage src={activeConv.recipient.avatarUrl} />
|
||||||
|
<AvatarFallback>
|
||||||
|
{activeConv.recipient.username[0].toUpperCase()}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-bold leading-none">
|
||||||
|
{activeConv.recipient.displayName || activeConv.recipient.username}
|
||||||
|
</h3>
|
||||||
|
<span
|
||||||
|
className={`text-xs font-medium ${
|
||||||
|
onlineUsers.has(activeConv.recipient.uuid)
|
||||||
|
? "text-green-500"
|
||||||
|
: "text-muted-foreground"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{onlineUsers.has(activeConv.recipient.uuid)
|
||||||
|
? "En ligne"
|
||||||
|
: "Hors ligne"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Messages */}
|
||||||
|
<ScrollArea className="flex-1 p-4" viewportRef={scrollRef}>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{isLoadingMsgs ? (
|
||||||
|
<div className="text-center py-4 text-sm text-muted-foreground">
|
||||||
|
Chargement...
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
messages.map((msg) => (
|
||||||
|
<div
|
||||||
|
key={msg.id}
|
||||||
|
className={`flex ${
|
||||||
|
msg.senderId === user?.uuid ? "justify-end" : "justify-start"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={`max-w-[70%] p-3 rounded-2xl text-sm ${
|
||||||
|
msg.senderId === user?.uuid
|
||||||
|
? "bg-primary text-primary-foreground rounded-br-none"
|
||||||
|
: "bg-zinc-100 dark:bg-zinc-800 rounded-bl-none"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<p className="whitespace-pre-wrap">{msg.text}</p>
|
||||||
|
<div
|
||||||
|
className={`flex items-center gap-1 text-[10px] mt-1 ${
|
||||||
|
msg.senderId === user?.uuid
|
||||||
|
? "text-primary-foreground/70 justify-end"
|
||||||
|
: "text-muted-foreground"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
{new Date(msg.createdAt).toLocaleTimeString([], {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
{msg.senderId === user?.uuid && (
|
||||||
|
<span className="flex items-center">
|
||||||
|
{msg.readAt ? (
|
||||||
|
<CheckCheck className="h-3 w-3" />
|
||||||
|
) : (
|
||||||
|
<Check className="h-3 w-3" />
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
{isOtherTyping && (
|
||||||
|
<div className="flex justify-start">
|
||||||
|
<div className="bg-zinc-100 dark:bg-zinc-800 p-3 rounded-2xl rounded-bl-none">
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce [animation-delay:-0.3s]" />
|
||||||
|
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce [animation-delay:-0.15s]" />
|
||||||
|
<span className="w-1.5 h-1.5 bg-zinc-400 rounded-full animate-bounce" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
|
||||||
|
{/* Input */}
|
||||||
|
<div className="p-4 border-t">
|
||||||
|
<form onSubmit={handleSendMessage} className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
placeholder="Écrivez un message..."
|
||||||
|
value={newMessage}
|
||||||
|
onChange={(e) => {
|
||||||
|
setNewMessage(e.target.value);
|
||||||
|
handleTyping();
|
||||||
|
}}
|
||||||
|
className="rounded-full px-4"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="icon"
|
||||||
|
className="rounded-full shrink-0"
|
||||||
|
disabled={!newMessage.trim()}
|
||||||
|
>
|
||||||
|
<Send className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="flex-1 flex flex-col items-center justify-center text-center p-8">
|
||||||
|
<div className="bg-primary/10 p-6 rounded-full mb-4">
|
||||||
|
<Send className="h-12 w-12 text-primary" />
|
||||||
|
</div>
|
||||||
|
<h2 className="text-2xl font-bold mb-2">Vos messages</h2>
|
||||||
|
<p className="text-muted-foreground max-w-sm">
|
||||||
|
Sélectionnez une conversation ou démarrez-en une nouvelle pour commencer
|
||||||
|
à discuter.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,12 +3,14 @@
|
|||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
import {
|
import {
|
||||||
AlertTriangle,
|
AlertTriangle,
|
||||||
|
Download,
|
||||||
Laptop,
|
Laptop,
|
||||||
Loader2,
|
Loader2,
|
||||||
Moon,
|
Moon,
|
||||||
Palette,
|
Palette,
|
||||||
Save,
|
Save,
|
||||||
Settings,
|
Settings,
|
||||||
|
Shield,
|
||||||
Sun,
|
Sun,
|
||||||
Trash2,
|
Trash2,
|
||||||
User as UserIcon,
|
User as UserIcon,
|
||||||
@@ -19,6 +21,7 @@ import * as React from "react";
|
|||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import * as z from "zod";
|
import * as z from "zod";
|
||||||
|
import { TwoFactorSetup } from "@/components/two-factor-setup";
|
||||||
import {
|
import {
|
||||||
AlertDialog,
|
AlertDialog,
|
||||||
AlertDialogAction,
|
AlertDialogAction,
|
||||||
@@ -51,6 +54,7 @@ import { Input } from "@/components/ui/input";
|
|||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { Switch } from "@/components/ui/switch";
|
||||||
import { Textarea } from "@/components/ui/textarea";
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { useAuth } from "@/providers/auth-provider";
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
import { UserService } from "@/services/user.service";
|
import { UserService } from "@/services/user.service";
|
||||||
@@ -58,6 +62,8 @@ import { UserService } from "@/services/user.service";
|
|||||||
const settingsSchema = z.object({
|
const settingsSchema = z.object({
|
||||||
displayName: z.string().max(32, "Le nom d'affichage est trop long").optional(),
|
displayName: z.string().max(32, "Le nom d'affichage est trop long").optional(),
|
||||||
bio: z.string().max(255, "La bio est trop longue").optional(),
|
bio: z.string().max(255, "La bio est trop longue").optional(),
|
||||||
|
showOnlineStatus: z.boolean(),
|
||||||
|
showReadReceipts: z.boolean(),
|
||||||
});
|
});
|
||||||
|
|
||||||
type SettingsFormValues = z.infer<typeof settingsSchema>;
|
type SettingsFormValues = z.infer<typeof settingsSchema>;
|
||||||
@@ -68,6 +74,7 @@ export default function SettingsPage() {
|
|||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [isSaving, setIsSaving] = React.useState(false);
|
const [isSaving, setIsSaving] = React.useState(false);
|
||||||
const [isDeleting, setIsDeleting] = React.useState(false);
|
const [isDeleting, setIsDeleting] = React.useState(false);
|
||||||
|
const [isExporting, setIsExporting] = React.useState(false);
|
||||||
const [mounted, setMounted] = React.useState(false);
|
const [mounted, setMounted] = React.useState(false);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
@@ -79,6 +86,8 @@ export default function SettingsPage() {
|
|||||||
defaultValues: {
|
defaultValues: {
|
||||||
displayName: "",
|
displayName: "",
|
||||||
bio: "",
|
bio: "",
|
||||||
|
showOnlineStatus: true,
|
||||||
|
showReadReceipts: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -87,6 +96,8 @@ export default function SettingsPage() {
|
|||||||
form.reset({
|
form.reset({
|
||||||
displayName: user.displayName || "",
|
displayName: user.displayName || "",
|
||||||
bio: user.bio || "",
|
bio: user.bio || "",
|
||||||
|
showOnlineStatus: user.showOnlineStatus ?? true,
|
||||||
|
showReadReceipts: user.showReadReceipts ?? true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}, [user, form]);
|
}, [user, form]);
|
||||||
@@ -143,6 +154,29 @@ export default function SettingsPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleExportData = async () => {
|
||||||
|
setIsExporting(true);
|
||||||
|
try {
|
||||||
|
const data = await UserService.exportData();
|
||||||
|
const blob = new Blob([JSON.stringify(data, null, 2)], {
|
||||||
|
type: "application/json",
|
||||||
|
});
|
||||||
|
const url = window.URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = url;
|
||||||
|
link.setAttribute("download", `memegoat-data-${user?.username}.json`);
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
toast.success("Vos données ont été exportées avec succès.");
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
toast.error("Erreur lors de l'exportation des données.");
|
||||||
|
} finally {
|
||||||
|
setIsExporting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="max-w-2xl mx-auto py-12 px-4">
|
<div className="max-w-2xl mx-auto py-12 px-4">
|
||||||
<div className="flex items-center gap-3 mb-8">
|
<div className="flex items-center gap-3 mb-8">
|
||||||
@@ -239,6 +273,75 @@ export default function SettingsPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{/* Confidentialité */}
|
||||||
|
<Card className="border-none shadow-sm">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Shield className="h-5 w-5 text-primary" />
|
||||||
|
<div>
|
||||||
|
<CardTitle>Confidentialité</CardTitle>
|
||||||
|
<CardDescription>Gérez la visibilité de vos activités.</CardDescription>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Form {...form}>
|
||||||
|
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="showOnlineStatus"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<FormLabel className="text-base">Statut en ligne</FormLabel>
|
||||||
|
<FormDescription>
|
||||||
|
Affiche quand vous êtes actif sur le site.
|
||||||
|
</FormDescription>
|
||||||
|
</div>
|
||||||
|
<FormControl>
|
||||||
|
<Switch checked={field.value} onCheckedChange={field.onChange} />
|
||||||
|
</FormControl>
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
<FormField
|
||||||
|
control={form.control}
|
||||||
|
name="showReadReceipts"
|
||||||
|
render={({ field }) => (
|
||||||
|
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
|
||||||
|
<div className="space-y-0.5">
|
||||||
|
<FormLabel className="text-base">
|
||||||
|
Confirmations de lecture
|
||||||
|
</FormLabel>
|
||||||
|
<FormDescription>
|
||||||
|
Permet aux autres de voir quand vous avez lu leurs messages.
|
||||||
|
</FormDescription>
|
||||||
|
</div>
|
||||||
|
<FormControl>
|
||||||
|
<Switch checked={field.value} onCheckedChange={field.onChange} />
|
||||||
|
</FormControl>
|
||||||
|
</FormItem>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-end pt-2">
|
||||||
|
<Button type="submit" disabled={isSaving} className="min-w-[150px]">
|
||||||
|
{isSaving ? (
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Save className="mr-2 h-4 w-4" />
|
||||||
|
)}
|
||||||
|
Enregistrer
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Form>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<TwoFactorSetup />
|
||||||
|
|
||||||
<Card className="border-none shadow-sm">
|
<Card className="border-none shadow-sm">
|
||||||
<CardHeader className="pb-4">
|
<CardHeader className="pb-4">
|
||||||
<div className="flex items-center gap-2 mb-1">
|
<div className="flex items-center gap-2 mb-1">
|
||||||
@@ -291,6 +394,49 @@ export default function SettingsPage() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<Card className="border-none shadow-sm">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
<Download className="h-5 w-5 text-primary" />
|
||||||
|
<CardTitle>Portabilité des données</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Conformément au RGPD, vous pouvez exporter l'intégralité de vos données
|
||||||
|
rattachées à votre compte.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 p-4 rounded-lg bg-white dark:bg-zinc-900 border">
|
||||||
|
<div className="space-y-1">
|
||||||
|
<p className="font-bold">Exporter mes données</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Téléchargez un fichier JSON contenant votre profil, vos mèmes et vos
|
||||||
|
favoris.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleExportData}
|
||||||
|
disabled={isExporting}
|
||||||
|
className="font-semibold"
|
||||||
|
>
|
||||||
|
{isExporting ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
Exportation...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Download className="h-4 w-4 mr-2" />
|
||||||
|
Exporter mes données
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
<Card className="border-destructive/20 shadow-sm bg-destructive/5">
|
<Card className="border-destructive/20 shadow-sm bg-destructive/5">
|
||||||
<CardHeader className="pb-4">
|
<CardHeader className="pb-4">
|
||||||
<div className="flex items-center gap-2 mb-1">
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ import {
|
|||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
import { useAuth } from "@/providers/auth-provider";
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
|
import { useSocket } from "@/providers/socket-provider";
|
||||||
import { CategoryService } from "@/services/category.service";
|
import { CategoryService } from "@/services/category.service";
|
||||||
import { ContentService } from "@/services/content.service";
|
import { ContentService } from "@/services/content.service";
|
||||||
import type { Category } from "@/types/content";
|
import type { Category } from "@/types/content";
|
||||||
@@ -52,10 +53,32 @@ type UploadFormValues = z.infer<typeof uploadSchema>;
|
|||||||
export default function UploadPage() {
|
export default function UploadPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { isAuthenticated, isLoading } = useAuth();
|
const { isAuthenticated, isLoading } = useAuth();
|
||||||
|
const { socket } = useSocket();
|
||||||
const [categories, setCategories] = React.useState<Category[]>([]);
|
const [categories, setCategories] = React.useState<Category[]>([]);
|
||||||
const [file, setFile] = React.useState<File | null>(null);
|
const [file, setFile] = React.useState<File | null>(null);
|
||||||
const [preview, setPreview] = React.useState<string | null>(null);
|
const [preview, setPreview] = React.useState<string | null>(null);
|
||||||
const [isUploading, setIsUploading] = React.useState(false);
|
const [isUploading, setIsUploading] = React.useState(false);
|
||||||
|
const [uploadStatus, setUploadStatus] = React.useState<string>("");
|
||||||
|
const [uploadProgress, setUploadProgress] = React.useState<number>(0);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (socket) {
|
||||||
|
socket.on(
|
||||||
|
"upload_progress",
|
||||||
|
(data: { status: string; progress: number; message?: string }) => {
|
||||||
|
setUploadStatus(data.status);
|
||||||
|
setUploadProgress(data.progress);
|
||||||
|
if (data.status === "error" && data.message) {
|
||||||
|
toast.error(data.message);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socket.off("upload_progress");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, [socket]);
|
||||||
|
|
||||||
const form = useForm<UploadFormValues>({
|
const form = useForm<UploadFormValues>({
|
||||||
resolver: zodResolver(uploadSchema),
|
resolver: zodResolver(uploadSchema),
|
||||||
@@ -327,10 +350,20 @@ export default function UploadPage() {
|
|||||||
|
|
||||||
<Button type="submit" className="w-full" disabled={isUploading}>
|
<Button type="submit" className="w-full" disabled={isUploading}>
|
||||||
{isUploading ? (
|
{isUploading ? (
|
||||||
<>
|
<div className="flex flex-col items-center gap-1">
|
||||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
<div className="flex items-center gap-2">
|
||||||
Upload en cours...
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
</>
|
<span>{uploadProgress}%</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-[10px] uppercase tracking-wider opacity-70">
|
||||||
|
{uploadStatus === "starting" && "Initialisation..."}
|
||||||
|
{uploadStatus === "scanning" && "Scan Antivirus..."}
|
||||||
|
{uploadStatus === "processing" && "Optimisation..."}
|
||||||
|
{uploadStatus === "uploading_s3" && "Envoi au cloud..."}
|
||||||
|
{uploadStatus === "saving" && "Finalisation..."}
|
||||||
|
{uploadStatus === "completed" && "Terminé !"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
"Publier le mème"
|
"Publier le mème"
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Calendar, Share2, User as UserIcon } from "lucide-react";
|
import {
|
||||||
|
Calendar,
|
||||||
|
MessageCircle,
|
||||||
|
Share2,
|
||||||
|
User as UserIcon,
|
||||||
|
} from "lucide-react";
|
||||||
|
import Link from "next/link";
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { ContentList } from "@/components/content-list";
|
import { ContentList } from "@/components/content-list";
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Spinner } from "@/components/ui/spinner";
|
import { Spinner } from "@/components/ui/spinner";
|
||||||
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
import { ContentService } from "@/services/content.service";
|
import { ContentService } from "@/services/content.service";
|
||||||
import { UserService } from "@/services/user.service";
|
import { UserService } from "@/services/user.service";
|
||||||
import type { User } from "@/types/user";
|
import type { User } from "@/types/user";
|
||||||
@@ -17,9 +24,12 @@ export default function PublicProfilePage({
|
|||||||
params: Promise<{ username: string }>;
|
params: Promise<{ username: string }>;
|
||||||
}) {
|
}) {
|
||||||
const { username } = React.use(params);
|
const { username } = React.use(params);
|
||||||
|
const { user: currentUser, isAuthenticated } = useAuth();
|
||||||
const [user, setUser] = React.useState<User | null>(null);
|
const [user, setUser] = React.useState<User | null>(null);
|
||||||
const [loading, setLoading] = React.useState(true);
|
const [loading, setLoading] = React.useState(true);
|
||||||
|
|
||||||
|
const isOwnProfile = currentUser?.username === username;
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
UserService.getProfile(username)
|
UserService.getProfile(username)
|
||||||
.then(setUser)
|
.then(setUser)
|
||||||
@@ -93,7 +103,15 @@ export default function PublicProfilePage({
|
|||||||
})}
|
})}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex justify-center md:justify-start pt-2">
|
<div className="flex flex-wrap justify-center md:justify-start gap-2 pt-2">
|
||||||
|
{!isOwnProfile && isAuthenticated && (
|
||||||
|
<Button size="sm" className="h-9 px-4" asChild>
|
||||||
|
<Link href={`/messages?user=${user.uuid}`}>
|
||||||
|
<MessageCircle className="h-4 w-4 mr-2" />
|
||||||
|
Message
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import type { Metadata } from "next";
|
import type { Metadata } from "next";
|
||||||
import { Ubuntu_Mono, Ubuntu_Sans } from "next/font/google";
|
import { Ubuntu_Mono, Ubuntu_Sans } from "next/font/google";
|
||||||
|
import { NotificationHandler } from "@/components/notification-handler";
|
||||||
import { Toaster } from "@/components/ui/sonner";
|
import { Toaster } from "@/components/ui/sonner";
|
||||||
import { AudioProvider } from "@/providers/audio-provider";
|
import { AudioProvider } from "@/providers/audio-provider";
|
||||||
import { AuthProvider } from "@/providers/auth-provider";
|
import { AuthProvider } from "@/providers/auth-provider";
|
||||||
|
import { SocketProvider } from "@/providers/socket-provider";
|
||||||
import { ThemeProvider } from "@/providers/theme-provider";
|
import { ThemeProvider } from "@/providers/theme-provider";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
@@ -30,7 +32,7 @@ export const metadata: Metadata = {
|
|||||||
openGraph: {
|
openGraph: {
|
||||||
type: "website",
|
type: "website",
|
||||||
locale: "fr_FR",
|
locale: "fr_FR",
|
||||||
url: "https://memegoat.local",
|
url: "/",
|
||||||
siteName: "MemeGoat",
|
siteName: "MemeGoat",
|
||||||
title: "MemeGoat | Partagez vos meilleurs mèmes",
|
title: "MemeGoat | Partagez vos meilleurs mèmes",
|
||||||
description: "La plateforme ultime pour les mèmes. Rejoignez le troupeau !",
|
description: "La plateforme ultime pour les mèmes. Rejoignez le troupeau !",
|
||||||
@@ -72,10 +74,13 @@ export default function RootLayout({
|
|||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
>
|
>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<AudioProvider>
|
<SocketProvider>
|
||||||
{children}
|
<AudioProvider>
|
||||||
<Toaster />
|
{children}
|
||||||
</AudioProvider>
|
<NotificationHandler />
|
||||||
|
<Toaster />
|
||||||
|
</AudioProvider>
|
||||||
|
</SocketProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
LayoutGrid,
|
LayoutGrid,
|
||||||
LogIn,
|
LogIn,
|
||||||
LogOut,
|
LogOut,
|
||||||
|
MessageCircle,
|
||||||
PlusCircle,
|
PlusCircle,
|
||||||
Settings,
|
Settings,
|
||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
@@ -44,6 +45,7 @@ import {
|
|||||||
SidebarGroupLabel,
|
SidebarGroupLabel,
|
||||||
SidebarHeader,
|
SidebarHeader,
|
||||||
SidebarMenu,
|
SidebarMenu,
|
||||||
|
SidebarMenuBadge,
|
||||||
SidebarMenuButton,
|
SidebarMenuButton,
|
||||||
SidebarMenuItem,
|
SidebarMenuItem,
|
||||||
SidebarMenuSub,
|
SidebarMenuSub,
|
||||||
@@ -53,7 +55,9 @@ import {
|
|||||||
SidebarTrigger,
|
SidebarTrigger,
|
||||||
} from "@/components/ui/sidebar";
|
} from "@/components/ui/sidebar";
|
||||||
import { useAuth } from "@/providers/auth-provider";
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
|
import { useSocket } from "@/providers/socket-provider";
|
||||||
import { CategoryService } from "@/services/category.service";
|
import { CategoryService } from "@/services/category.service";
|
||||||
|
import { MessageService } from "@/services/message.service";
|
||||||
import type { Category } from "@/types/content";
|
import type { Category } from "@/types/content";
|
||||||
|
|
||||||
const mainNav = [
|
const mainNav = [
|
||||||
@@ -78,15 +82,46 @@ export function AppSidebar() {
|
|||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const { user, logout, isAuthenticated } = useAuth();
|
const { user, logout, isAuthenticated } = useAuth();
|
||||||
|
const { socket } = useSocket();
|
||||||
const { resolvedTheme } = useTheme();
|
const { resolvedTheme } = useTheme();
|
||||||
const [categories, setCategories] = React.useState<Category[]>([]);
|
const [categories, setCategories] = React.useState<Category[]>([]);
|
||||||
const [mounted, setMounted] = React.useState(false);
|
const [mounted, setMounted] = React.useState(false);
|
||||||
|
const [unreadMessages, setUnreadMessages] = React.useState(0);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
CategoryService.getAll().then(setCategories).catch(console.error);
|
CategoryService.getAll().then(setCategories).catch(console.error);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Gérer le compteur de messages non-lus
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (isAuthenticated) {
|
||||||
|
MessageService.getUnreadCount().then(setUnreadMessages).catch(console.error);
|
||||||
|
}
|
||||||
|
}, [isAuthenticated]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (socket && isAuthenticated) {
|
||||||
|
socket.on("new_message", () => {
|
||||||
|
// Incrémenter si on n'est pas sur la page messages
|
||||||
|
if (pathname !== "/messages") {
|
||||||
|
setUnreadMessages((prev) => prev + 1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socket.off("new_message");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, [socket, isAuthenticated, pathname]);
|
||||||
|
|
||||||
|
// Remettre à zéro si on arrive sur la page messages
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (pathname === "/messages") {
|
||||||
|
setUnreadMessages(0);
|
||||||
|
}
|
||||||
|
}, [pathname]);
|
||||||
|
|
||||||
const logoSrc = React.useMemo(() => {
|
const logoSrc = React.useMemo(() => {
|
||||||
if (!mounted) return "/memegoat-color.svg";
|
if (!mounted) return "/memegoat-color.svg";
|
||||||
return resolvedTheme === "dark"
|
return resolvedTheme === "dark"
|
||||||
@@ -180,6 +215,25 @@ export function AppSidebar() {
|
|||||||
</Link>
|
</Link>
|
||||||
</SidebarMenuButton>
|
</SidebarMenuButton>
|
||||||
</SidebarMenuItem>
|
</SidebarMenuItem>
|
||||||
|
{isAuthenticated && (
|
||||||
|
<SidebarMenuItem>
|
||||||
|
<SidebarMenuButton
|
||||||
|
asChild
|
||||||
|
isActive={pathname === "/messages"}
|
||||||
|
tooltip="Messages"
|
||||||
|
>
|
||||||
|
<Link href="/messages">
|
||||||
|
<MessageCircle />
|
||||||
|
<span>Messages</span>
|
||||||
|
</Link>
|
||||||
|
</SidebarMenuButton>
|
||||||
|
{unreadMessages > 0 && (
|
||||||
|
<SidebarMenuBadge className="bg-red-500 text-white border-none h-5 min-w-5 flex items-center justify-center p-1 text-[10px]">
|
||||||
|
{unreadMessages > 9 ? "9+" : unreadMessages}
|
||||||
|
</SidebarMenuBadge>
|
||||||
|
)}
|
||||||
|
</SidebarMenuItem>
|
||||||
|
)}
|
||||||
</SidebarMenu>
|
</SidebarMenu>
|
||||||
</SidebarGroup>
|
</SidebarGroup>
|
||||||
|
|
||||||
|
|||||||
314
frontend/src/components/comment-section.tsx
Normal file
314
frontend/src/components/comment-section.tsx
Normal file
@@ -0,0 +1,314 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { formatDistanceToNow } from "date-fns";
|
||||||
|
import { fr } from "date-fns/locale";
|
||||||
|
import { Heart, MoreHorizontal, Send, Trash2 } from "lucide-react";
|
||||||
|
import * as React from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
DropdownMenu,
|
||||||
|
DropdownMenuContent,
|
||||||
|
DropdownMenuItem,
|
||||||
|
DropdownMenuTrigger,
|
||||||
|
} from "@/components/ui/dropdown-menu";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
|
import { useSocket } from "@/providers/socket-provider";
|
||||||
|
import { type Comment, CommentService } from "@/services/comment.service";
|
||||||
|
|
||||||
|
interface CommentSectionProps {
|
||||||
|
contentId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CommentSection({ contentId }: CommentSectionProps) {
|
||||||
|
const { user, isAuthenticated } = useAuth();
|
||||||
|
const { socket } = useSocket();
|
||||||
|
const [comments, setComments] = React.useState<Comment[]>([]);
|
||||||
|
const [newComment, setNewComment] = React.useState("");
|
||||||
|
const [replyingTo, setReplyingTo] = React.useState<Comment | null>(null);
|
||||||
|
const [isSubmitting, setIsSubmitting] = React.useState(false);
|
||||||
|
const [isLoading, setIsLoading] = React.useState(true);
|
||||||
|
|
||||||
|
const fetchComments = React.useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const data = await CommentService.getByContentId(contentId);
|
||||||
|
setComments(data);
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Impossible de charger les commentaires");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, [contentId]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
fetchComments();
|
||||||
|
}, [fetchComments]);
|
||||||
|
|
||||||
|
// Gestion du WebSocket
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (socket) {
|
||||||
|
socket.emit("join_content", contentId);
|
||||||
|
|
||||||
|
socket.on("new_comment", (comment: Comment) => {
|
||||||
|
setComments((prev) => {
|
||||||
|
// Éviter les doublons si l'auteur reçoit son propre commentaire via WS
|
||||||
|
if (prev.some((c) => c.id === comment.id)) return prev;
|
||||||
|
return [comment, ...prev];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socket.emit("leave_content", contentId);
|
||||||
|
socket.off("new_comment");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}, [socket, contentId]);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newComment.trim() || isSubmitting) return;
|
||||||
|
|
||||||
|
setIsSubmitting(true);
|
||||||
|
try {
|
||||||
|
const comment = await CommentService.create(
|
||||||
|
contentId,
|
||||||
|
newComment.trim(),
|
||||||
|
replyingTo?.id,
|
||||||
|
);
|
||||||
|
setComments((prev) => [comment, ...prev]);
|
||||||
|
setNewComment("");
|
||||||
|
setReplyingTo(null);
|
||||||
|
toast.success("Commentaire publié !");
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors de la publication du commentaire");
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (commentId: string) => {
|
||||||
|
try {
|
||||||
|
await CommentService.remove(commentId);
|
||||||
|
setComments((prev) => prev.filter((c) => c.id !== commentId));
|
||||||
|
toast.success("Commentaire supprimé");
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors de la suppression");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLike = async (comment: Comment) => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
toast.error("Vous devez être connecté pour liker");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (comment.isLiked) {
|
||||||
|
await CommentService.unlike(comment.id);
|
||||||
|
setComments((prev) =>
|
||||||
|
prev.map((c) =>
|
||||||
|
c.id === comment.id
|
||||||
|
? { ...c, isLiked: false, likesCount: c.likesCount - 1 }
|
||||||
|
: c,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
await CommentService.like(comment.id);
|
||||||
|
setComments((prev) =>
|
||||||
|
prev.map((c) =>
|
||||||
|
c.id === comment.id
|
||||||
|
? { ...c, isLiked: true, likesCount: c.likesCount + 1 }
|
||||||
|
: c,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Une erreur est survenue");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Organiser les commentaires : Parents d'abord
|
||||||
|
const rootComments = comments.filter((c) => !c.parentId);
|
||||||
|
|
||||||
|
const renderComment = (comment: Comment, depth = 0) => {
|
||||||
|
const replies = comments.filter((c) => c.parentId === comment.id);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={comment.id} className={cn("space-y-4", depth > 0 && "ml-10")}>
|
||||||
|
<div className="flex gap-3">
|
||||||
|
<Avatar className="h-8 w-8 shrink-0">
|
||||||
|
<AvatarImage src={comment.user.avatarUrl} />
|
||||||
|
<AvatarFallback>{comment.user.username[0].toUpperCase()}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1 space-y-1">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-sm font-bold">
|
||||||
|
{comment.user.displayName || comment.user.username}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{formatDistanceToNow(new Date(comment.createdAt), {
|
||||||
|
addSuffix: true,
|
||||||
|
locale: fr,
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className={cn(
|
||||||
|
"h-8 w-8",
|
||||||
|
comment.isLiked && "text-red-500 hover:text-red-600",
|
||||||
|
)}
|
||||||
|
onClick={() => handleLike(comment)}
|
||||||
|
>
|
||||||
|
<Heart className={cn("h-4 w-4", comment.isLiked && "fill-current")} />
|
||||||
|
</Button>
|
||||||
|
{(user?.uuid === comment.user.uuid ||
|
||||||
|
user?.role === "admin" ||
|
||||||
|
user?.role === "moderator") && (
|
||||||
|
<DropdownMenu>
|
||||||
|
<DropdownMenuTrigger asChild>
|
||||||
|
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||||
|
<MoreHorizontal className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
<DropdownMenuContent align="end">
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={() => handleDelete(comment.id)}
|
||||||
|
className="text-destructive"
|
||||||
|
>
|
||||||
|
<Trash2 className="h-4 w-4 mr-2" />
|
||||||
|
Supprimer
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm leading-relaxed whitespace-pre-wrap">
|
||||||
|
{comment.text}
|
||||||
|
</p>
|
||||||
|
<div className="flex items-center gap-4 pt-1">
|
||||||
|
{comment.likesCount > 0 && (
|
||||||
|
<span className="text-xs font-semibold text-muted-foreground">
|
||||||
|
{comment.likesCount} like{comment.likesCount > 1 ? "s" : ""}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{isAuthenticated && depth < 1 && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="h-auto p-0 text-xs font-semibold text-muted-foreground hover:bg-transparent hover:text-foreground"
|
||||||
|
onClick={() => {
|
||||||
|
setReplyingTo(comment);
|
||||||
|
setNewComment(`@${comment.user.username} `);
|
||||||
|
document.querySelector("textarea")?.focus();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Répondre
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{replies.length > 0 && (
|
||||||
|
<div className="space-y-4 pt-2">
|
||||||
|
{replies.map((reply) => renderComment(reply, depth + 1))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 mt-8">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h3 className="font-bold text-lg">Commentaires ({comments.length})</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isAuthenticated ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{replyingTo && (
|
||||||
|
<div className="flex items-center justify-between bg-zinc-100 dark:bg-zinc-800 px-3 py-1.5 rounded-lg text-xs">
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
En réponse à{" "}
|
||||||
|
<span className="font-bold">@{replyingTo.user.username}</span>
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-4 w-4"
|
||||||
|
onClick={() => {
|
||||||
|
setReplyingTo(null);
|
||||||
|
setNewComment("");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<form onSubmit={handleSubmit} className="flex gap-3">
|
||||||
|
<Avatar className="h-8 w-8 shrink-0">
|
||||||
|
<AvatarImage src={user?.avatarUrl} />
|
||||||
|
<AvatarFallback>{user?.username[0].toUpperCase()}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex-1 space-y-2">
|
||||||
|
<Textarea
|
||||||
|
placeholder={
|
||||||
|
replyingTo ? "Ajouter une réponse..." : "Ajouter un commentaire..."
|
||||||
|
}
|
||||||
|
value={newComment}
|
||||||
|
onChange={(e) => setNewComment(e.target.value)}
|
||||||
|
className="min-h-[80px] resize-none"
|
||||||
|
/>
|
||||||
|
<div className="flex justify-end gap-2">
|
||||||
|
{replyingTo && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
setReplyingTo(null);
|
||||||
|
setNewComment("");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
size="sm"
|
||||||
|
disabled={!newComment.trim() || isSubmitting}
|
||||||
|
>
|
||||||
|
{isSubmitting ? "Envoi..." : replyingTo ? "Répondre" : "Publier"}
|
||||||
|
<Send className="ml-2 h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="bg-zinc-100 dark:bg-zinc-800 p-4 rounded-xl text-center text-sm">
|
||||||
|
Connectez-vous pour laisser un commentaire.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="space-y-6">
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="text-center text-muted-foreground py-4">Chargement...</div>
|
||||||
|
) : rootComments.length === 0 ? (
|
||||||
|
<div className="text-center text-muted-foreground py-4">
|
||||||
|
Aucun commentaire pour le moment. Soyez le premier !
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
rootComments.map((comment) => renderComment(comment))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
import {
|
import {
|
||||||
Edit,
|
Edit,
|
||||||
Eye,
|
Eye,
|
||||||
|
Flag,
|
||||||
Heart,
|
Heart,
|
||||||
MoreHorizontal,
|
MoreHorizontal,
|
||||||
Share2,
|
Share2,
|
||||||
@@ -34,7 +35,9 @@ import { useAuth } from "@/providers/auth-provider";
|
|||||||
import { ContentService } from "@/services/content.service";
|
import { ContentService } from "@/services/content.service";
|
||||||
import { FavoriteService } from "@/services/favorite.service";
|
import { FavoriteService } from "@/services/favorite.service";
|
||||||
import type { Content } from "@/types/content";
|
import type { Content } from "@/types/content";
|
||||||
|
import { ShareDialog } from "./share-dialog";
|
||||||
import { UserContentEditDialog } from "./user-content-edit-dialog";
|
import { UserContentEditDialog } from "./user-content-edit-dialog";
|
||||||
|
import { ViewCounter } from "./view-counter";
|
||||||
|
|
||||||
interface ContentCardProps {
|
interface ContentCardProps {
|
||||||
content: Content;
|
content: Content;
|
||||||
@@ -49,6 +52,8 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
|||||||
const [isLiked, setIsLiked] = React.useState(content.isLiked || false);
|
const [isLiked, setIsLiked] = React.useState(content.isLiked || false);
|
||||||
const [likesCount, setLikesCount] = React.useState(content.favoritesCount);
|
const [likesCount, setLikesCount] = React.useState(content.favoritesCount);
|
||||||
const [editDialogOpen, setEditDialogOpen] = React.useState(false);
|
const [editDialogOpen, setEditDialogOpen] = React.useState(false);
|
||||||
|
const [shareDialogOpen, setShareDialogOpen] = React.useState(false);
|
||||||
|
const [_reportDialogOpen, setReportDialogOpen] = React.useState(false);
|
||||||
|
|
||||||
const isAuthor = user?.uuid === content.authorId;
|
const isAuthor = user?.uuid === content.authorId;
|
||||||
const isVideo = !content.mimeType.startsWith("image/");
|
const isVideo = !content.mimeType.startsWith("image/");
|
||||||
@@ -96,6 +101,8 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
|||||||
await FavoriteService.add(content.id);
|
await FavoriteService.add(content.id);
|
||||||
setIsLiked(true);
|
setIsLiked(true);
|
||||||
setLikesCount((prev) => prev + 1);
|
setLikesCount((prev) => prev + 1);
|
||||||
|
// Considérer un like comme une vue
|
||||||
|
ContentService.incrementViews(content.id).catch(() => {});
|
||||||
}
|
}
|
||||||
} catch (_error) {
|
} catch (_error) {
|
||||||
toast.error("Une erreur est survenue");
|
toast.error("Une erreur est survenue");
|
||||||
@@ -144,6 +151,7 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<ViewCounter contentId={content.id} videoRef={videoRef} />
|
||||||
<Card className="overflow-hidden border-none gap-0 shadow-none bg-transparent">
|
<Card className="overflow-hidden border-none gap-0 shadow-none bg-transparent">
|
||||||
<CardHeader className="p-3 flex flex-row items-center space-y-0 gap-3">
|
<CardHeader className="p-3 flex flex-row items-center space-y-0 gap-3">
|
||||||
<Avatar className="h-8 w-8 border">
|
<Avatar className="h-8 w-8 border">
|
||||||
@@ -184,10 +192,24 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
|||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<DropdownMenuItem onClick={() => toast.success("Lien copié !")}>
|
<DropdownMenuItem
|
||||||
|
onClick={() => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
toast.error("Connectez-vous pour partager");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setShareDialogOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
<Share2 className="h-4 w-4 mr-2" />
|
<Share2 className="h-4 w-4 mr-2" />
|
||||||
Partager
|
Partager
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
{!isAuthor && (
|
||||||
|
<DropdownMenuItem onClick={() => setReportDialogOpen(true)}>
|
||||||
|
<Flag className="h-4 w-4 mr-2" />
|
||||||
|
Signaler
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</div>
|
</div>
|
||||||
@@ -251,10 +273,11 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
navigator.clipboard.writeText(
|
if (!isAuthenticated) {
|
||||||
`${window.location.origin}/meme/${content.slug}`,
|
toast.error("Connectez-vous pour partager");
|
||||||
);
|
return;
|
||||||
toast.success("Lien copié !");
|
}
|
||||||
|
setShareDialogOpen(true);
|
||||||
}}
|
}}
|
||||||
className="hover:text-muted-foreground"
|
className="hover:text-muted-foreground"
|
||||||
>
|
>
|
||||||
@@ -310,6 +333,13 @@ export function ContentCard({ content, onUpdate }: ContentCardProps) {
|
|||||||
onOpenChange={setEditDialogOpen}
|
onOpenChange={setEditDialogOpen}
|
||||||
onSuccess={() => onUpdate?.()}
|
onSuccess={() => onUpdate?.()}
|
||||||
/>
|
/>
|
||||||
|
<ShareDialog
|
||||||
|
contentId={content.id}
|
||||||
|
contentTitle={content.title}
|
||||||
|
contentUrl={`${typeof window !== "undefined" ? window.location.origin : ""}/meme/${content.slug}`}
|
||||||
|
open={shareDialogOpen}
|
||||||
|
onOpenChange={setShareDialogOpen}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
108
frontend/src/components/notification-handler.tsx
Normal file
108
frontend/src/components/notification-handler.tsx
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Bell, Heart, MessageCircle, Reply } from "lucide-react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import * as React from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { useSocket } from "@/providers/socket-provider";
|
||||||
|
|
||||||
|
interface NotificationData {
|
||||||
|
type: "comment" | "reply" | "like_comment" | "message";
|
||||||
|
userId: string;
|
||||||
|
username: string;
|
||||||
|
contentId?: string;
|
||||||
|
commentId?: string;
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function NotificationHandler() {
|
||||||
|
const { socket } = useSocket();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!socket) return;
|
||||||
|
|
||||||
|
const handleNotification = (data: NotificationData) => {
|
||||||
|
// Ne pas afficher de toast si on est déjà sur la page des messages pour un nouveau message
|
||||||
|
if (data.type === "message" && window.location.pathname === "/messages") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
toast.custom(
|
||||||
|
(t) => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex items-start gap-3 bg-white dark:bg-zinc-900 p-4 rounded-xl shadow-lg border border-zinc-200 dark:border-zinc-800 w-full max-w-sm cursor-pointer hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors text-left"
|
||||||
|
onClick={() => {
|
||||||
|
toast.dismiss(t);
|
||||||
|
if (data.type === "message") {
|
||||||
|
router.push("/messages");
|
||||||
|
} else if (data.contentId) {
|
||||||
|
router.push(`/meme/${data.contentId}`);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="bg-primary/10 p-2 rounded-full shrink-0">
|
||||||
|
{data.type === "comment" && (
|
||||||
|
<MessageCircle className="h-4 w-4 text-primary" />
|
||||||
|
)}
|
||||||
|
{data.type === "reply" && <Reply className="h-4 w-4 text-primary" />}
|
||||||
|
{data.type === "like_comment" && (
|
||||||
|
<Heart className="h-4 w-4 text-red-500" />
|
||||||
|
)}
|
||||||
|
{data.type === "message" && (
|
||||||
|
<MessageCircle className="h-4 w-4 text-primary" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 overflow-hidden">
|
||||||
|
<p className="text-sm font-bold">@{data.username}</p>
|
||||||
|
<p className="text-xs text-muted-foreground truncate">{data.text}</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-muted-foreground hover:text-foreground p-1 rounded-full hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
toast.dismiss(t);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Bell className="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</button>
|
||||||
|
),
|
||||||
|
{
|
||||||
|
duration: 5000,
|
||||||
|
position: "top-right",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.on("notification", handleNotification);
|
||||||
|
|
||||||
|
// Aussi pour les nouveaux messages (si on veut un toast global)
|
||||||
|
socket.on(
|
||||||
|
"new_message",
|
||||||
|
(data: { message: { text: string; sender?: { username: string } } }) => {
|
||||||
|
if (window.location.pathname !== "/messages") {
|
||||||
|
toast(
|
||||||
|
`Nouveau message de @${data.message.sender?.username || "un membre"}`,
|
||||||
|
{
|
||||||
|
description: data.message.text.substring(0, 50),
|
||||||
|
action: {
|
||||||
|
label: "Voir",
|
||||||
|
onClick: () => router.push("/messages"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socket.off("notification");
|
||||||
|
socket.off("new_message");
|
||||||
|
};
|
||||||
|
}, [socket, router]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
119
frontend/src/components/report-dialog.tsx
Normal file
119
frontend/src/components/report-dialog.tsx
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
|
import { ReportReason, ReportService } from "@/services/report.service";
|
||||||
|
|
||||||
|
interface ReportDialogProps {
|
||||||
|
contentId?: string;
|
||||||
|
tagId?: string;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReportDialog({
|
||||||
|
contentId,
|
||||||
|
tagId,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: ReportDialogProps) {
|
||||||
|
const [reason, setReason] = useState<ReportReason>(ReportReason.INAPPROPRIATE);
|
||||||
|
const [description, setDescription] = useState("");
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
setIsSubmitting(true);
|
||||||
|
try {
|
||||||
|
await ReportService.create({
|
||||||
|
contentId,
|
||||||
|
tagId,
|
||||||
|
reason,
|
||||||
|
description,
|
||||||
|
});
|
||||||
|
toast.success(
|
||||||
|
"Signalement envoyé avec succès. Merci de nous aider à maintenir la communauté sûre.",
|
||||||
|
);
|
||||||
|
onOpenChange(false);
|
||||||
|
setDescription("");
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors de l'envoi du signalement.");
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Signaler le contenu</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
Pourquoi signalez-vous ce contenu ? Un modérateur examinera votre demande.
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="grid gap-4 py-4">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="reason">Raison</Label>
|
||||||
|
<Select
|
||||||
|
value={reason}
|
||||||
|
onValueChange={(value) => setReason(value as ReportReason)}
|
||||||
|
>
|
||||||
|
<SelectTrigger id="reason">
|
||||||
|
<SelectValue placeholder="Sélectionnez une raison" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value={ReportReason.INAPPROPRIATE}>Inapproprié</SelectItem>
|
||||||
|
<SelectItem value={ReportReason.SPAM}>Spam</SelectItem>
|
||||||
|
<SelectItem value={ReportReason.COPYRIGHT}>Droit d'auteur</SelectItem>
|
||||||
|
<SelectItem value={ReportReason.OTHER}>Autre</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="description">Description (optionnelle)</Label>
|
||||||
|
<Textarea
|
||||||
|
id="description"
|
||||||
|
placeholder="Détaillez votre signalement..."
|
||||||
|
value={description}
|
||||||
|
onChange={(e) => setDescription(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => onOpenChange(false)}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
>
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={isSubmitting}
|
||||||
|
>
|
||||||
|
{isSubmitting ? "Envoi..." : "Signaler"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
186
frontend/src/components/share-dialog.tsx
Normal file
186
frontend/src/components/share-dialog.tsx
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Search, Send, X } from "lucide-react";
|
||||||
|
import * as React from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||||
|
import { MessageService } from "@/services/message.service";
|
||||||
|
import { UserService } from "@/services/user.service";
|
||||||
|
import type { User } from "@/types/user";
|
||||||
|
|
||||||
|
interface ShareDialogProps {
|
||||||
|
contentId: string;
|
||||||
|
contentTitle: string;
|
||||||
|
contentUrl: string;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ShareDialog({
|
||||||
|
contentId,
|
||||||
|
contentTitle,
|
||||||
|
contentUrl: _unused, // Support legacy prop
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
}: ShareDialogProps) {
|
||||||
|
const [searchQuery, setSearchQuery] = React.useState("");
|
||||||
|
const [results, setResults] = React.useState<User[]>([]);
|
||||||
|
const [isLoading, setIsLoading] = React.useState(false);
|
||||||
|
const [sendingTo, setSendingTo] = React.useState<string | null>(null);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (!open) {
|
||||||
|
setSearchQuery("");
|
||||||
|
setResults([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchInitial = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
// Par défaut, montrer les conversations récentes ou suggérer des gens
|
||||||
|
const recent = await UserService.search("");
|
||||||
|
setResults(recent);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch users", error);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
fetchInitial();
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (searchQuery.length < 2) return;
|
||||||
|
|
||||||
|
const timeout = setTimeout(async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const data = await UserService.search(searchQuery);
|
||||||
|
setResults(data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Search failed", error);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}, 300);
|
||||||
|
|
||||||
|
return () => clearTimeout(timeout);
|
||||||
|
}, [searchQuery]);
|
||||||
|
|
||||||
|
const handleShare = async (user: User) => {
|
||||||
|
setSendingTo(user.uuid);
|
||||||
|
try {
|
||||||
|
const shareUrl = `${window.location.origin}/meme/${contentId}`;
|
||||||
|
await MessageService.sendMessage(
|
||||||
|
user.uuid,
|
||||||
|
`Regarde ce mème : ${contentTitle}\n${shareUrl}`,
|
||||||
|
);
|
||||||
|
toast.success(`Partagé avec @${user.username}`);
|
||||||
|
onOpenChange(false);
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Échec du partage");
|
||||||
|
} finally {
|
||||||
|
setSendingTo(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="sm:max-w-[425px] p-0 gap-0 overflow-hidden">
|
||||||
|
<DialogHeader className="p-4 border-b">
|
||||||
|
<DialogTitle>Partager avec</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="p-4 border-b">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
placeholder="Rechercher un membre..."
|
||||||
|
className="pl-9 h-9"
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
{searchQuery && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSearchQuery("")}
|
||||||
|
className="absolute right-3 top-1/2 -translate-y-1/2 p-0.5 hover:bg-zinc-100 dark:hover:bg-zinc-800 rounded-full"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3 text-muted-foreground" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ScrollArea className="h-[300px]">
|
||||||
|
<div className="p-2 space-y-1">
|
||||||
|
{isLoading && results.length === 0 ? (
|
||||||
|
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
Chargement...
|
||||||
|
</div>
|
||||||
|
) : results.length === 0 ? (
|
||||||
|
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
Aucun membre trouvé.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
results.map((user) => (
|
||||||
|
<div
|
||||||
|
key={user.uuid}
|
||||||
|
className="flex items-center justify-between p-2 rounded-lg hover:bg-zinc-100 dark:hover:bg-zinc-900"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Avatar className="h-9 w-9">
|
||||||
|
<AvatarImage src={user.avatarUrl} />
|
||||||
|
<AvatarFallback>{user.username[0].toUpperCase()}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="text-sm font-bold leading-none">
|
||||||
|
{user.displayName || user.username}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
@{user.username}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant={sendingTo === user.uuid ? "outline" : "default"}
|
||||||
|
disabled={sendingTo !== null}
|
||||||
|
onClick={() => handleShare(user)}
|
||||||
|
className="h-8 px-4 rounded-full"
|
||||||
|
>
|
||||||
|
{sendingTo === user.uuid ? "Envoi..." : "Envoyer"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</ScrollArea>
|
||||||
|
<div className="p-4 border-t bg-zinc-50 dark:bg-zinc-900/50">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
className="w-full justify-start gap-2 h-10 rounded-xl"
|
||||||
|
onClick={() => {
|
||||||
|
navigator.clipboard.writeText(
|
||||||
|
`${window.location.origin}/meme/${contentId}`,
|
||||||
|
);
|
||||||
|
toast.success("Lien copié !");
|
||||||
|
onOpenChange(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Send className="h-4 w-4" />
|
||||||
|
Copier le lien
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
294
frontend/src/components/two-factor-setup.tsx
Normal file
294
frontend/src/components/two-factor-setup.tsx
Normal file
@@ -0,0 +1,294 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Loader2, Shield, ShieldAlert, ShieldCheck } from "lucide-react";
|
||||||
|
import Image from "next/image";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardFooter,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import {
|
||||||
|
InputOTP,
|
||||||
|
InputOTPGroup,
|
||||||
|
InputOTPSeparator,
|
||||||
|
InputOTPSlot,
|
||||||
|
} from "@/components/ui/input-otp";
|
||||||
|
import { useAuth } from "@/providers/auth-provider";
|
||||||
|
import { AuthService } from "@/services/auth.service";
|
||||||
|
|
||||||
|
export function TwoFactorSetup() {
|
||||||
|
const { user, refreshUser } = useAuth();
|
||||||
|
const [step, setStep] = useState<"idle" | "setup" | "verify">("idle");
|
||||||
|
const [qrCode, setQrCode] = useState<string | null>(null);
|
||||||
|
const [secret, setSecret] = useState<string | null>(null);
|
||||||
|
const [otpValue, setOtpValue] = useState("");
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isRevealed, setIsRevealed] = useState(false);
|
||||||
|
|
||||||
|
const handleSetup = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const data = await AuthService.setup2fa();
|
||||||
|
setQrCode(data.qrCodeUrl);
|
||||||
|
setSecret(data.secret);
|
||||||
|
setStep("setup");
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Erreur lors de la configuration de la 2FA.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEnable = async () => {
|
||||||
|
if (otpValue.length !== 6) return;
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
await AuthService.enable2fa(otpValue);
|
||||||
|
toast.success("Double authentification activée !");
|
||||||
|
await refreshUser();
|
||||||
|
setStep("idle");
|
||||||
|
setOtpValue("");
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Code invalide. Veuillez réessayer.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDisable = async () => {
|
||||||
|
if (otpValue.length !== 6) return;
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
await AuthService.disable2fa(otpValue);
|
||||||
|
toast.success("Double authentification désactivée.");
|
||||||
|
await refreshUser();
|
||||||
|
setStep("idle");
|
||||||
|
setOtpValue("");
|
||||||
|
} catch (_error) {
|
||||||
|
toast.error("Code invalide. Veuillez réessayer.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Note: We need a way to know if 2FA is enabled.
|
||||||
|
const isEnabled = user?.twoFactorEnabled;
|
||||||
|
|
||||||
|
if (step === "idle") {
|
||||||
|
return (
|
||||||
|
<Card className="border-none shadow-sm">
|
||||||
|
<CardHeader className="pb-4">
|
||||||
|
<div className="flex items-center gap-2 mb-1">
|
||||||
|
<Shield className="h-5 w-5 text-primary" />
|
||||||
|
<CardTitle>Double Authentification (2FA)</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Ajoutez une couche de sécurité supplémentaire à votre compte en utilisant
|
||||||
|
une application d'authentification.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="flex items-center gap-4 p-4 rounded-lg bg-zinc-50 dark:bg-zinc-900 border">
|
||||||
|
{isEnabled ? (
|
||||||
|
<>
|
||||||
|
<div className="bg-green-100 dark:bg-green-900/30 p-2 rounded-full">
|
||||||
|
<ShieldCheck className="h-6 w-6 text-green-600 dark:text-green-400" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className="font-bold">La 2FA est activée</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Votre compte est protégé par un code temporaire.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button variant="outline" size="sm" onClick={() => setStep("verify")}>
|
||||||
|
Désactiver
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="bg-zinc-200 dark:bg-zinc-800 p-2 rounded-full">
|
||||||
|
<ShieldAlert className="h-6 w-6 text-zinc-500" />
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className="font-bold">La 2FA n'est pas activée</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Activez la 2FA pour mieux protéger votre compte.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="default"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleSetup}
|
||||||
|
disabled={isLoading}
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
"Configurer"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (step === "setup") {
|
||||||
|
return (
|
||||||
|
<Card className="border-none shadow-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Configurer la 2FA</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Scannez le QR Code ci-dessous avec votre application d'authentification
|
||||||
|
(Google Authenticator, Authy, etc.).
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col items-center gap-6">
|
||||||
|
{qrCode && (
|
||||||
|
<div className="relative group">
|
||||||
|
<div
|
||||||
|
className={`bg-white p-4 rounded-xl border-4 border-zinc-100 transition-all duration-300 ${
|
||||||
|
!isRevealed ? "blur-md select-none" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Image
|
||||||
|
src={qrCode}
|
||||||
|
alt="QR Code 2FA"
|
||||||
|
width={192}
|
||||||
|
height={192}
|
||||||
|
className="w-48 h-48"
|
||||||
|
unoptimized
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{!isRevealed && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center">
|
||||||
|
<Button
|
||||||
|
variant="secondary"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setIsRevealed(true)}
|
||||||
|
className="shadow-lg"
|
||||||
|
>
|
||||||
|
Afficher le QR Code
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="w-full space-y-2">
|
||||||
|
<p className="text-sm font-medium text-center">
|
||||||
|
Ou entrez ce code manuellement :
|
||||||
|
</p>
|
||||||
|
<div className="relative group">
|
||||||
|
<code
|
||||||
|
className={`block p-2 bg-muted text-center rounded text-xs font-mono break-all transition-all duration-300 ${
|
||||||
|
!isRevealed ? "blur-[3px] select-none" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{secret}
|
||||||
|
</code>
|
||||||
|
{!isRevealed && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setIsRevealed(true)}
|
||||||
|
className="text-[10px] font-bold uppercase tracking-wider text-primary hover:underline"
|
||||||
|
>
|
||||||
|
Afficher le code
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-center gap-4 w-full border-t pt-6">
|
||||||
|
<p className="text-sm font-medium">
|
||||||
|
Entrez le code à 6 chiffres pour confirmer :
|
||||||
|
</p>
|
||||||
|
<InputOTP maxLength={6} value={otpValue} onChange={setOtpValue}>
|
||||||
|
<InputOTPGroup>
|
||||||
|
<InputOTPSlot index={0} />
|
||||||
|
<InputOTPSlot index={1} />
|
||||||
|
<InputOTPSlot index={2} />
|
||||||
|
</InputOTPGroup>
|
||||||
|
<InputOTPSeparator />
|
||||||
|
<InputOTPGroup>
|
||||||
|
<InputOTPSlot index={3} />
|
||||||
|
<InputOTPSlot index={4} />
|
||||||
|
<InputOTPSlot index={5} />
|
||||||
|
</InputOTPGroup>
|
||||||
|
</InputOTP>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
<CardFooter className="flex justify-between">
|
||||||
|
<Button variant="ghost" onClick={() => setStep("idle")}>
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleEnable}
|
||||||
|
disabled={otpValue.length !== 6 || isLoading}
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
"Activer la 2FA"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (step === "verify") {
|
||||||
|
return (
|
||||||
|
<Card className="border-none shadow-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Désactiver la 2FA</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Veuillez entrer le code de votre application pour désactiver la double
|
||||||
|
authentification.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="flex flex-col items-center gap-6">
|
||||||
|
<InputOTP maxLength={6} value={otpValue} onChange={setOtpValue}>
|
||||||
|
<InputOTPGroup>
|
||||||
|
<InputOTPSlot index={0} />
|
||||||
|
<InputOTPSlot index={1} />
|
||||||
|
<InputOTPSlot index={2} />
|
||||||
|
</InputOTPGroup>
|
||||||
|
<InputOTPSeparator />
|
||||||
|
<InputOTPGroup>
|
||||||
|
<InputOTPSlot index={3} />
|
||||||
|
<InputOTPSlot index={4} />
|
||||||
|
<InputOTPSlot index={5} />
|
||||||
|
</InputOTPGroup>
|
||||||
|
</InputOTP>
|
||||||
|
</CardContent>
|
||||||
|
<CardFooter className="flex justify-between">
|
||||||
|
<Button variant="ghost" onClick={() => setStep("idle")}>
|
||||||
|
Annuler
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="destructive"
|
||||||
|
onClick={handleDisable}
|
||||||
|
disabled={otpValue.length !== 6 || isLoading}
|
||||||
|
>
|
||||||
|
{isLoading ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
"Confirmer la désactivation"
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</CardFooter>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -7,17 +7,23 @@ import { cn } from "@/lib/utils";
|
|||||||
|
|
||||||
function Avatar({
|
function Avatar({
|
||||||
className,
|
className,
|
||||||
|
isOnline,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
}: React.ComponentProps<typeof AvatarPrimitive.Root> & { isOnline?: boolean }) {
|
||||||
return (
|
return (
|
||||||
<AvatarPrimitive.Root
|
<div className="relative inline-block">
|
||||||
data-slot="avatar"
|
<AvatarPrimitive.Root
|
||||||
className={cn(
|
data-slot="avatar"
|
||||||
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
className={cn(
|
||||||
className,
|
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
{isOnline && (
|
||||||
|
<span className="absolute bottom-0 right-0 block h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-white dark:ring-zinc-900" />
|
||||||
)}
|
)}
|
||||||
{...props}
|
</div>
|
||||||
/>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,8 +8,11 @@ import { cn } from "@/lib/utils";
|
|||||||
function ScrollArea({
|
function ScrollArea({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
|
viewportRef,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
|
||||||
|
viewportRef?: React.Ref<HTMLDivElement>;
|
||||||
|
}) {
|
||||||
return (
|
return (
|
||||||
<ScrollAreaPrimitive.Root
|
<ScrollAreaPrimitive.Root
|
||||||
data-slot="scroll-area"
|
data-slot="scroll-area"
|
||||||
@@ -18,6 +21,7 @@ function ScrollArea({
|
|||||||
>
|
>
|
||||||
<ScrollAreaPrimitive.Viewport
|
<ScrollAreaPrimitive.Viewport
|
||||||
data-slot="scroll-area-viewport"
|
data-slot="scroll-area-viewport"
|
||||||
|
ref={viewportRef}
|
||||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -1,23 +1,74 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef } from "react";
|
import { type RefObject, useEffect, useRef } from "react";
|
||||||
import { ContentService } from "@/services/content.service";
|
import { ContentService } from "@/services/content.service";
|
||||||
|
|
||||||
interface ViewCounterProps {
|
interface ViewCounterProps {
|
||||||
contentId: string;
|
contentId: string;
|
||||||
|
videoRef?: RefObject<HTMLVideoElement | null>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ViewCounter({ contentId }: ViewCounterProps) {
|
export function ViewCounter({ contentId, videoRef }: ViewCounterProps) {
|
||||||
const hasIncremented = useRef(false);
|
const hasIncremented = useRef(false);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!hasIncremented.current) {
|
const increment = () => {
|
||||||
ContentService.incrementViews(contentId).catch((err) => {
|
if (!hasIncremented.current) {
|
||||||
console.error("Failed to increment views:", err);
|
ContentService.incrementViews(contentId).catch((err) => {
|
||||||
});
|
console.error("Failed to increment views:", err);
|
||||||
hasIncremented.current = true;
|
});
|
||||||
}
|
hasIncremented.current = true;
|
||||||
}, [contentId]);
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return null;
|
// 1. Observer pour la visibilité (IntersectionObserver)
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
const entry = entries[0];
|
||||||
|
if (entry.isIntersecting) {
|
||||||
|
// Si c'est une image (pas de videoRef), on attend 3 secondes
|
||||||
|
if (!videoRef) {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
increment();
|
||||||
|
}, 3000);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.5 },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (containerRef.current) {
|
||||||
|
observer.observe(containerRef.current);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Logique pour la vidéo (> 50%)
|
||||||
|
let videoElement: HTMLVideoElement | null = null;
|
||||||
|
const handleTimeUpdate = () => {
|
||||||
|
if (videoElement && videoElement.duration > 0) {
|
||||||
|
const progress = videoElement.currentTime / videoElement.duration;
|
||||||
|
if (progress >= 0.5) {
|
||||||
|
increment();
|
||||||
|
videoElement.removeEventListener("timeupdate", handleTimeUpdate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (videoRef?.current) {
|
||||||
|
videoElement = videoRef.current;
|
||||||
|
videoElement.addEventListener("timeupdate", handleTimeUpdate);
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
observer.disconnect();
|
||||||
|
if (videoElement) {
|
||||||
|
videoElement.removeEventListener("timeupdate", handleTimeUpdate);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [contentId, videoRef]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={containerRef} className="absolute inset-0 pointer-events-none" />
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,14 +5,15 @@ import * as React from "react";
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { AuthService } from "@/services/auth.service";
|
import { AuthService } from "@/services/auth.service";
|
||||||
import { UserService } from "@/services/user.service";
|
import { UserService } from "@/services/user.service";
|
||||||
import type { RegisterPayload } from "@/types/auth";
|
import type { LoginResponse, RegisterPayload } from "@/types/auth";
|
||||||
import type { User } from "@/types/user";
|
import type { User } from "@/types/user";
|
||||||
|
|
||||||
interface AuthContextType {
|
interface AuthContextType {
|
||||||
user: User | null;
|
user: User | null;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
isAuthenticated: boolean;
|
isAuthenticated: boolean;
|
||||||
login: (email: string, password: string) => Promise<void>;
|
login: (email: string, password: string) => Promise<LoginResponse>;
|
||||||
|
verify2fa: (userId: string, token: string) => Promise<void>;
|
||||||
register: (payload: RegisterPayload) => Promise<void>;
|
register: (payload: RegisterPayload) => Promise<void>;
|
||||||
logout: () => Promise<void>;
|
logout: () => Promise<void>;
|
||||||
refreshUser: () => Promise<void>;
|
refreshUser: () => Promise<void>;
|
||||||
@@ -59,12 +60,43 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
|
|
||||||
const login = async (email: string, password: string) => {
|
const login = async (email: string, password: string) => {
|
||||||
try {
|
try {
|
||||||
await AuthService.login(email, password);
|
const response = await AuthService.login(email, password);
|
||||||
|
if (response.userId && response.message === "Please provide 2FA token") {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
await refreshUser();
|
||||||
|
toast.success("Connexion réussie !");
|
||||||
|
router.push("/");
|
||||||
|
return response;
|
||||||
|
} catch (error: unknown) {
|
||||||
|
let errorMessage = "Erreur de connexion";
|
||||||
|
if (
|
||||||
|
error &&
|
||||||
|
typeof error === "object" &&
|
||||||
|
"response" in error &&
|
||||||
|
error.response &&
|
||||||
|
typeof error.response === "object" &&
|
||||||
|
"data" in error.response &&
|
||||||
|
error.response.data &&
|
||||||
|
typeof error.response.data === "object" &&
|
||||||
|
"message" in error.response.data &&
|
||||||
|
typeof error.response.data.message === "string"
|
||||||
|
) {
|
||||||
|
errorMessage = error.response.data.message;
|
||||||
|
}
|
||||||
|
toast.error(errorMessage);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const verify2fa = async (userId: string, token: string) => {
|
||||||
|
try {
|
||||||
|
await AuthService.verify2fa(userId, token);
|
||||||
await refreshUser();
|
await refreshUser();
|
||||||
toast.success("Connexion réussie !");
|
toast.success("Connexion réussie !");
|
||||||
router.push("/");
|
router.push("/");
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
let errorMessage = "Erreur de connexion";
|
let errorMessage = "Code 2FA invalide";
|
||||||
if (
|
if (
|
||||||
error &&
|
error &&
|
||||||
typeof error === "object" &&
|
typeof error === "object" &&
|
||||||
@@ -130,6 +162,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
isLoading,
|
isLoading,
|
||||||
isAuthenticated: !!user,
|
isAuthenticated: !!user,
|
||||||
login,
|
login,
|
||||||
|
verify2fa,
|
||||||
register,
|
register,
|
||||||
logout,
|
logout,
|
||||||
refreshUser,
|
refreshUser,
|
||||||
|
|||||||
66
frontend/src/providers/socket-provider.tsx
Normal file
66
frontend/src/providers/socket-provider.tsx
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import { io, type Socket } from "socket.io-client";
|
||||||
|
import { useAuth } from "./auth-provider";
|
||||||
|
|
||||||
|
interface SocketContextType {
|
||||||
|
socket: Socket | null;
|
||||||
|
isConnected: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SocketContext = React.createContext<SocketContextType>({
|
||||||
|
socket: null,
|
||||||
|
isConnected: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const useSocket = () => React.useContext(SocketContext);
|
||||||
|
|
||||||
|
export function SocketProvider({ children }: { children: React.ReactNode }) {
|
||||||
|
const { isAuthenticated } = useAuth();
|
||||||
|
const [socket, setSocket] = React.useState<Socket | null>(null);
|
||||||
|
const [isConnected, setIsConnected] = React.useState(false);
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (isAuthenticated) {
|
||||||
|
const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000";
|
||||||
|
|
||||||
|
// Initialisation du socket avec configuration optimisée pour la production
|
||||||
|
const socketInstance = io(apiUrl, {
|
||||||
|
withCredentials: true,
|
||||||
|
transports: ["websocket"], // Recommandé pour éviter les problèmes de sticky sessions
|
||||||
|
reconnectionAttempts: 5,
|
||||||
|
reconnectionDelay: 1000,
|
||||||
|
});
|
||||||
|
|
||||||
|
socketInstance.on("connect", () => {
|
||||||
|
console.log("WebSocket connected to:", apiUrl);
|
||||||
|
setIsConnected(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
socketInstance.on("connect_error", (error) => {
|
||||||
|
console.error("WebSocket connection error:", error);
|
||||||
|
// Si le websocket pur échoue, on peut tenter le polling en fallback (optionnel)
|
||||||
|
});
|
||||||
|
|
||||||
|
socketInstance.on("disconnect", () => {
|
||||||
|
setIsConnected(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
setSocket(socketInstance);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socketInstance.disconnect();
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
setSocket(null);
|
||||||
|
setIsConnected(false);
|
||||||
|
}
|
||||||
|
}, [isAuthenticated]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<SocketContext.Provider value={{ socket, isConnected }}>
|
||||||
|
{children}
|
||||||
|
</SocketContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import api from "@/lib/api";
|
import api from "@/lib/api";
|
||||||
|
import type { User } from "@/types/user";
|
||||||
|
import type { Report, ReportStatus } from "./report.service";
|
||||||
|
|
||||||
export interface AdminStats {
|
export interface AdminStats {
|
||||||
users: number;
|
users: number;
|
||||||
@@ -11,4 +13,24 @@ export const adminService = {
|
|||||||
const response = await api.get("/admin/stats");
|
const response = await api.get("/admin/stats");
|
||||||
return response.data;
|
return response.data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getReports: async (limit = 10, offset = 0): Promise<Report[]> => {
|
||||||
|
const response = await api.get("/reports", { params: { limit, offset } });
|
||||||
|
return response.data;
|
||||||
|
},
|
||||||
|
|
||||||
|
updateReportStatus: async (
|
||||||
|
reportId: string,
|
||||||
|
status: ReportStatus,
|
||||||
|
): Promise<void> => {
|
||||||
|
await api.patch(`/reports/${reportId}/status`, { status });
|
||||||
|
},
|
||||||
|
|
||||||
|
deleteUser: async (userId: string): Promise<void> => {
|
||||||
|
await api.delete(`/users/${userId}`);
|
||||||
|
},
|
||||||
|
|
||||||
|
updateUser: async (userId: string, data: Partial<User>): Promise<void> => {
|
||||||
|
await api.patch(`/users/admin/${userId}`, data);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import api from "@/lib/api";
|
import api from "@/lib/api";
|
||||||
import type { LoginResponse, RegisterPayload } from "@/types/auth";
|
import type {
|
||||||
|
LoginResponse,
|
||||||
|
RegisterPayload,
|
||||||
|
TwoFactorSetupResponse,
|
||||||
|
} from "@/types/auth";
|
||||||
|
|
||||||
export const AuthService = {
|
export const AuthService = {
|
||||||
async login(email: string, password: string): Promise<LoginResponse> {
|
async login(email: string, password: string): Promise<LoginResponse> {
|
||||||
@@ -10,6 +14,14 @@ export const AuthService = {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async verify2fa(userId: string, token: string): Promise<LoginResponse> {
|
||||||
|
const { data } = await api.post<LoginResponse>("/auth/verify-2fa", {
|
||||||
|
userId,
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
async register(payload: RegisterPayload): Promise<void> {
|
async register(payload: RegisterPayload): Promise<void> {
|
||||||
await api.post("/auth/register", payload);
|
await api.post("/auth/register", payload);
|
||||||
},
|
},
|
||||||
@@ -21,4 +33,19 @@ export const AuthService = {
|
|||||||
async refresh(): Promise<void> {
|
async refresh(): Promise<void> {
|
||||||
await api.post("/auth/refresh");
|
await api.post("/auth/refresh");
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async setup2fa(): Promise<TwoFactorSetupResponse> {
|
||||||
|
const { data } = await api.post<TwoFactorSetupResponse>(
|
||||||
|
"/users/me/2fa/setup",
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async enable2fa(token: string): Promise<void> {
|
||||||
|
await api.post("/users/me/2fa/enable", { token });
|
||||||
|
},
|
||||||
|
|
||||||
|
async disable2fa(token: string): Promise<void> {
|
||||||
|
await api.post("/users/me/2fa/disable", { token });
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
48
frontend/src/services/comment.service.ts
Normal file
48
frontend/src/services/comment.service.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import api from "@/lib/api";
|
||||||
|
|
||||||
|
export interface Comment {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
parentId?: string;
|
||||||
|
likesCount: number;
|
||||||
|
isLiked: boolean;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
user: {
|
||||||
|
uuid: string;
|
||||||
|
username: string;
|
||||||
|
displayName?: string;
|
||||||
|
avatarUrl?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CommentService = {
|
||||||
|
async getByContentId(contentId: string): Promise<Comment[]> {
|
||||||
|
const { data } = await api.get<Comment[]>(`/contents/${contentId}/comments`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async create(
|
||||||
|
contentId: string,
|
||||||
|
text: string,
|
||||||
|
parentId?: string,
|
||||||
|
): Promise<Comment> {
|
||||||
|
const { data } = await api.post<Comment>(`/contents/${contentId}/comments`, {
|
||||||
|
text,
|
||||||
|
parentId,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async remove(commentId: string): Promise<void> {
|
||||||
|
await api.delete(`/comments/${commentId}`);
|
||||||
|
},
|
||||||
|
|
||||||
|
async like(commentId: string): Promise<void> {
|
||||||
|
await api.post(`/comments/${commentId}/like`);
|
||||||
|
},
|
||||||
|
|
||||||
|
async unlike(commentId: string): Promise<void> {
|
||||||
|
await api.delete(`/comments/${commentId}/like`);
|
||||||
|
},
|
||||||
|
};
|
||||||
62
frontend/src/services/message.service.ts
Normal file
62
frontend/src/services/message.service.ts
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
import api from "@/lib/api";
|
||||||
|
|
||||||
|
export interface Conversation {
|
||||||
|
id: string;
|
||||||
|
updatedAt: string;
|
||||||
|
lastMessage?: {
|
||||||
|
text: string;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
recipient: {
|
||||||
|
uuid: string;
|
||||||
|
username: string;
|
||||||
|
displayName?: string;
|
||||||
|
avatarUrl?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Message {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
createdAt: string;
|
||||||
|
senderId: string;
|
||||||
|
readAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const MessageService = {
|
||||||
|
async getConversations(): Promise<Conversation[]> {
|
||||||
|
const { data } = await api.get<Conversation[]>("/messages/conversations");
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async getUnreadCount(): Promise<number> {
|
||||||
|
const { data } = await api.get<number>("/messages/unread-count");
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async getMessages(conversationId: string): Promise<Message[]> {
|
||||||
|
const { data } = await api.get<Message[]>(
|
||||||
|
`/messages/conversations/${conversationId}`,
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async getConversationWith(userId: string): Promise<Conversation | null> {
|
||||||
|
const { data } = await api.get<Conversation | null>(
|
||||||
|
`/messages/conversations/with/${userId}`,
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async sendMessage(recipientId: string, text: string): Promise<Message> {
|
||||||
|
const { data } = await api.post<Message>("/messages", {
|
||||||
|
recipientId,
|
||||||
|
text,
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async markAsRead(conversationId: string): Promise<void> {
|
||||||
|
await api.patch(`/messages/conversations/${conversationId}/read`);
|
||||||
|
},
|
||||||
|
};
|
||||||
40
frontend/src/services/report.service.ts
Normal file
40
frontend/src/services/report.service.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import api from "@/lib/api";
|
||||||
|
|
||||||
|
export enum ReportReason {
|
||||||
|
INAPPROPRIATE = "inappropriate",
|
||||||
|
SPAM = "spam",
|
||||||
|
COPYRIGHT = "copyright",
|
||||||
|
OTHER = "other",
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum ReportStatus {
|
||||||
|
PENDING = "pending",
|
||||||
|
REVIEWED = "reviewed",
|
||||||
|
RESOLVED = "resolved",
|
||||||
|
DISMISSED = "dismissed",
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateReportPayload {
|
||||||
|
contentId?: string;
|
||||||
|
tagId?: string;
|
||||||
|
reason: ReportReason;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Report {
|
||||||
|
uuid: string;
|
||||||
|
reporterId: string;
|
||||||
|
contentId?: string;
|
||||||
|
tagId?: string;
|
||||||
|
reason: ReportReason;
|
||||||
|
description?: string;
|
||||||
|
status: ReportStatus;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ReportService = {
|
||||||
|
async create(payload: CreateReportPayload): Promise<void> {
|
||||||
|
await api.post("/reports", payload);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -12,6 +12,13 @@ export const UserService = {
|
|||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async search(query: string): Promise<User[]> {
|
||||||
|
const { data } = await api.get<User[]>("/users/search", {
|
||||||
|
params: { q: query },
|
||||||
|
});
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
async updateMe(update: Partial<User>): Promise<User> {
|
async updateMe(update: Partial<User>): Promise<User> {
|
||||||
const { data } = await api.patch<User>("/users/me", update);
|
const { data } = await api.patch<User>("/users/me", update);
|
||||||
return data;
|
return data;
|
||||||
@@ -53,4 +60,9 @@ export const UserService = {
|
|||||||
});
|
});
|
||||||
return data;
|
return data;
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async exportData(): Promise<Record<string, unknown>> {
|
||||||
|
const { data } = await api.get<Record<string, unknown>>("/users/me/export");
|
||||||
|
return data;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
export interface LoginResponse {
|
export interface LoginResponse {
|
||||||
message: string;
|
message: string;
|
||||||
userId: string;
|
userId?: string;
|
||||||
|
access_token?: string;
|
||||||
|
refresh_token?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RegisterPayload {
|
export interface RegisterPayload {
|
||||||
@@ -17,6 +19,12 @@ export interface AuthStatus {
|
|||||||
username: string;
|
username: string;
|
||||||
displayName?: string;
|
displayName?: string;
|
||||||
avatarUrl?: string;
|
avatarUrl?: string;
|
||||||
|
role?: string;
|
||||||
};
|
};
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface TwoFactorSetupResponse {
|
||||||
|
qrCodeUrl: string;
|
||||||
|
secret: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ export interface User {
|
|||||||
bio?: string;
|
bio?: string;
|
||||||
role?: "user" | "admin" | "moderator";
|
role?: "user" | "admin" | "moderator";
|
||||||
status?: "active" | "verification" | "suspended" | "pending" | "deleted";
|
status?: "active" | "verification" | "suspended" | "pending" | "deleted";
|
||||||
|
twoFactorEnabled?: boolean;
|
||||||
|
showOnlineStatus?: boolean;
|
||||||
|
showReadReceipts?: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@memegoat/source",
|
"name": "@memegoat/source",
|
||||||
"version": "1.7.0",
|
"version": "1.9.5",
|
||||||
"description": "",
|
"description": "",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"version:get": "cmake -P version.cmake GET",
|
"version:get": "cmake -P version.cmake GET",
|
||||||
|
|||||||
21079
pnpm-lock.yaml
generated
21079
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user