Merge pull request 'Fix of backend validation problems.' (#8) from dev into prod
Some checks failed
Backend Tests / test (push) Has been cancelled
Lint / lint (push) Has been cancelled
Deploy to Production / deploy (push) Successful in 6m41s

Reviewed-on: #8
This commit was merged in pull request #8.
This commit is contained in:
2026-01-14 21:13:06 +01:00
18 changed files with 1966 additions and 41 deletions

View File

@@ -0,0 +1 @@
ALTER TABLE "users" ALTER COLUMN "password_hash" SET DATA TYPE varchar(100);

File diff suppressed because it is too large Load Diff

View File

@@ -36,6 +36,13 @@
"when": 1768417827439,
"tag": "0004_cheerful_dakota_north",
"breakpoints": true
},
{
"idx": 5,
"version": "7",
"when": 1768420201679,
"tag": "0005_perpetual_silverclaw",
"breakpoints": true
}
]
}

View File

@@ -11,6 +11,7 @@ import {
import { AuthGuard } from "../auth/guards/auth.guard";
import type { AuthenticatedRequest } from "../common/interfaces/request.interface";
import { ApiKeysService } from "./api-keys.service";
import { CreateApiKeyDto } from "./dto/create-api-key.dto";
@Controller("api-keys")
@UseGuards(AuthGuard)
@@ -20,13 +21,12 @@ export class ApiKeysController {
@Post()
create(
@Req() req: AuthenticatedRequest,
@Body("name") name: string,
@Body("expiresAt") expiresAt?: string,
@Body() createApiKeyDto: CreateApiKeyDto,
) {
return this.apiKeysService.create(
req.user.sub,
name,
expiresAt ? new Date(expiresAt) : undefined,
createApiKeyDto.name,
createApiKeyDto.expiresAt ? new Date(createApiKeyDto.expiresAt) : undefined,
);
}

View File

@@ -0,0 +1,18 @@
import {
IsDateString,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
} from "class-validator";
export class CreateApiKeyDto {
@IsString()
@IsNotEmpty()
@MaxLength(128)
name!: string;
@IsOptional()
@IsDateString()
expiresAt?: string;
}

View File

@@ -1,5 +1,5 @@
import { CacheModule } from "@nestjs/cache-manager";
import { Module } from "@nestjs/common";
import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { ScheduleModule } from "@nestjs/schedule";
import { ThrottlerModule } from "@nestjs/throttler";
@@ -10,6 +10,7 @@ import { AppService } from "./app.service";
import { AuthModule } from "./auth/auth.module";
import { CategoriesModule } from "./categories/categories.module";
import { CommonModule } from "./common/common.module";
import { CrawlerDetectionMiddleware } from "./common/middlewares/crawler-detection.middleware";
import { validateEnv } from "./config/env.schema";
import { ContentsModule } from "./contents/contents.module";
import { CryptoModule } from "./crypto/crypto.module";
@@ -71,4 +72,8 @@ import { UsersModule } from "./users/users.module";
controllers: [AppController, HealthController],
providers: [AppService],
})
export class AppModule {}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(CrawlerDetectionMiddleware).forRoutes("*");
}
}

View File

@@ -1,15 +1,18 @@
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
import { IsNotEmpty, IsOptional, IsString, MaxLength } from "class-validator";
export class CreateCategoryDto {
@IsString()
@IsNotEmpty()
@MaxLength(64)
name!: string;
@IsOptional()
@IsString()
@MaxLength(255)
description?: string;
@IsOptional()
@IsString()
@MaxLength(512)
iconUrl?: string;
}

View File

@@ -0,0 +1,67 @@
import { Injectable, Logger, NestMiddleware } from "@nestjs/common";
import type { NextFunction, Request, Response } from "express";
@Injectable()
export class CrawlerDetectionMiddleware implements NestMiddleware {
private readonly logger = new Logger("CrawlerDetection");
private readonly SUSPICIOUS_PATTERNS = [
/\.env/,
/wp-admin/,
/wp-login/,
/\.git/,
/\.php$/,
/xmlrpc/,
/config/,
/setup/,
/wp-config/,
/_next/,
/install/,
/admin/,
/phpmyadmin/,
/sql/,
/backup/,
/db\./,
/backup\./,
/cgi-bin/,
/\.well-known\/security\.txt/, // Bien que légitime, souvent scanné
];
private readonly BOT_USER_AGENTS = [
/bot/i,
/crawler/i,
/spider/i,
/python/i,
/curl/i,
/wget/i,
/nmap/i,
/nikto/i,
/zgrab/i,
/masscan/i,
];
use(req: Request, res: Response, next: NextFunction) {
const { method, url, ip } = req;
const userAgent = req.get("user-agent") || "unknown";
res.on("finish", () => {
if (res.statusCode === 404) {
const isSuspiciousPath = this.SUSPICIOUS_PATTERNS.some((pattern) =>
pattern.test(url),
);
const isBotUserAgent = this.BOT_USER_AGENTS.some((pattern) =>
pattern.test(userAgent),
);
if (isSuspiciousPath || isBotUserAgent) {
this.logger.warn(
`Potential crawler detected: [${ip}] ${method} ${url} - User-Agent: ${userAgent}`,
);
// Ici, on pourrait ajouter une logique pour bannir l'IP temporairement via Redis
}
}
});
next();
}
}

View File

@@ -6,6 +6,7 @@ import {
IsOptional,
IsString,
IsUUID,
MaxLength,
} from "class-validator";
export enum ContentType {
@@ -19,14 +20,17 @@ export class CreateContentDto {
@IsString()
@IsNotEmpty()
@MaxLength(255)
title!: string;
@IsString()
@IsNotEmpty()
@MaxLength(512)
storageKey!: string;
@IsString()
@IsNotEmpty()
@MaxLength(128)
mimeType!: string;
@IsInt()
@@ -39,5 +43,6 @@ export class CreateContentDto {
@IsOptional()
@IsArray()
@IsString({ each: true })
@MaxLength(64, { each: true })
tags?: string[];
}

View File

@@ -1,9 +1,11 @@
import {
IsArray,
IsEnum,
IsNotEmpty,
IsOptional,
IsString,
IsUUID,
MaxLength,
} from "class-validator";
import { ContentType } from "./create-content.dto";
@@ -13,6 +15,7 @@ export class UploadContentDto {
@IsString()
@IsNotEmpty()
@MaxLength(255)
title!: string;
@IsOptional()
@@ -20,6 +23,8 @@ export class UploadContentDto {
categoryId?: string;
@IsOptional()
@IsArray()
@IsString({ each: true })
@MaxLength(64, { each: true })
tags?: string[];
}

View File

@@ -29,7 +29,7 @@ export const users = pgTable(
displayName: varchar("display_name", { length: 32 }),
username: varchar("username", { length: 32 }).notNull().unique(),
passwordHash: varchar("password_hash", { length: 95 }).notNull(),
passwordHash: varchar("password_hash", { length: 100 }).notNull(),
// Sécurité
twoFactorSecret: pgpEncrypted("two_factor_secret"),

View File

@@ -1,4 +1,10 @@
import { IsEnum, IsOptional, IsString, IsUUID } from "class-validator";
import {
IsEnum,
IsOptional,
IsString,
IsUUID,
MaxLength,
} from "class-validator";
export enum ReportReason {
INAPPROPRIATE = "inappropriate",
@@ -21,5 +27,6 @@ export class CreateReportDto {
@IsOptional()
@IsString()
@MaxLength(1000)
description?: string;
}

View File

@@ -1,11 +1,13 @@
import { IsNotEmpty, IsString } from "class-validator";
import { IsNotEmpty, IsString, MaxLength } from "class-validator";
export class UpdateConsentDto {
@IsString()
@IsNotEmpty()
@MaxLength(16)
termsVersion!: string;
@IsString()
@IsNotEmpty()
@MaxLength(16)
privacyVersion!: string;
}

View File

@@ -7,6 +7,7 @@ import {
SidebarProvider,
SidebarTrigger,
} from "@/components/ui/sidebar";
import { UserNavMobile } from "@/components/user-nav-mobile";
export default function DashboardLayout({
children,
@@ -16,26 +17,31 @@ export default function DashboardLayout({
modal: React.ReactNode;
}) {
return (
<SidebarProvider>
<AppSidebar />
<SidebarInset className="flex flex-row overflow-hidden">
<div className="flex-1 flex flex-col min-w-0">
<header className="flex h-16 shrink-0 items-center gap-2 border-b px-4 lg:hidden">
<SidebarTrigger />
<div className="flex-1" />
</header>
<main className="flex-1 overflow-y-auto bg-zinc-50 dark:bg-zinc-950">
{children}
{modal}
</main>
<React.Suspense fallback={null}>
<SidebarProvider>
<AppSidebar />
<SidebarInset className="flex flex-row overflow-hidden">
<div className="flex-1 flex flex-col min-w-0">
<header className="flex h-16 shrink-0 items-center gap-2 border-b px-4 lg:hidden sticky top-0 bg-background z-40">
<SidebarTrigger />
<div className="flex-1 flex justify-center">
<span className="font-bold text-primary text-lg">MemeGoat</span>
</div>
<UserNavMobile />
</header>
<main className="flex-1 overflow-y-auto bg-zinc-50 dark:bg-zinc-950">
{children}
{modal}
</main>
<React.Suspense fallback={null}>
<MobileFilters />
</React.Suspense>
</div>
<React.Suspense fallback={null}>
<MobileFilters />
<SearchSidebar />
</React.Suspense>
</div>
<React.Suspense fallback={null}>
<SearchSidebar />
</React.Suspense>
</SidebarInset>
</SidebarProvider>
</SidebarInset>
</SidebarProvider>
</React.Suspense>
);
}

View File

@@ -1,12 +1,20 @@
"use client";
import { Calendar, LogOut, Settings } from "lucide-react";
import { Calendar, LogIn, LogOut, Settings } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";
import { useSearchParams } from "next/navigation";
import * as React from "react";
import { ContentList } from "@/components/content-list";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Spinner } from "@/components/ui/spinner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useAuth } from "@/providers/auth-provider";
import { ContentService } from "@/services/content.service";
@@ -14,6 +22,8 @@ import { FavoriteService } from "@/services/favorite.service";
export default function ProfilePage() {
const { user, isAuthenticated, isLoading, logout } = useAuth();
const searchParams = useSearchParams();
const tab = searchParams.get("tab") || "memes";
const fetchMyMemes = React.useCallback(
(params: { limit: number; offset: number }) =>
@@ -26,9 +36,36 @@ export default function ProfilePage() {
[],
);
if (isLoading) return null;
if (isLoading) {
return (
<div className="flex h-[400px] items-center justify-center">
<Spinner className="h-8 w-8 text-primary" />
</div>
);
}
if (!isAuthenticated || !user) {
redirect("/login");
return (
<div className="max-w-2xl mx-auto py-8 px-4 text-center">
<Card className="p-12">
<CardHeader>
<div className="mx-auto bg-primary/10 p-4 rounded-full w-fit mb-4">
<LogIn className="h-8 w-8 text-primary" />
</div>
<CardTitle>Profil inaccessible</CardTitle>
<CardDescription>
Vous devez être connecté pour voir votre profil, vos mèmes et vos
favoris.
</CardDescription>
</CardHeader>
<CardContent>
<Button asChild className="w-full sm:w-auto">
<Link href="/login">Se connecter</Link>
</Button>
</CardContent>
</Card>
</div>
);
}
return (
@@ -79,10 +116,14 @@ export default function ProfilePage() {
</div>
</div>
<Tabs defaultValue="memes" className="w-full">
<Tabs value={tab} className="w-full">
<TabsList className="grid w-full grid-cols-2 mb-8">
<TabsTrigger value="memes">Mes Mèmes</TabsTrigger>
<TabsTrigger value="favorites">Mes Favoris</TabsTrigger>
<TabsTrigger value="memes" asChild>
<Link href="/profile?tab=memes">Mes Mèmes</Link>
</TabsTrigger>
<TabsTrigger value="favorites" asChild>
<Link href="/profile?tab=favorites">Mes Favoris</Link>
</TabsTrigger>
</TabsList>
<TabsContent value="memes">
<ContentList fetchFn={fetchMyMemes} />

View File

@@ -1,15 +1,22 @@
"use client";
import { zodResolver } from "@hookform/resolvers/zod";
import { Image as ImageIcon, Loader2, Upload, X } from "lucide-react";
import { Image as ImageIcon, Loader2, LogIn, Upload, X } from "lucide-react";
import NextImage from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import * as React from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
Form,
FormControl,
@@ -27,6 +34,8 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { useAuth } from "@/providers/auth-provider";
import { CategoryService } from "@/services/category.service";
import { ContentService } from "@/services/content.service";
import type { Category } from "@/types/content";
@@ -42,6 +51,7 @@ type UploadFormValues = z.infer<typeof uploadSchema>;
export default function UploadPage() {
const router = useRouter();
const { isAuthenticated, isLoading } = useAuth();
const [categories, setCategories] = React.useState<Category[]>([]);
const [file, setFile] = React.useState<File | null>(null);
const [preview, setPreview] = React.useState<string | null>(null);
@@ -57,8 +67,42 @@ export default function UploadPage() {
});
React.useEffect(() => {
CategoryService.getAll().then(setCategories).catch(console.error);
}, []);
if (isAuthenticated) {
CategoryService.getAll().then(setCategories).catch(console.error);
}
}, [isAuthenticated]);
if (isLoading) {
return (
<div className="flex h-[400px] items-center justify-center">
<Spinner className="h-8 w-8 text-primary" />
</div>
);
}
if (!isAuthenticated) {
return (
<div className="max-w-2xl mx-auto py-8 px-4">
<Card className="text-center p-12">
<CardHeader>
<div className="mx-auto bg-primary/10 p-4 rounded-full w-fit mb-4">
<LogIn className="h-8 w-8 text-primary" />
</div>
<CardTitle>Connexion requise</CardTitle>
<CardDescription>
Vous devez être connecté pour partager vos meilleurs mèmes avec la
communauté.
</CardDescription>
</CardHeader>
<CardContent>
<Button asChild className="w-full sm:w-auto">
<Link href="/login">Se connecter</Link>
</Button>
</CardContent>
</Card>
</div>
);
}
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0];

View File

@@ -3,7 +3,9 @@
import {
ChevronRight,
Clock,
Heart,
HelpCircle,
History,
Home,
LayoutGrid,
LogIn,
@@ -14,7 +16,7 @@ import {
User as UserIcon,
} from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { usePathname, useSearchParams } from "next/navigation";
import * as React from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
@@ -68,6 +70,7 @@ const mainNav = [
export function AppSidebar() {
const pathname = usePathname();
const searchParams = useSearchParams();
const { user, logout, isAuthenticated } = useAuth();
const [categories, setCategories] = React.useState<Category[]>([]);
@@ -149,6 +152,40 @@ export function AppSidebar() {
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
<SidebarGroup>
<SidebarGroupLabel>Ma Bibliothèque</SidebarGroupLabel>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={
pathname === "/profile" && searchParams.get("tab") === "favorites"
}
tooltip="Mes Favoris"
>
<Link href="/profile?tab=favorites">
<Heart />
<span>Mes Favoris</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton
asChild
isActive={
pathname === "/profile" && searchParams.get("tab") === "memes"
}
tooltip="Mes Mèmes"
>
<Link href="/profile?tab=memes">
<History />
<span>Mes Mèmes</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroup>
</SidebarContent>
<SidebarFooter>
<SidebarMenu>

View File

@@ -0,0 +1,37 @@
"use client";
import { LogIn, User as UserIcon } from "lucide-react";
import Link from "next/link";
import * as React from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/providers/auth-provider";
export function UserNavMobile() {
const { user, isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return <div className="h-8 w-8 rounded-full bg-zinc-200 animate-pulse" />;
}
if (!isAuthenticated || !user) {
return (
<Button variant="ghost" size="icon" asChild className="h-9 w-9">
<Link href="/login">
<LogIn className="h-5 w-5" />
</Link>
</Button>
);
}
return (
<Button variant="ghost" size="icon" asChild className="h-9 w-9 p-0">
<Link href="/profile">
<Avatar className="h-8 w-8 border">
<AvatarImage src={user.avatarUrl} alt={user.username} />
<AvatarFallback>{user.username.slice(0, 2).toUpperCase()}</AvatarFallback>
</Avatar>
</Link>
</Button>
);
}