feat: fix registration 500, add forgot-password flow, frontend validation
Some checks failed
Build and Deploy / Backend Tests (push) Has been cancelled
Build and Deploy / Frontend Build Check (push) Has been cancelled
Build and Deploy / Build Docker Images (push) Has been cancelled
Build and Deploy / Deploy to Server (push) Has been cancelled

- Fix MissingGreenlet: sync_engine now uses psycopg2 instead of asyncpg
- Fix bcrypt/passlib compat: pin bcrypt<4.1 in requirements
- Fix legacy password_hash NOT NULL: alter column to nullable in migration
- Add frontend password validation (uppercase + lowercase + digit)
- Add forgot-password and reset-password backend endpoints
- Add forgot-password and reset-password frontend pages
- Add email_service.py (SMTP via admin settings)
- Add reset_token/reset_token_expires columns to User model
- Migrate legacy JSON-only users to DB on password reset request
- Mount data/ volume in docker-compose.local.yml for persistence
- Add production deployment config (Dockerfile, nginx, deploy.sh)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Sepehr Ramezani
2026-05-01 16:23:51 +02:00
parent 26bd096a06
commit 2f7347b4db
25 changed files with 2765 additions and 64 deletions

View File

@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect } from "react";
import { Settings, Save, Loader2, CheckCircle, XCircle, RefreshCw, FlaskConical, KeyRound } from "lucide-react";
import { Settings, Save, Loader2, CheckCircle, XCircle, RefreshCw, FlaskConical, KeyRound, Mail } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -10,6 +10,7 @@ import { Switch } from "@/components/ui/switch";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useNotification } from "@/components/ui/notification";
import { ModelCombobox, ModelOption } from "@/components/ui/model-combobox";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";
@@ -22,6 +23,16 @@ interface ProviderConfig {
max_retries?: number;
}
interface SmtpConfig {
enabled: boolean;
host?: string;
port: number;
username?: string;
password?: string;
from_email?: string;
use_tls: boolean;
}
interface SettingsConfig {
google: ProviderConfig;
google_cloud: ProviderConfig;
@@ -31,6 +42,7 @@ interface SettingsConfig {
openrouter: ProviderConfig;
openrouter_premium: ProviderConfig;
zai: ProviderConfig;
smtp: SmtpConfig;
fallback_chain: string;
fallback_chain_classic: string;
fallback_chain_llm: string;
@@ -44,6 +56,7 @@ interface EnvInfo {
zai: boolean;
ollama: boolean;
google_cloud: boolean;
smtp: boolean;
}
interface OllamaModel {
@@ -61,6 +74,7 @@ const defaultConfig: SettingsConfig = {
openrouter: { enabled: false, api_key: "", model: "deepseek/deepseek-chat" },
openrouter_premium: { enabled: false, api_key: "", model: "openai/gpt-4o-mini" },
zai: { enabled: false, api_key: "", base_url: "https://api.x.ai/v1", model: "grok-2-1212" },
smtp: { enabled: false, host: "", port: 587, username: "", password: "", from_email: "", use_tls: true },
fallback_chain: "google,deepl,openai,ollama,openrouter,openrouter_premium,zai",
fallback_chain_classic: "google,deepl",
fallback_chain_llm: "ollama,openai,openrouter,zai",
@@ -74,6 +88,7 @@ const defaultEnvInfo: EnvInfo = {
zai: false,
ollama: false,
google_cloud: false,
smtp: false,
};
export default function AdminSettingsPage() {
@@ -85,6 +100,13 @@ export default function AdminSettingsPage() {
const [testMessages, setTestMessages] = useState<Record<string, string>>({});
const [ollamaModels, setOllamaModels] = useState<OllamaModel[]>([]);
const [isLoadingModels, setIsLoadingModels] = useState(false);
const [openaiModels, setOpenaiModels] = useState<ModelOption[]>([]);
const [openrouterModels, setOpenrouterModels] = useState<ModelOption[]>([]);
const [zaiModels, setZaiModels] = useState<ModelOption[]>([]);
const [loadingModelsProvider, setLoadingModelsProvider] = useState<string | null>(null);
const [isSendingTestEmail, setIsSendingTestEmail] = useState(false);
const [testEmailResult, setTestEmailResult] = useState<"idle" | "ok" | "error">("idle");
const [testEmailMessage, setTestEmailMessage] = useState<string>("");
const { success, error, info } = useNotification();
useEffect(() => {
@@ -147,11 +169,19 @@ export default function AdminSettingsPage() {
setTestResults((prev) => ({ ...prev, [provider]: "testing" }));
setTestMessages((prev) => ({ ...prev, [provider]: "" }));
try {
// For SMTP, send current form values so unsaved changes are tested
const smtpBody = provider === "smtp"
? { body: JSON.stringify(config.smtp) }
: {};
const response = await fetch(
`${API_BASE}/api/v1/admin/providers/${provider}/test`,
{
method: "POST",
headers: { Authorization: `Bearer ${getToken()}` },
headers: {
Authorization: `Bearer ${getToken()}`,
...(provider === "smtp" ? { "Content-Type": "application/json" } : {}),
},
...smtpBody,
}
);
const data = await response.json();
@@ -174,10 +204,12 @@ export default function AdminSettingsPage() {
const fetchOllamaModels = async () => {
setIsLoadingModels(true);
try {
const response = await fetch(
`${API_BASE}/api/v1/admin/providers/ollama/models`,
{ headers: { Authorization: `Bearer ${getToken()}` } }
);
const url = config.ollama.base_url
? `${API_BASE}/api/v1/admin/providers/ollama/models?base_url=${encodeURIComponent(config.ollama.base_url)}`
: `${API_BASE}/api/v1/admin/providers/ollama/models`;
const response = await fetch(url, {
headers: { Authorization: `Bearer ${getToken()}` },
});
if (response.ok) {
const data = await response.json();
setOllamaModels(data.data || []);
@@ -195,7 +227,32 @@ export default function AdminSettingsPage() {
}
};
type ProviderKey = keyof Omit<SettingsConfig, "fallback_chain" | "fallback_chain_classic" | "fallback_chain_llm">;
const fetchModels = async (provider: string) => {
setLoadingModelsProvider(provider);
try {
const response = await fetch(
`${API_BASE}/api/v1/admin/providers/${provider}/models`,
{ headers: { Authorization: `Bearer ${getToken()}` } }
);
if (response.ok) {
const data = await response.json();
const models: ModelOption[] = data.data || [];
if (provider === "openai") setOpenaiModels(models);
else if (provider === "openrouter") setOpenrouterModels(models);
else if (provider === "zai") setZaiModels(models);
info({ title: `${models.length} modèles ${provider} trouvés` });
} else {
const body = await response.json().catch(() => ({}));
error({ title: `Erreur ${provider}`, description: body.message || `HTTP ${response.status}` });
}
} catch (e) {
error({ title: `Erreur ${provider}`, description: "Impossible de contacter le serveur." });
} finally {
setLoadingModelsProvider(null);
}
};
type ProviderKey = keyof Omit<SettingsConfig, "fallback_chain" | "fallback_chain_classic" | "fallback_chain_llm" | "smtp">;
const updateProvider = (provider: ProviderKey, updates: Partial<ProviderConfig>) => {
setConfig((prev) => ({
...prev,
@@ -203,6 +260,45 @@ export default function AdminSettingsPage() {
}));
};
const updateSmtp = (updates: Partial<SmtpConfig>) => {
setConfig((prev) => ({
...prev,
smtp: { ...prev.smtp, ...updates },
}));
};
const sendTestEmail = async () => {
setIsSendingTestEmail(true);
setTestEmailResult("idle");
setTestEmailMessage("");
try {
const response = await fetch(
`${API_BASE}/api/v1/admin/providers/smtp/test-send`,
{
method: "POST",
headers: {
Authorization: `Bearer ${getToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify(config.smtp),
}
);
const data = await response.json();
if (data.available) {
setTestEmailResult("ok");
setTestEmailMessage(data.test_result || "Email envoyé avec succès");
} else {
setTestEmailResult("error");
setTestEmailMessage(data.error || "Échec de l'envoi");
}
} catch {
setTestEmailResult("error");
setTestEmailMessage("Erreur réseau");
} finally {
setIsSendingTestEmail(false);
}
};
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
@@ -298,15 +394,29 @@ export default function AdminSettingsPage() {
testMessage={testMessages.openai}
envKeySet={envInfo.openai}
>
<div className="space-y-2">
<Label htmlFor="openai-key">Clé API</Label>
<Input
id="openai-key"
type="password"
placeholder={envInfo.openai ? "Clé configurée dans .env (laisser vide pour l'utiliser)" : "sk-..."}
value={config.openai.api_key || ""}
onChange={(e) => updateProvider("openai", { api_key: e.target.value })}
/>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="openai-key">Clé API</Label>
<Input
id="openai-key"
type="password"
placeholder={envInfo.openai ? "Clé configurée dans .env (laisser vide pour l'utiliser)" : "sk-..."}
value={config.openai.api_key || ""}
onChange={(e) => updateProvider("openai", { api_key: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="openai-model">Modèle</Label>
<ModelCombobox
value={config.openai.model || ""}
onChange={(v) => updateProvider("openai", { model: v })}
models={openaiModels}
isLoading={loadingModelsProvider === "openai"}
onFetchModels={() => fetchModels("openai")}
providerLabel="OpenAI"
placeholder="gpt-4o"
/>
</div>
</div>
</ProviderCard>
@@ -409,11 +519,14 @@ export default function AdminSettingsPage() {
</div>
<div className="space-y-2">
<Label htmlFor="openrouter-model">Modèle Essentiel</Label>
<Input
id="openrouter-model"
placeholder="deepseek/deepseek-chat"
<ModelCombobox
value={config.openrouter.model || ""}
onChange={(e) => updateProvider("openrouter", { model: e.target.value })}
onChange={(v) => updateProvider("openrouter", { model: v })}
models={openrouterModels}
isLoading={loadingModelsProvider === "openrouter"}
onFetchModels={() => fetchModels("openrouter")}
providerLabel="OpenRouter"
placeholder="deepseek/deepseek-chat"
/>
<p className="text-xs text-muted-foreground">Recommandé : <code>deepseek/deepseek-chat</code> (~0.04/doc)</p>
</div>
@@ -432,11 +545,14 @@ export default function AdminSettingsPage() {
>
<div className="space-y-2">
<Label htmlFor="openrouter-premium-model">Modèle Premium</Label>
<Input
id="openrouter-premium-model"
placeholder="openai/gpt-4o-mini"
<ModelCombobox
value={config.openrouter_premium.model || ""}
onChange={(e) => updateProvider("openrouter_premium", { model: e.target.value })}
onChange={(v) => updateProvider("openrouter_premium", { model: v })}
models={openrouterModels}
isLoading={loadingModelsProvider === "openrouter"}
onFetchModels={() => fetchModels("openrouter")}
providerLabel="OpenRouter"
placeholder="openai/gpt-4o-mini"
/>
<p className="text-xs text-muted-foreground">
Recommandé : <code>openai/gpt-4o-mini</code> (~0.15/doc) ou <code>anthropic/claude-3.5-haiku</code> (~0.20/doc)
@@ -467,11 +583,14 @@ export default function AdminSettingsPage() {
</div>
<div className="space-y-2">
<Label htmlFor="zai-model">Modèle</Label>
<Input
id="zai-model"
placeholder="grok-2-1212"
<ModelCombobox
value={config.zai.model || ""}
onChange={(e) => updateProvider("zai", { model: e.target.value })}
onChange={(v) => updateProvider("zai", { model: v })}
models={zaiModels}
isLoading={loadingModelsProvider === "zai"}
onFetchModels={() => fetchModels("zai")}
providerLabel="xAI"
placeholder="grok-2-1212"
/>
</div>
</div>
@@ -513,6 +632,143 @@ export default function AdminSettingsPage() {
</div>
</CardContent>
</Card>
<Card className={config.smtp.enabled ? "border-primary/30 overflow-visible" : "overflow-visible"}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-blue-600/20 rounded-md flex items-center justify-center">
<Mail className="w-4 h-4 text-blue-400" />
</div>
<CardTitle className="text-base">Email SMTP</CardTitle>
<Badge variant={config.smtp.enabled ? "default" : "secondary"} className="text-xs">
{config.smtp.enabled ? "Activé" : "Désactivé"}
</Badge>
{envInfo.smtp && (
<Badge variant="outline" className="text-xs gap-1 border-green-500/40 text-green-400">
<KeyRound className="size-3" />
Config dans .env
</Badge>
)}
</div>
<div className="flex items-center gap-3">
<Button
variant="outline"
size="sm"
onClick={() => testProvider("smtp")}
disabled={testResults.smtp === "testing"}
className="h-8"
>
{testResults.smtp === "testing" ? (
<><Loader2 className="size-3 animate-spin mr-1" />Test...</>
) : testResults.smtp === "ok" ? (
<><CheckCircle className="size-3 text-green-500 mr-1" />OK</>
) : testResults.smtp === "error" ? (
<><XCircle className="size-3 text-red-500 mr-1" />Erreur</>
) : (
<><FlaskConical className="size-3 mr-1" />Tester</>
)}
</Button>
<Switch checked={config.smtp.enabled} onCheckedChange={(enabled) => updateSmtp({ enabled })} />
</div>
</div>
<CardDescription>
Configuration du serveur SMTP pour l&apos;envoi d&apos;emails (mot de passe oublié, notifications, etc.)
</CardDescription>
{testMessages.smtp && (
<p className={`text-xs mt-1 ${testResults.smtp === "ok" ? "text-green-400" : "text-red-400"}`}>
{testMessages.smtp}
</p>
)}
</CardHeader>
<CardContent className="pt-0 space-y-4">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="smtp-host">Hôte SMTP</Label>
<Input
id="smtp-host"
placeholder={envInfo.smtp ? "Configuré dans .env" : "smtp.example.com"}
value={config.smtp.host || ""}
onChange={(e) => updateSmtp({ host: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="smtp-port">Port</Label>
<Input
id="smtp-port"
type="number"
placeholder="587"
value={config.smtp.port}
onChange={(e) => updateSmtp({ port: parseInt(e.target.value) || 587 })}
/>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="smtp-username">Nom d&apos;utilisateur</Label>
<Input
id="smtp-username"
placeholder={envInfo.smtp ? "Configuré dans .env" : "user@example.com"}
value={config.smtp.username || ""}
onChange={(e) => updateSmtp({ username: e.target.value })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="smtp-password">Mot de passe</Label>
<Input
id="smtp-password"
type="password"
placeholder="••••••••"
value={config.smtp.password || ""}
onChange={(e) => updateSmtp({ password: e.target.value })}
/>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="smtp-from">Adresse d&apos;expédition</Label>
<Input
id="smtp-from"
type="email"
placeholder={envInfo.smtp ? "Configuré dans .env" : "noreply@example.com"}
value={config.smtp.from_email || ""}
onChange={(e) => updateSmtp({ from_email: e.target.value })}
/>
</div>
<div className="flex items-center gap-3 pt-6">
<Switch
checked={config.smtp.use_tls}
onCheckedChange={(checked) => updateSmtp({ use_tls: checked })}
/>
<Label>Utiliser TLS</Label>
</div>
</div>
<div className="flex items-center gap-3 pt-2">
<Button
variant="outline"
size="sm"
onClick={sendTestEmail}
disabled={isSendingTestEmail || !config.smtp.enabled}
className="h-8"
>
{isSendingTestEmail ? (
<><Loader2 className="size-3 animate-spin mr-1" />Envoi...</>
) : testEmailResult === "ok" ? (
<><CheckCircle className="size-3 text-green-500 mr-1" />Envoyé</>
) : testEmailResult === "error" ? (
<><XCircle className="size-3 text-red-500 mr-1" />Échec</>
) : (
<><Mail className="size-3 mr-1" />Envoyer un email de test</>
)}
</Button>
{testEmailMessage && (
<p className={`text-xs ${testEmailResult === "ok" ? "text-green-400" : "text-red-400"}`}>
{testEmailMessage}
</p>
)}
</div>
</CardContent>
</Card>
</div>
<div className="flex justify-end">
@@ -558,7 +814,7 @@ function ProviderCard({
children?: React.ReactNode;
}) {
return (
<Card className={enabled ? "border-primary/30" : ""}>
<Card className={enabled ? "border-primary/30 overflow-visible" : "overflow-visible"}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">

View File

@@ -0,0 +1,157 @@
'use client';
import { useState, Suspense } from 'react';
import Link from 'next/link';
import { Mail, Loader2, Languages, ArrowLeft, CheckCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { apiClient } from '@/lib/apiClient';
function ForgotPasswordForm() {
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [sent, setSent] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
if (!email) {
setError('Veuillez entrer votre adresse email');
return;
}
setLoading(true);
try {
await apiClient.post('/api/v1/auth/forgot-password', { email });
setSent(true);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : "Une erreur s'est produite";
setError(message);
} finally {
setLoading(false);
}
};
return (
<Card variant="elevated" className="w-full max-w-md mx-auto" hover={false}>
<CardHeader className="text-center pb-6">
<Link href="/" className="inline-flex items-center gap-3 mb-6 group">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-lg group-hover:shadow-xl group-hover:shadow-primary/25 transition-all duration-300 group-hover:-translate-y-0.5">
<Languages className="h-6 w-6" />
</div>
<span className="text-2xl font-semibold text-foreground group-hover:text-primary transition-colors duration-300">
Office Translator
</span>
</Link>
<CardTitle className="text-2xl font-bold">Mot de passe oublie</CardTitle>
<CardDescription>
{sent
? 'Verifiez votre boite mail'
: 'Entrez votre email pour recevoir un lien de reinitialisation'}
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
{sent ? (
<div className="rounded-lg bg-green-50 border border-green-200 p-4 dark:bg-green-950/20 dark:border-green-900">
<div className="flex items-start gap-3">
<CheckCircle className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
<p className="text-sm text-green-800 dark:text-green-200">
Si un compte existe avec cette adresse, un email de reinitialisation a ete envoye.
</p>
</div>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4">
<p className="text-sm text-destructive">{error}</p>
</div>
)}
<div className="space-y-2">
<Label htmlFor="email">Adresse email</Label>
<Input
id="email"
type="email"
placeholder="vous@exemple.com"
value={email}
onChange={(e) => setEmail(e.target.value)}
leftIcon={<Mail className="h-4 w-4" />}
required
autoComplete="email"
/>
</div>
<Button
type="submit"
variant="premium"
size="lg"
className="w-full"
disabled={loading || !email}
loading={loading}
>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Envoi en cours...
</>
) : (
'Envoyer le lien de reinitialisation'
)}
</Button>
</form>
)}
<p className="text-center text-sm text-muted-foreground">
<Link href="/auth/login" className="text-primary hover:underline font-medium inline-flex items-center gap-1">
<ArrowLeft className="h-3 w-3" />
Retour a la connexion
</Link>
</p>
</CardContent>
</Card>
);
}
function LoadingFallback() {
return (
<div className="w-full max-w-md mx-auto">
<div className="rounded-xl bg-card border border-border shadow-lg p-8">
<div className="flex flex-col items-center justify-center py-8 space-y-4">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground">
<Languages className="h-6 w-6" />
</div>
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-muted-foreground">Chargement...</p>
</div>
</div>
</div>
);
}
export default function ForgotPasswordPage() {
return (
<div className="min-h-screen bg-gradient-to-br from-surface via-surface-elevated to-background flex items-center justify-center p-4 relative overflow-hidden">
<div className="absolute inset-0">
<div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-accent/5" />
<div className="absolute inset-0 bg-[url('/grid.svg')] opacity-5" />
<div className="absolute inset-0 bg-gradient-to-t from-background via-background/90 to-background/50" />
</div>
<div className="absolute inset-0 overflow-hidden pointer-events-none">
<div className="absolute top-20 left-10 w-32 h-32 bg-primary/5 rounded-full blur-3xl animate-pulse" />
<div className="absolute bottom-20 right-20 w-24 h-24 bg-accent/5 rounded-full blur-2xl animate-pulse" />
</div>
<Suspense fallback={<LoadingFallback />}>
<ForgotPasswordForm />
</Suspense>
</div>
);
}

View File

@@ -27,7 +27,10 @@ function validateEmail(email: string) {
}
function validatePassword(password: string) {
return password.length >= 8;
return password.length >= 8
&& /[A-Z]/.test(password)
&& /[a-z]/.test(password)
&& /[0-9]/.test(password);
}
function getPasswordStrength(password: string) {
@@ -79,7 +82,7 @@ export function RegisterForm() {
: undefined;
const passwordError = touched.password && password.length > 0 && !validatePassword(password)
? 'Mot de passe trop court (minimum 8 caractères)'
? 'Le mot de passe doit contenir au moins 8 caractères, une majuscule, une minuscule et un chiffre'
: undefined;
const confirmError = touched.confirmPassword && confirmPassword.length > 0 && password !== confirmPassword

View File

@@ -0,0 +1,253 @@
'use client';
import { useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Lock, Loader2, Languages, Eye, EyeOff, CheckCircle, ArrowLeft } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { apiClient } from '@/lib/apiClient';
function validatePassword(password: string) {
return password.length >= 8
&& /[A-Z]/.test(password)
&& /[a-z]/.test(password)
&& /[0-9]/.test(password);
}
function ResetPasswordForm() {
const router = useRouter();
const searchParams = useSearchParams();
const token = searchParams.get('token');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [showConfirm, setShowConfirm] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState(false);
const passwordError = password.length > 0 && !validatePassword(password)
? 'Le mot de passe doit contenir au moins 8 caracteres, une majuscule, une minuscule et un chiffre'
: '';
const confirmError = confirmPassword.length > 0 && password !== confirmPassword
? 'Les mots de passe ne correspondent pas'
: '';
const isFormValid = validatePassword(password) && password === confirmPassword;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
if (!token) {
setError('Token manquant. Veuillez utiliser le lien recu par email.');
return;
}
if (!isFormValid) return;
setLoading(true);
try {
await apiClient.post('/api/v1/auth/reset-password', { token, password });
setSuccess(true);
setTimeout(() => {
router.push('/auth/login');
}, 3000);
} catch (err: unknown) {
const message = err instanceof Error ? err.message : "Une erreur s'est produite";
setError(message);
} finally {
setLoading(false);
}
};
if (!token) {
return (
<Card variant="elevated" className="w-full max-w-md mx-auto" hover={false}>
<CardHeader className="text-center pb-6">
<Link href="/" className="inline-flex items-center gap-3 mb-6 group">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-lg">
<Languages className="h-6 w-6" />
</div>
<span className="text-2xl font-semibold text-foreground">
Office Translator
</span>
</Link>
<CardTitle className="text-2xl font-bold">Lien invalide</CardTitle>
</CardHeader>
<CardContent className="space-y-5">
<div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4">
<p className="text-sm text-destructive">
Ce lien de reinitialisation est invalide. Veuillez redemander un nouveau lien.
</p>
</div>
<p className="text-center text-sm text-muted-foreground">
<Link href="/auth/forgot-password" className="text-primary hover:underline font-medium">
Redemander un lien
</Link>
</p>
</CardContent>
</Card>
);
}
return (
<Card variant="elevated" className="w-full max-w-md mx-auto" hover={false}>
<CardHeader className="text-center pb-6">
<Link href="/" className="inline-flex items-center gap-3 mb-6 group">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground shadow-lg group-hover:shadow-xl group-hover:shadow-primary/25 transition-all duration-300 group-hover:-translate-y-0.5">
<Languages className="h-6 w-6" />
</div>
<span className="text-2xl font-semibold text-foreground group-hover:text-primary transition-colors duration-300">
Office Translator
</span>
</Link>
<CardTitle className="text-2xl font-bold">
{success ? 'Mot de passe reinitialise' : 'Nouveau mot de passe'}
</CardTitle>
<CardDescription>
{success
? 'Vous allez etre redirige vers la connexion'
: 'Definissez votre nouveau mot de passe'}
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
{success ? (
<div className="rounded-lg bg-green-50 border border-green-200 p-4 dark:bg-green-950/20 dark:border-green-900">
<div className="flex items-start gap-3">
<CheckCircle className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
<p className="text-sm text-green-800 dark:text-green-200">
Votre mot de passe a ete reinitialise avec succes. Vous allez etre redirige vers la page de connexion.
</p>
</div>
</div>
) : (
<form onSubmit={handleSubmit} className="space-y-4">
{error && (
<div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4">
<p className="text-sm text-destructive">{error}</p>
</div>
)}
<div className="space-y-2">
<Label htmlFor="password">Nouveau mot de passe</Label>
<div className="relative">
<Input
id="password"
type={showPassword ? 'text' : 'password'}
placeholder="••••••••"
value={password}
onChange={(e) => setPassword(e.target.value)}
leftIcon={<Lock className="h-4 w-4" />}
error={passwordError}
required
autoComplete="new-password"
/>
</div>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="text-xs text-muted-foreground hover:text-foreground"
>
{showPassword ? 'Masquer' : 'Afficher'} le mot de passe
</button>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirmer le mot de passe</Label>
<div className="relative">
<Input
id="confirmPassword"
type={showConfirm ? 'text' : 'password'}
placeholder="••••••••"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
leftIcon={<Lock className="h-4 w-4" />}
error={confirmError}
required
autoComplete="new-password"
/>
</div>
<button
type="button"
onClick={() => setShowConfirm(!showConfirm)}
className="text-xs text-muted-foreground hover:text-foreground"
>
{showConfirm ? 'Masquer' : 'Afficher'} le mot de passe
</button>
</div>
<Button
type="submit"
variant="premium"
size="lg"
className="w-full"
disabled={loading || !isFormValid}
loading={loading}
>
{loading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Reinitialisation...
</>
) : (
'Reinitialiser le mot de passe'
)}
</Button>
</form>
)}
<p className="text-center text-sm text-muted-foreground">
<Link href="/auth/login" className="text-primary hover:underline font-medium inline-flex items-center gap-1">
<ArrowLeft className="h-3 w-3" />
Retour a la connexion
</Link>
</p>
</CardContent>
</Card>
);
}
function LoadingFallback() {
return (
<div className="w-full max-w-md mx-auto">
<div className="rounded-xl bg-card border border-border shadow-lg p-8">
<div className="flex flex-col items-center justify-center py-8 space-y-4">
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground">
<Languages className="h-6 w-6" />
</div>
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-muted-foreground">Chargement...</p>
</div>
</div>
</div>
);
}
export default function ResetPasswordPage() {
return (
<div className="min-h-screen bg-gradient-to-br from-surface via-surface-elevated to-background flex items-center justify-center p-4 relative overflow-hidden">
<div className="absolute inset-0">
<div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-accent/5" />
<div className="absolute inset-0 bg-[url('/grid.svg')] opacity-5" />
<div className="absolute inset-0 bg-gradient-to-t from-background via-background/90 to-background/50" />
</div>
<div className="absolute inset-0 overflow-hidden pointer-events-none">
<div className="absolute top-20 left-10 w-32 h-32 bg-primary/5 rounded-full blur-3xl animate-pulse" />
<div className="absolute bottom-20 right-20 w-24 h-24 bg-accent/5 rounded-full blur-2xl animate-pulse" />
</div>
<Suspense fallback={<LoadingFallback />}>
<ResetPasswordForm />
</Suspense>
</div>
);
}

View File

@@ -0,0 +1,172 @@
"use client";
import React, { useState, useRef, useEffect, useCallback } from "react";
import { Search, List, Loader2, Check } from "lucide-react";
import { Input } from "@/components/ui/input";
export interface ModelOption {
id: string;
name?: string;
owned_by?: string;
context_length?: number;
pricing?: { prompt?: string; completion?: string };
}
interface ModelComboboxProps {
value: string;
onChange: (value: string) => void;
models: ModelOption[];
isLoading: boolean;
onFetchModels: () => void;
providerLabel: string;
placeholder?: string;
}
export function ModelCombobox({
value,
onChange,
models,
isLoading,
onFetchModels,
providerLabel,
placeholder = "nom-du-modele",
}: ModelComboboxProps) {
const [isOpen, setIsOpen] = useState(false);
const [filter, setFilter] = useState("");
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLUListElement>(null);
const [highlightIndex, setHighlightIndex] = useState(-1);
const filtered = React.useMemo(() => {
if (!filter.trim()) return models;
const q = filter.toLowerCase();
return models.filter(
(m) =>
m.id.toLowerCase().includes(q) ||
(m.name && m.name.toLowerCase().includes(q))
);
}, [models, filter]);
useEffect(() => {
function handleClick(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setIsOpen(false);
}
}
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
useEffect(() => { setHighlightIndex(-1); }, [filter]);
useEffect(() => {
if (highlightIndex >= 0 && listRef.current) {
(listRef.current.children[highlightIndex] as HTMLElement)?.scrollIntoView({ block: "nearest" });
}
}, [highlightIndex]);
const handleBrowse = useCallback(() => {
if (!isOpen) onFetchModels();
setIsOpen(!isOpen);
}, [isOpen, onFetchModels]);
const handleSelect = useCallback(
(model: ModelOption) => {
onChange(model.id);
setFilter("");
setIsOpen(false);
},
[onChange]
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (!isOpen || filtered.length === 0) return;
if (e.key === "ArrowDown") { e.preventDefault(); setHighlightIndex((p) => Math.min(p + 1, filtered.length - 1)); }
else if (e.key === "ArrowUp") { e.preventDefault(); setHighlightIndex((p) => Math.max(p - 1, 0)); }
else if (e.key === "Enter" && highlightIndex >= 0) { e.preventDefault(); handleSelect(filtered[highlightIndex]); }
else if (e.key === "Escape") { setIsOpen(false); }
},
[isOpen, filtered, highlightIndex, handleSelect]
);
return (
<div ref={containerRef} className="relative">
<div className="flex gap-2">
<div className="flex-1">
<Input
placeholder={placeholder}
value={value}
onChange={(e) => onChange(e.target.value)}
onFocus={() => { if (models.length > 0) setIsOpen(true); }}
onKeyDown={handleKeyDown}
leftIcon={<Search className="size-4" />}
loading={isLoading}
/>
</div>
<button
type="button"
onClick={handleBrowse}
disabled={isLoading}
className="flex items-center gap-1.5 px-3 h-10 rounded-lg border border-border-subtle bg-surface text-sm text-muted-foreground hover:bg-surface-elevated hover:text-foreground transition-colors disabled:opacity-50"
>
{isLoading ? <Loader2 className="size-4 animate-spin" /> : <List className="size-4" />}
<span className="hidden sm:inline">Parcourir</span>
</button>
</div>
{isOpen && (
<div className="absolute z-50 mt-1 w-full rounded-lg border border-border-subtle bg-card shadow-xl max-h-72 overflow-hidden flex flex-col">
{/* Filter */}
<div className="p-2 border-b border-border-subtle">
<Input
placeholder={`Filtrer...`}
value={filter}
onChange={(e) => setFilter(e.target.value)}
leftIcon={<Search className="size-3.5" />}
className="h-8 text-xs"
/>
</div>
{/* List */}
<ul ref={listRef} className="overflow-y-auto flex-1">
{filtered.length === 0 ? (
<li className="px-3 py-4 text-xs text-muted-foreground text-center">
{models.length === 0 ? "Aucun modele recupere" : "Aucun modele ne correspond"}
</li>
) : (
filtered.map((model, i) => (
<li
key={model.id}
onClick={() => handleSelect(model)}
onMouseEnter={() => setHighlightIndex(i)}
className={`flex items-center justify-between px-3 py-2 text-xs cursor-pointer transition-colors ${
i === highlightIndex ? "bg-primary/10 text-foreground" : "text-muted-foreground hover:bg-surface-elevated"
} ${value === model.id ? "bg-primary/5" : ""}`}
>
<div className="flex-1 min-w-0">
<div className="font-mono truncate text-foreground">{model.id}</div>
{model.name && model.name !== model.id && (
<div className="text-muted-foreground truncate mt-0.5">{model.name}</div>
)}
{model.context_length && (
<span className="text-muted-foreground">ctx: {(model.context_length / 1000).toFixed(0)}k</span>
)}
</div>
{value === model.id && <Check className="size-3.5 text-primary flex-shrink-0 ml-2" />}
</li>
))
)}
</ul>
{models.length > 0 && (
<div className="px-3 py-1.5 border-t border-border-subtle text-xs text-muted-foreground text-center bg-card">
{filtered.length} modele{filtered.length !== 1 ? "s" : ""}
{filter ? ` sur ${models.length}` : ""} nom libre possible
</div>
)}
</div>
)}
</div>
);
}