Enhance user registration and profile management: Update registration API to include bio, character class, and avatar fields. Implement validation for character class and improve error messages. Refactor registration page to support multi-step form with avatar upload and additional profile customization options, enhancing user experience during account creation.

This commit is contained in:
Julien Froidefond
2025-12-10 05:54:06 +01:00
parent 95e580aff6
commit 125e9b345d
5 changed files with 688 additions and 99 deletions

View File

@@ -88,7 +88,7 @@ export async function PUT(request: Request) {
}
// Validation bio
if (bio !== undefined) {
if (bio !== undefined && bio !== null) {
if (typeof bio !== "string") {
return NextResponse.json(
{ error: "La bio doit être une chaîne de caractères" },

View File

@@ -0,0 +1,63 @@
import { NextResponse } from "next/server";
import { writeFile, mkdir } from "fs/promises";
import { join } from "path";
import { existsSync } from "fs";
export async function POST(request: Request) {
try {
const formData = await request.formData();
const file = formData.get("file") as File;
if (!file) {
return NextResponse.json(
{ error: "Aucun fichier fourni" },
{ status: 400 }
);
}
// Vérifier le type de fichier
if (!file.type.startsWith("image/")) {
return NextResponse.json(
{ error: "Le fichier doit être une image" },
{ status: 400 }
);
}
// Limiter la taille (par exemple 5MB)
const maxSize = 5 * 1024 * 1024; // 5MB
if (file.size > maxSize) {
return NextResponse.json(
{ error: "L'image est trop grande (max 5MB)" },
{ status: 400 }
);
}
// Créer le dossier uploads s'il n'existe pas
const uploadsDir = join(process.cwd(), "public", "uploads");
if (!existsSync(uploadsDir)) {
await mkdir(uploadsDir, { recursive: true });
}
// Générer un nom de fichier unique avec timestamp
const timestamp = Date.now();
const randomId = Math.random().toString(36).substring(2, 9);
const filename = `avatar-register-${timestamp}-${randomId}-${file.name}`;
const filepath = join(uploadsDir, filename);
// Convertir le fichier en buffer et l'écrire
const bytes = await file.arrayBuffer();
const buffer = Buffer.from(bytes);
await writeFile(filepath, buffer);
// Retourner l'URL de l'image
const imageUrl = `/uploads/${filename}`;
return NextResponse.json({ url: imageUrl });
} catch (error) {
console.error("Error uploading avatar:", error);
return NextResponse.json(
{ error: "Erreur lors de l'upload de l'avatar" },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,161 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { CharacterClass } from "@/prisma/generated/prisma/enums";
export async function POST(request: Request) {
try {
const body = await request.json();
const { userId, username, avatar, bio, characterClass } = body;
if (!userId) {
return NextResponse.json(
{ error: "ID utilisateur requis" },
{ status: 400 }
);
}
// Vérifier que l'utilisateur existe et a été créé récemment (dans les 10 dernières minutes)
const user = await prisma.user.findUnique({
where: { id: userId },
});
if (!user) {
return NextResponse.json(
{ error: "Utilisateur non trouvé" },
{ status: 404 }
);
}
// Vérifier que le compte a été créé récemment (dans les 10 dernières minutes)
const tenMinutesAgo = new Date(Date.now() - 10 * 60 * 1000);
if (user.createdAt < tenMinutesAgo) {
return NextResponse.json(
{ error: "Temps écoulé pour finaliser l'inscription" },
{ status: 400 }
);
}
// Validation username
if (username !== undefined) {
if (typeof username !== "string" || username.trim().length === 0) {
return NextResponse.json(
{ error: "Le nom d'utilisateur ne peut pas être vide" },
{ status: 400 }
);
}
if (username.length < 3 || username.length > 20) {
return NextResponse.json(
{ error: "Le nom d'utilisateur doit contenir entre 3 et 20 caractères" },
{ status: 400 }
);
}
// Vérifier si le username est déjà pris par un autre utilisateur
const existingUser = await prisma.user.findFirst({
where: {
username: username.trim(),
NOT: { id: userId },
},
});
if (existingUser) {
return NextResponse.json(
{ error: "Ce nom d'utilisateur est déjà pris" },
{ status: 400 }
);
}
}
// Validation bio
if (bio !== undefined && bio !== null) {
if (typeof bio !== "string") {
return NextResponse.json(
{ error: "La bio doit être une chaîne de caractères" },
{ status: 400 }
);
}
if (bio.length > 500) {
return NextResponse.json(
{ error: "La bio ne peut pas dépasser 500 caractères" },
{ status: 400 }
);
}
}
// Validation characterClass
const validClasses = [
"WARRIOR",
"MAGE",
"ROGUE",
"RANGER",
"PALADIN",
"ENGINEER",
"MERCHANT",
"SCHOLAR",
"BERSERKER",
"NECROMANCER",
];
if (characterClass !== undefined && characterClass !== null) {
if (!validClasses.includes(characterClass)) {
return NextResponse.json(
{ error: "Classe de personnage invalide" },
{ status: 400 }
);
}
}
// Mettre à jour l'utilisateur
const updateData: {
username?: string;
avatar?: string | null;
bio?: string | null;
characterClass?: CharacterClass | null;
} = {};
if (username !== undefined) {
updateData.username = username.trim();
}
if (avatar !== undefined) {
updateData.avatar = avatar || null;
}
if (bio !== undefined) {
if (bio === null || bio === "") {
updateData.bio = null;
} else if (typeof bio === "string") {
updateData.bio = bio.trim() || null;
} else {
updateData.bio = null;
}
}
if (characterClass !== undefined) {
updateData.characterClass = (characterClass as CharacterClass) || null;
}
// Si aucun champ à mettre à jour, retourner succès quand même
if (Object.keys(updateData).length === 0) {
return NextResponse.json({
message: "Profil finalisé avec succès",
userId: user.id,
});
}
const updatedUser = await prisma.user.update({
where: { id: userId },
data: updateData,
});
return NextResponse.json({
message: "Profil finalisé avec succès",
userId: updatedUser.id,
});
} catch (error) {
console.error("Error completing registration:", error);
const errorMessage = error instanceof Error ? error.message : "Erreur inconnue";
return NextResponse.json(
{ error: `Erreur lors de la finalisation de l'inscription: ${errorMessage}` },
{ status: 500 }
);
}
}

View File

@@ -5,11 +5,11 @@ import bcrypt from "bcryptjs";
export async function POST(request: Request) {
try {
const body = await request.json();
const { email, username, password } = body;
const { email, username, password, bio, characterClass, avatar } = body;
if (!email || !username || !password) {
return NextResponse.json(
{ error: "Tous les champs sont requis" },
{ error: "Email, nom d'utilisateur et mot de passe sont requis" },
{ status: 400 }
);
}
@@ -21,6 +21,26 @@ export async function POST(request: Request) {
);
}
// Valider characterClass si fourni
const validCharacterClasses = [
"WARRIOR",
"MAGE",
"ROGUE",
"RANGER",
"PALADIN",
"ENGINEER",
"MERCHANT",
"SCHOLAR",
"BERSERKER",
"NECROMANCER",
];
if (characterClass && !validCharacterClasses.includes(characterClass)) {
return NextResponse.json(
{ error: "Classe de personnage invalide" },
{ status: 400 }
);
}
// Vérifier si l'email existe déjà
const existingUser = await prisma.user.findFirst({
where: {
@@ -44,6 +64,9 @@ export async function POST(request: Request) {
email,
username,
password: hashedPassword,
bio: bio || null,
characterClass: characterClass || null,
avatar: avatar || null,
},
});

View File

@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Navigation from "@/components/Navigation";
@@ -12,18 +12,64 @@ export default function RegisterPage() {
username: "",
password: "",
confirmPassword: "",
bio: "",
characterClass: null as string | null,
avatar: null as string | null,
});
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [uploadingAvatar, setUploadingAvatar] = useState(false);
const [step, setStep] = useState(1);
const [userId, setUserId] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const handleChange = (
e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = async (e: React.FormEvent) => {
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setUploadingAvatar(true);
setError("");
try {
const formDataUpload = new FormData();
formDataUpload.append("file", file);
const response = await fetch("/api/register/avatar", {
method: "POST",
body: formDataUpload,
});
if (response.ok) {
const data = await response.json();
setFormData({
...formData,
avatar: data.url,
});
} else {
const errorData = await response.json();
setError(errorData.error || "Erreur lors de l'upload de l'avatar");
}
} catch (err) {
console.error("Error uploading avatar:", err);
setError("Erreur lors de l'upload de l'avatar");
} finally {
setUploadingAvatar(false);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}
};
const handleStep1Submit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
@@ -49,6 +95,9 @@ export default function RegisterPage() {
email: formData.email,
username: formData.username,
password: formData.password,
bio: null,
characterClass: null,
avatar: null,
}),
});
@@ -59,7 +108,8 @@ export default function RegisterPage() {
return;
}
router.push("/login?registered=true");
setUserId(data.userId);
setStep(2);
} catch (err) {
setError("Une erreur est survenue");
} finally {
@@ -67,6 +117,47 @@ export default function RegisterPage() {
}
};
const handleStep2Submit = async (e: React.FormEvent) => {
e.preventDefault();
setError("");
if (!userId) {
setError("Erreur: ID utilisateur manquant");
return;
}
setLoading(true);
try {
const response = await fetch("/api/register/complete", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
userId,
username: formData.username,
bio: formData.bio && formData.bio.trim() ? formData.bio.trim() : null,
characterClass: formData.characterClass || null,
avatar: formData.avatar || null,
}),
});
if (!response.ok) {
const errorData = await response.json();
setError(errorData.error || "Une erreur est survenue");
return;
}
router.push("/login?registered=true");
} catch (err) {
console.error("Registration completion error:", err);
setError(err instanceof Error ? err.message : "Une erreur est survenue");
} finally {
setLoading(false);
}
};
return (
<main className="min-h-screen bg-black relative">
<Navigation />
@@ -89,101 +180,352 @@ export default function RegisterPage() {
INSCRIPTION
</span>
</h1>
<p className="text-gray-400 text-sm text-center mb-8">
Créez votre compte pour commencer
<p className="text-gray-400 text-sm text-center mb-4">
{step === 1
? "Créez votre compte pour commencer"
: "Personnalisez votre profil"}
</p>
<form onSubmit={handleSubmit} className="space-y-6">
{error && (
<div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
{error}
</div>
)}
<div>
<label
htmlFor="email"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Email
</label>
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="votre@email.com"
/>
</div>
<div>
<label
htmlFor="username"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Nom d'utilisateur
</label>
<input
id="username"
name="username"
type="text"
value={formData.username}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="VotrePseudo"
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Mot de passe
</label>
<input
id="password"
name="password"
type="password"
value={formData.password}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="••••••••"
/>
</div>
<div>
<label
htmlFor="confirmPassword"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Confirmer le mot de passe
</label>
<input
id="confirmPassword"
name="confirmPassword"
type="password"
value={formData.confirmPassword}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="••••••••"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full px-6 py-3 border border-pixel-gold/50 bg-black/60 text-white uppercase text-sm tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
{/* Step Indicator */}
<div className="flex items-center justify-center gap-2 mb-8">
<div
className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition ${
step >= 1
? "bg-pixel-gold text-black"
: "bg-gray-700 text-gray-400"
}`}
>
{loading ? "Inscription..." : "S'inscrire"}
</button>
</form>
1
</div>
<div
className={`h-px w-12 transition ${
step >= 2 ? "bg-pixel-gold" : "bg-gray-700"
}`}
/>
<div
className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold transition ${
step >= 2
? "bg-pixel-gold text-black"
: "bg-gray-700 text-gray-400"
}`}
>
2
</div>
</div>
{step === 1 ? (
<form onSubmit={handleStep1Submit} className="space-y-6">
{error && (
<div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
{error}
</div>
)}
<div>
<label
htmlFor="email"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Email
</label>
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="votre@email.com"
/>
</div>
<div>
<label
htmlFor="username"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Nom d'utilisateur
</label>
<input
id="username"
name="username"
type="text"
value={formData.username}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="VotrePseudo"
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Mot de passe
</label>
<input
id="password"
name="password"
type="password"
value={formData.password}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="••••••••"
/>
</div>
<div>
<label
htmlFor="confirmPassword"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Confirmer le mot de passe
</label>
<input
id="confirmPassword"
name="confirmPassword"
type="password"
value={formData.confirmPassword}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="••••••••"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full px-6 py-3 border border-pixel-gold/50 bg-black/60 text-white uppercase text-sm tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? "Création..." : "Suivant"}
</button>
</form>
) : (
<form onSubmit={handleStep2Submit} className="space-y-6">
{error && (
<div className="bg-red-900/50 border border-red-500/50 text-red-400 px-4 py-3 rounded text-sm">
{error}
</div>
)}
{/* Avatar Selection */}
<div>
<label className="block text-sm font-semibold text-gray-300 mb-3 uppercase tracking-wider">
Avatar (optionnel)
</label>
<div className="flex flex-col items-center gap-4">
{/* Preview */}
<div className="relative">
<div className="w-24 h-24 rounded-full border-4 border-pixel-gold/50 overflow-hidden bg-gray-900 flex items-center justify-center">
{formData.avatar ? (
<img
src={formData.avatar}
alt="Avatar"
className="w-full h-full object-cover"
/>
) : formData.username ? (
<span className="text-pixel-gold text-3xl font-bold">
{formData.username.charAt(0).toUpperCase()}
</span>
) : (
<span className="text-pixel-gold text-3xl font-bold">
?
</span>
)}
</div>
{uploadingAvatar && (
<div className="absolute inset-0 bg-black/60 flex items-center justify-center rounded-full">
<div className="text-pixel-gold text-xs">
Upload...
</div>
</div>
)}
</div>
{/* Default Avatars */}
<div className="flex flex-col items-center gap-2 w-full">
<label className="text-pixel-gold text-xs uppercase tracking-widest">
Avatars par défaut
</label>
<div className="flex flex-wrap gap-2 justify-center">
{[
"/avatar-1.jpg",
"/avatar-2.jpg",
"/avatar-3.jpg",
"/avatar-4.jpg",
"/avatar-5.jpg",
"/avatar-6.jpg",
].map((defaultAvatar) => (
<button
key={defaultAvatar}
type="button"
onClick={() =>
setFormData({
...formData,
avatar: defaultAvatar,
})
}
className={`w-16 h-16 rounded-full border-2 overflow-hidden transition ${
formData.avatar === defaultAvatar
? "border-pixel-gold scale-110"
: "border-pixel-gold/30 hover:border-pixel-gold/50"
}`}
>
<img
src={defaultAvatar}
alt="Avatar par défaut"
className="w-full h-full object-cover"
/>
</button>
))}
</div>
</div>
{/* Custom Upload */}
<div>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleAvatarUpload}
className="hidden"
id="avatar-upload"
/>
<label
htmlFor="avatar-upload"
className="px-4 py-2 border border-pixel-gold/50 bg-black/40 text-white uppercase text-xs tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition cursor-pointer inline-block"
>
{uploadingAvatar
? "Upload en cours..."
: "Upload un avatar custom"}
</label>
</div>
</div>
</div>
<div>
<label
htmlFor="username-step2"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Nom d'utilisateur
</label>
<input
id="username-step2"
name="username"
type="text"
value={formData.username}
onChange={handleChange}
required
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition"
placeholder="VotrePseudo"
minLength={3}
maxLength={20}
/>
<p className="text-gray-500 text-xs mt-1">3-20 caractères</p>
</div>
<div>
<label
htmlFor="bio"
className="block text-sm font-semibold text-gray-300 mb-2 uppercase tracking-wider"
>
Bio (optionnel)
</label>
<textarea
id="bio"
name="bio"
value={formData.bio}
onChange={handleChange}
className="w-full px-4 py-3 bg-black/60 border border-pixel-gold/30 rounded text-white placeholder-gray-500 focus:outline-none focus:border-pixel-gold transition resize-none"
rows={4}
maxLength={500}
placeholder="Parlez-nous de vous..."
/>
<p className="text-gray-500 text-xs mt-1">
{formData.bio.length}/500 caractères
</p>
</div>
<div>
<label className="block text-sm font-semibold text-gray-300 mb-3 uppercase tracking-wider">
Classe de Personnage (optionnel)
</label>
<div className="grid grid-cols-2 gap-2">
{[
{ value: "WARRIOR", name: "Guerrier", icon: "⚔️" },
{ value: "MAGE", name: "Mage", icon: "🔮" },
{ value: "ROGUE", name: "Voleur", icon: "🗡️" },
{ value: "RANGER", name: "Rôdeur", icon: "🏹" },
{ value: "PALADIN", name: "Paladin", icon: "🛡️" },
{ value: "ENGINEER", name: "Ingénieur", icon: "⚙️" },
{ value: "MERCHANT", name: "Marchand", icon: "💰" },
{ value: "SCHOLAR", name: "Érudit", icon: "📚" },
{ value: "BERSERKER", name: "Berserker", icon: "🔥" },
{
value: "NECROMANCER",
name: "Nécromancien",
icon: "💀",
},
].map((cls) => (
<button
key={cls.value}
type="button"
onClick={() =>
setFormData({
...formData,
characterClass:
formData.characterClass === cls.value
? null
: cls.value,
})
}
className={`p-3 border-2 rounded-lg text-left transition-all ${
formData.characterClass === cls.value
? "border-pixel-gold bg-pixel-gold/20"
: "border-pixel-gold/30 bg-black/40 hover:border-pixel-gold/50"
}`}
>
<div className="flex items-center gap-2">
<span className="text-xl">{cls.icon}</span>
<span
className={`font-bold text-xs uppercase tracking-wider ${
formData.characterClass === cls.value
? "text-pixel-gold"
: "text-white"
}`}
>
{cls.name}
</span>
</div>
</button>
))}
</div>
</div>
<div className="flex gap-4">
<button
type="button"
onClick={() => setStep(1)}
className="flex-1 px-6 py-3 border border-gray-600/50 bg-black/40 text-gray-400 uppercase text-sm tracking-widest rounded hover:bg-gray-900/40 hover:border-gray-500 transition"
>
Retour
</button>
<button
type="submit"
disabled={loading}
className="flex-1 px-6 py-3 border border-pixel-gold/50 bg-black/60 text-white uppercase text-sm tracking-widest rounded hover:bg-pixel-gold/10 hover:border-pixel-gold transition disabled:opacity-50 disabled:cursor-not-allowed"
>
{loading ? "Finalisation..." : "Terminer"}
</button>
</div>
</form>
)}
<div className="mt-6 text-center">
<p className="text-gray-400 text-sm">