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, "when": 1768417827439,
"tag": "0004_cheerful_dakota_north", "tag": "0004_cheerful_dakota_north",
"breakpoints": true "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 { AuthGuard } from "../auth/guards/auth.guard";
import type { AuthenticatedRequest } from "../common/interfaces/request.interface"; import type { AuthenticatedRequest } from "../common/interfaces/request.interface";
import { ApiKeysService } from "./api-keys.service"; import { ApiKeysService } from "./api-keys.service";
import { CreateApiKeyDto } from "./dto/create-api-key.dto";
@Controller("api-keys") @Controller("api-keys")
@UseGuards(AuthGuard) @UseGuards(AuthGuard)
@@ -20,13 +21,12 @@ export class ApiKeysController {
@Post() @Post()
create( create(
@Req() req: AuthenticatedRequest, @Req() req: AuthenticatedRequest,
@Body("name") name: string, @Body() createApiKeyDto: CreateApiKeyDto,
@Body("expiresAt") expiresAt?: string,
) { ) {
return this.apiKeysService.create( return this.apiKeysService.create(
req.user.sub, req.user.sub,
name, createApiKeyDto.name,
expiresAt ? new Date(expiresAt) : undefined, 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 { CacheModule } from "@nestjs/cache-manager";
import { Module } from "@nestjs/common"; import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config"; import { ConfigModule, ConfigService } from "@nestjs/config";
import { ScheduleModule } from "@nestjs/schedule"; import { ScheduleModule } from "@nestjs/schedule";
import { ThrottlerModule } from "@nestjs/throttler"; import { ThrottlerModule } from "@nestjs/throttler";
@@ -10,6 +10,7 @@ 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 { CommonModule } from "./common/common.module"; import { CommonModule } from "./common/common.module";
import { CrawlerDetectionMiddleware } from "./common/middlewares/crawler-detection.middleware";
import { validateEnv } from "./config/env.schema"; import { validateEnv } from "./config/env.schema";
import { ContentsModule } from "./contents/contents.module"; import { ContentsModule } from "./contents/contents.module";
import { CryptoModule } from "./crypto/crypto.module"; import { CryptoModule } from "./crypto/crypto.module";
@@ -71,4 +72,8 @@ import { UsersModule } from "./users/users.module";
controllers: [AppController, HealthController], controllers: [AppController, HealthController],
providers: [AppService], 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 { export class CreateCategoryDto {
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@MaxLength(64)
name!: string; name!: string;
@IsOptional() @IsOptional()
@IsString() @IsString()
@MaxLength(255)
description?: string; description?: string;
@IsOptional() @IsOptional()
@IsString() @IsString()
@MaxLength(512)
iconUrl?: string; 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, IsOptional,
IsString, IsString,
IsUUID, IsUUID,
MaxLength,
} from "class-validator"; } from "class-validator";
export enum ContentType { export enum ContentType {
@@ -19,14 +20,17 @@ export class CreateContentDto {
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@MaxLength(255)
title!: string; title!: string;
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@MaxLength(512)
storageKey!: string; storageKey!: string;
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
@MaxLength(128)
mimeType!: string; mimeType!: string;
@IsInt() @IsInt()
@@ -39,5 +43,6 @@ export class CreateContentDto {
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@IsString({ each: true }) @IsString({ each: true })
@MaxLength(64, { each: true })
tags?: string[]; tags?: string[];
} }

View File

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

View File

@@ -29,7 +29,7 @@ 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: 95 }).notNull(), passwordHash: varchar("password_hash", { length: 100 }).notNull(),
// Sécurité // Sécurité
twoFactorSecret: pgpEncrypted("two_factor_secret"), 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 { export enum ReportReason {
INAPPROPRIATE = "inappropriate", INAPPROPRIATE = "inappropriate",
@@ -21,5 +27,6 @@ export class CreateReportDto {
@IsOptional() @IsOptional()
@IsString() @IsString()
@MaxLength(1000)
description?: string; description?: string;
} }

View File

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

View File

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

View File

@@ -1,12 +1,20 @@
"use client"; "use client";
import { Calendar, LogOut, Settings } from "lucide-react"; import { Calendar, LogIn, LogOut, Settings } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { redirect } from "next/navigation"; import { useSearchParams } from "next/navigation";
import * as React from "react"; import * as React from "react";
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 {
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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useAuth } from "@/providers/auth-provider"; import { useAuth } from "@/providers/auth-provider";
import { ContentService } from "@/services/content.service"; import { ContentService } from "@/services/content.service";
@@ -14,6 +22,8 @@ import { FavoriteService } from "@/services/favorite.service";
export default function ProfilePage() { export default function ProfilePage() {
const { user, isAuthenticated, isLoading, logout } = useAuth(); const { user, isAuthenticated, isLoading, logout } = useAuth();
const searchParams = useSearchParams();
const tab = searchParams.get("tab") || "memes";
const fetchMyMemes = React.useCallback( const fetchMyMemes = React.useCallback(
(params: { limit: number; offset: number }) => (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) { 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 ( return (
@@ -79,10 +116,14 @@ export default function ProfilePage() {
</div> </div>
</div> </div>
<Tabs defaultValue="memes" className="w-full"> <Tabs value={tab} className="w-full">
<TabsList className="grid w-full grid-cols-2 mb-8"> <TabsList className="grid w-full grid-cols-2 mb-8">
<TabsTrigger value="memes">Mes Mèmes</TabsTrigger> <TabsTrigger value="memes" asChild>
<TabsTrigger value="favorites">Mes Favoris</TabsTrigger> <Link href="/profile?tab=memes">Mes Mèmes</Link>
</TabsTrigger>
<TabsTrigger value="favorites" asChild>
<Link href="/profile?tab=favorites">Mes Favoris</Link>
</TabsTrigger>
</TabsList> </TabsList>
<TabsContent value="memes"> <TabsContent value="memes">
<ContentList fetchFn={fetchMyMemes} /> <ContentList fetchFn={fetchMyMemes} />

View File

@@ -1,15 +1,22 @@
"use client"; "use client";
import { zodResolver } from "@hookform/resolvers/zod"; 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 NextImage from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import * as React from "react"; 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 { Button } from "@/components/ui/button"; 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 { import {
Form, Form,
FormControl, FormControl,
@@ -27,6 +34,8 @@ import {
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import { useAuth } from "@/providers/auth-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";
@@ -42,6 +51,7 @@ 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 [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);
@@ -57,8 +67,42 @@ export default function UploadPage() {
}); });
React.useEffect(() => { 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 handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = e.target.files?.[0]; const selectedFile = e.target.files?.[0];

View File

@@ -3,7 +3,9 @@
import { import {
ChevronRight, ChevronRight,
Clock, Clock,
Heart,
HelpCircle, HelpCircle,
History,
Home, Home,
LayoutGrid, LayoutGrid,
LogIn, LogIn,
@@ -14,7 +16,7 @@ import {
User as UserIcon, User as UserIcon,
} from "lucide-react"; } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { usePathname } from "next/navigation"; import { usePathname, useSearchParams } from "next/navigation";
import * as React from "react"; import * as React from "react";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { import {
@@ -68,6 +70,7 @@ const mainNav = [
export function AppSidebar() { export function AppSidebar() {
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams();
const { user, logout, isAuthenticated } = useAuth(); const { user, logout, isAuthenticated } = useAuth();
const [categories, setCategories] = React.useState<Category[]>([]); const [categories, setCategories] = React.useState<Category[]>([]);
@@ -149,6 +152,40 @@ export function AppSidebar() {
</SidebarMenuItem> </SidebarMenuItem>
</SidebarMenu> </SidebarMenu>
</SidebarGroup> </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> </SidebarContent>
<SidebarFooter> <SidebarFooter>
<SidebarMenu> <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>
);
}