feat: implement user account management features including profile display and password change functionality

This commit is contained in:
Julien Froidefond
2025-10-16 22:27:06 +02:00
parent 3cd58f63e6
commit 83f523c11a
11 changed files with 501 additions and 1 deletions

34
src/app/account/page.tsx Normal file
View File

@@ -0,0 +1,34 @@
import { UserProfileCard } from "@/components/account/UserProfileCard";
import { ChangePasswordForm } from "@/components/account/ChangePasswordForm";
import { UserService } from "@/lib/services/user.service";
import { redirect } from "next/navigation";
export default async function AccountPage() {
try {
const [profile, stats] = await Promise.all([
UserService.getUserProfile(),
UserService.getUserStats(),
]);
return (
<div className="container mx-auto px-4 py-8">
<div className="max-w-4xl mx-auto space-y-8">
<div>
<h1 className="text-3xl font-bold">Mon compte</h1>
<p className="text-muted-foreground mt-2">
Gérez vos informations personnelles et votre sécurité
</p>
</div>
<div className="grid gap-6 md:grid-cols-2">
<UserProfileCard profile={{ ...profile, stats }} />
<ChangePasswordForm />
</div>
</div>
</div>
);
} catch (error) {
console.error("Erreur lors du chargement du compte:", error);
redirect("/login");
}
}

View File

@@ -0,0 +1,49 @@
import { NextRequest, NextResponse } from "next/server";
import { UserService } from "@/lib/services/user.service";
import { AppError } from "@/utils/errors";
import { AuthServerService } from "@/lib/services/auth-server.service";
export async function PUT(request: NextRequest) {
try {
const body = await request.json();
const { currentPassword, newPassword } = body;
if (!currentPassword || !newPassword) {
return NextResponse.json(
{ error: "Mots de passe manquants" },
{ status: 400 }
);
}
// Vérifier que le nouveau mot de passe est fort
if (!AuthServerService.isPasswordStrong(newPassword)) {
return NextResponse.json(
{
error: "Le nouveau mot de passe doit contenir au moins 8 caractères, une majuscule et un chiffre"
},
{ status: 400 }
);
}
await UserService.changePassword(currentPassword, newPassword);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Erreur lors du changement de mot de passe:", error);
if (error instanceof AppError) {
return NextResponse.json(
{ error: error.message, code: error.code },
{
status: error.code === "AUTH_INVALID_PASSWORD" ? 400 :
error.code === "AUTH_UNAUTHENTICATED" ? 401 : 500
}
);
}
return NextResponse.json(
{ error: "Erreur lors du changement de mot de passe" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,28 @@
import { NextResponse } from "next/server";
import { UserService } from "@/lib/services/user.service";
import { AppError } from "@/utils/errors";
export async function GET() {
try {
const [profile, stats] = await Promise.all([
UserService.getUserProfile(),
UserService.getUserStats(),
]);
return NextResponse.json({ ...profile, stats });
} catch (error) {
console.error("Erreur lors de la récupération du profil:", error);
if (error instanceof AppError) {
return NextResponse.json(
{ error: error.message, code: error.code },
{ status: error.code === "AUTH_UNAUTHENTICATED" ? 401 : 500 }
);
}
return NextResponse.json(
{ error: "Erreur lors de la récupération du profil" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,139 @@
"use client";
import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import { Lock } from "lucide-react";
export function ChangePasswordForm() {
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const { toast } = useToast();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (newPassword !== confirmPassword) {
toast({
variant: "destructive",
title: "Erreur",
description: "Les mots de passe ne correspondent pas",
});
return;
}
if (newPassword.length < 8) {
toast({
variant: "destructive",
title: "Erreur",
description: "Le mot de passe doit contenir au moins 8 caractères",
});
return;
}
setIsLoading(true);
try {
const response = await fetch("/api/user/password", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ currentPassword, newPassword }),
});
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors du changement de mot de passe");
}
toast({
title: "Succès",
description: "Votre mot de passe a été modifié avec succès",
});
// Reset form
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
} catch (error) {
toast({
variant: "destructive",
title: "Erreur",
description: error instanceof Error ? error.message : "Une erreur est survenue",
});
} finally {
setIsLoading(false);
}
};
return (
<Card>
<CardHeader>
<CardTitle>Changer le mot de passe</CardTitle>
<CardDescription>
Assurez-vous d&apos;utiliser un mot de passe fort (8 caractères minimum, une majuscule et un chiffre)
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="currentPassword">Mot de passe actuel</Label>
<div className="relative">
<Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="currentPassword"
type="password"
value={currentPassword}
onChange={(e) => setCurrentPassword(e.target.value)}
className="pl-9"
required
disabled={isLoading}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="newPassword">Nouveau mot de passe</Label>
<div className="relative">
<Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="newPassword"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="pl-9"
required
disabled={isLoading}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirmer le mot de passe</Label>
<div className="relative">
<Lock className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
<Input
id="confirmPassword"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="pl-9"
required
disabled={isLoading}
/>
</div>
</div>
<Button type="submit" disabled={isLoading}>
{isLoading ? "Modification..." : "Changer le mot de passe"}
</Button>
</form>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,76 @@
"use client";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Mail, Calendar, Shield, Heart } from "lucide-react";
import type { UserProfile } from "@/lib/services/user.service";
interface UserProfileCardProps {
profile: UserProfile & { stats: { favoritesCount: number; hasPreferences: boolean; hasKomgaConfig: boolean } };
}
export function UserProfileCard({ profile }: UserProfileCardProps) {
return (
<Card>
<CardHeader>
<CardTitle>Informations du compte</CardTitle>
<CardDescription>Vos informations personnelles</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center gap-3">
<Mail className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Email</p>
<p className="text-sm text-muted-foreground">{profile.email}</p>
</div>
</div>
<div className="flex items-center gap-3">
<Shield className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Rôles</p>
<div className="flex gap-2 mt-1">
{profile.roles.map((role) => (
<Badge key={role} variant="secondary">
{role.replace("ROLE_", "")}
</Badge>
))}
</div>
</div>
</div>
<div className="flex items-center gap-3">
<Calendar className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Membre depuis</p>
<p className="text-sm text-muted-foreground">
{new Date(profile.createdAt).toLocaleDateString("fr-FR", {
year: "numeric",
month: "long",
day: "numeric",
})}
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Heart className="h-5 w-5 text-muted-foreground" />
<div>
<p className="text-sm font-medium">Favoris</p>
<p className="text-sm text-muted-foreground">
{profile.stats.favoritesCount} séries favorites
</p>
</div>
</div>
<div className="pt-4 border-t">
<p className="text-xs text-muted-foreground">
Dernière mise à jour:{" "}
{new Date(profile.updatedAt).toLocaleDateString("fr-FR")}
</p>
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,6 +1,6 @@
"use client";
import { Home, Library, Settings, LogOut, RefreshCw, Star, Download } from "lucide-react";
import { Home, Library, Settings, LogOut, RefreshCw, Star, Download, User } from "lucide-react";
import { usePathname, useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { signOut } from "next-auth/react";
@@ -274,6 +274,16 @@ export function Sidebar({ isOpen, onClose, initialLibraries, initialFavorites }:
<h2 className="mb-2 px-4 text-lg font-semibold tracking-tight">
{t("sidebar.settings.title")}
</h2>
<button
onClick={() => handleLinkClick("/account")}
className={cn(
"w-full flex items-center rounded-lg px-3 py-2 text-sm font-medium hover:bg-accent hover:text-accent-foreground",
pathname === "/account" ? "bg-accent" : "transparent"
)}
>
<User className="mr-2 h-4 w-4" />
{t("sidebar.account")}
</button>
<button
onClick={() => handleLinkClick("/settings")}
className={cn(

View File

@@ -0,0 +1,36 @@
import * as React from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };

View File

@@ -14,6 +14,10 @@ export const ERROR_CODES = {
INVALID_USER_DATA: "AUTH_INVALID_USER_DATA",
LOGOUT_ERROR: "AUTH_LOGOUT_ERROR",
REGISTRATION_FAILED: "AUTH_REGISTRATION_FAILED",
USER_NOT_FOUND: "AUTH_USER_NOT_FOUND",
INVALID_PASSWORD: "AUTH_INVALID_PASSWORD",
PASSWORD_CHANGE_ERROR: "AUTH_PASSWORD_CHANGE_ERROR",
FETCH_ERROR: "AUTH_FETCH_ERROR",
},
KOMGA: {
MISSING_CONFIG: "KOMGA_MISSING_CONFIG",

View File

@@ -46,6 +46,7 @@
"navigation": "Navigation",
"home": "Home",
"downloads": "Downloads",
"account": "My Account",
"favorites": {
"title": "Favorites",
"empty": "No favorites",

View File

@@ -46,6 +46,7 @@
"navigation": "Navigation",
"home": "Accueil",
"downloads": "Téléchargements",
"account": "Mon compte",
"favorites": {
"title": "Favoris",
"empty": "Aucun favori",

View File

@@ -0,0 +1,122 @@
import prisma from "@/lib/prisma";
import { getCurrentUser } from "../auth-utils";
import { ERROR_CODES } from "../../constants/errorCodes";
import { AppError } from "../../utils/errors";
import bcrypt from "bcryptjs";
export interface UserProfile {
id: string;
email: string;
roles: string[];
createdAt: Date;
updatedAt: Date;
}
export class UserService {
private static readonly SALT_ROUNDS = 10;
static async getUserProfile(): Promise<UserProfile> {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
throw new AppError(ERROR_CODES.AUTH.UNAUTHENTICATED);
}
const user = await prisma.user.findUnique({
where: { id: currentUser.id },
select: {
id: true,
email: true,
roles: true,
createdAt: true,
updatedAt: true,
},
});
if (!user) {
throw new AppError(ERROR_CODES.AUTH.USER_NOT_FOUND);
}
return user;
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(ERROR_CODES.AUTH.FETCH_ERROR, {}, error);
}
}
static async changePassword(
currentPassword: string,
newPassword: string
): Promise<void> {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
throw new AppError(ERROR_CODES.AUTH.UNAUTHENTICATED);
}
// Récupérer l'utilisateur avec son mot de passe
const user = await prisma.user.findUnique({
where: { id: currentUser.id },
});
if (!user) {
throw new AppError(ERROR_CODES.AUTH.USER_NOT_FOUND);
}
// Vérifier l'ancien mot de passe
const isPasswordValid = await bcrypt.compare(currentPassword, user.password);
if (!isPasswordValid) {
throw new AppError(ERROR_CODES.AUTH.INVALID_PASSWORD);
}
// Hasher le nouveau mot de passe
const hashedPassword = await bcrypt.hash(newPassword, this.SALT_ROUNDS);
// Mettre à jour le mot de passe
await prisma.user.update({
where: { id: currentUser.id },
data: { password: hashedPassword },
});
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(ERROR_CODES.AUTH.PASSWORD_CHANGE_ERROR, {}, error);
}
}
static async getUserStats() {
try {
const currentUser = await getCurrentUser();
if (!currentUser) {
throw new AppError(ERROR_CODES.AUTH.UNAUTHENTICATED);
}
const [favoritesCount, preferences, komgaConfig] = await Promise.all([
prisma.favorite.count({
where: { userId: currentUser.id },
}),
prisma.preferences.findUnique({
where: { userId: currentUser.id },
}),
prisma.komgaConfig.findUnique({
where: { userId: currentUser.id },
}),
]);
return {
favoritesCount,
hasPreferences: !!preferences,
hasKomgaConfig: !!komgaConfig,
};
} catch (error) {
if (error instanceof AppError) {
throw error;
}
throw new AppError(ERROR_CODES.AUTH.FETCH_ERROR, {}, error);
}
}
}