SAVE
This commit is contained in:
parent
3a99ab39c6
commit
ccecbe7c1f
|
@ -13,11 +13,14 @@
|
||||||
"@types/bcryptjs": "^3.0.0",
|
"@types/bcryptjs": "^3.0.0",
|
||||||
"@types/jsonwebtoken": "^9.0.9",
|
"@types/jsonwebtoken": "^9.0.9",
|
||||||
"bcryptjs": "^3.0.2",
|
"bcryptjs": "^3.0.2",
|
||||||
|
"i18next": "^25.1.2",
|
||||||
|
"i18next-resources-to-backend": "^1.2.1",
|
||||||
"jsonwebtoken": "^9.0.2",
|
"jsonwebtoken": "^9.0.2",
|
||||||
"mongoose": "^8.14.2",
|
"mongoose": "^8.14.2",
|
||||||
"next": "15.3.2",
|
"next": "15.3.2",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0"
|
"react-dom": "^19.0.0",
|
||||||
|
"react-i18next": "^15.5.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/eslintrc": "^3",
|
"@eslint/eslintrc": "^3",
|
||||||
|
|
|
@ -1 +0,0 @@
|
||||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
|
Before Width: | Height: | Size: 391 B |
|
@ -1 +0,0 @@
|
||||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
|
Before Width: | Height: | Size: 1.0 KiB |
|
@ -0,0 +1,54 @@
|
||||||
|
{
|
||||||
|
"header": {
|
||||||
|
"login": "Log in",
|
||||||
|
"register": "Sign up"
|
||||||
|
},
|
||||||
|
"home": {
|
||||||
|
"title": "Draw what you imagine",
|
||||||
|
"description": "A simple and powerful app to express your creativity through digital drawings.",
|
||||||
|
"startFree": "Start for free",
|
||||||
|
"learnMore": "Learn more"
|
||||||
|
},
|
||||||
|
"footer": {
|
||||||
|
"copyright": "© 2023 Draw. All rights reserved."
|
||||||
|
},
|
||||||
|
"auth": {
|
||||||
|
"login": {
|
||||||
|
"title": "Log in",
|
||||||
|
"subtitle": "Access your account to start drawing",
|
||||||
|
"email": "Email address",
|
||||||
|
"password": "Password",
|
||||||
|
"forgotPassword": "Forgot your password?",
|
||||||
|
"rememberMe": "Remember me",
|
||||||
|
"button": "Log in",
|
||||||
|
"buttonLoading": "Logging in...",
|
||||||
|
"noAccount": "Don't have an account?",
|
||||||
|
"signUp": "Sign up"
|
||||||
|
},
|
||||||
|
"register": {
|
||||||
|
"title": "Create account",
|
||||||
|
"subtitle": "Sign up to start drawing",
|
||||||
|
"username": "Username",
|
||||||
|
"email": "Email address",
|
||||||
|
"password": "Password",
|
||||||
|
"confirmPassword": "Confirm password",
|
||||||
|
"minChars": "Minimum 6 characters",
|
||||||
|
"button": "Create account",
|
||||||
|
"buttonLoading": "Creating account...",
|
||||||
|
"haveAccount": "Already have an account?",
|
||||||
|
"login": "Log in"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"passwordMatch": "Passwords do not match",
|
||||||
|
"passwordLength": "Password must be at least 6 characters long",
|
||||||
|
"registerError": "Error registering user",
|
||||||
|
"loginError": "Error logging in",
|
||||||
|
"unknownError": "An unknown error has occurred"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"language": {
|
||||||
|
"select": "Select language",
|
||||||
|
"es": "Spanish",
|
||||||
|
"en": "English"
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
{
|
||||||
|
"header": {
|
||||||
|
"login": "Iniciar sesión",
|
||||||
|
"register": "Registrarse"
|
||||||
|
},
|
||||||
|
"home": {
|
||||||
|
"title": "Dibuja lo que imagines",
|
||||||
|
"description": "Una aplicación simple y poderosa para expresar tu creatividad mediante dibujos digitales.",
|
||||||
|
"startFree": "Comenzar gratis",
|
||||||
|
"learnMore": "Conocer más"
|
||||||
|
},
|
||||||
|
"footer": {
|
||||||
|
"copyright": "© 2023 Draw. Todos los derechos reservados."
|
||||||
|
},
|
||||||
|
"auth": {
|
||||||
|
"login": {
|
||||||
|
"title": "Iniciar sesión",
|
||||||
|
"subtitle": "Accede a tu cuenta para comenzar a dibujar",
|
||||||
|
"email": "Correo electrónico",
|
||||||
|
"password": "Contraseña",
|
||||||
|
"forgotPassword": "¿Olvidaste tu contraseña?",
|
||||||
|
"rememberMe": "Recordarme",
|
||||||
|
"button": "Iniciar sesión",
|
||||||
|
"buttonLoading": "Iniciando sesión...",
|
||||||
|
"noAccount": "¿No tienes una cuenta?",
|
||||||
|
"signUp": "Regístrate"
|
||||||
|
},
|
||||||
|
"register": {
|
||||||
|
"title": "Crear cuenta",
|
||||||
|
"subtitle": "Regístrate para comenzar a dibujar",
|
||||||
|
"username": "Nombre de usuario",
|
||||||
|
"email": "Correo electrónico",
|
||||||
|
"password": "Contraseña",
|
||||||
|
"confirmPassword": "Confirmar contraseña",
|
||||||
|
"minChars": "Mínimo 6 caracteres",
|
||||||
|
"button": "Crear cuenta",
|
||||||
|
"buttonLoading": "Creando cuenta...",
|
||||||
|
"haveAccount": "¿Ya tienes una cuenta?",
|
||||||
|
"login": "Inicia sesión"
|
||||||
|
},
|
||||||
|
"errors": {
|
||||||
|
"passwordMatch": "Las contraseñas no coinciden",
|
||||||
|
"passwordLength": "La contraseña debe tener al menos 6 caracteres",
|
||||||
|
"registerError": "Error al registrar usuario",
|
||||||
|
"loginError": "Error al iniciar sesión",
|
||||||
|
"unknownError": "Ha ocurrido un error desconocido"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"language": {
|
||||||
|
"select": "Seleccionar idioma",
|
||||||
|
"es": "Español",
|
||||||
|
"en": "Inglés"
|
||||||
|
}
|
||||||
|
}
|
|
@ -1 +0,0 @@
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
|
Before Width: | Height: | Size: 1.3 KiB |
|
@ -1 +0,0 @@
|
||||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
|
Before Width: | Height: | Size: 128 B |
|
@ -1 +0,0 @@
|
||||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
|
Before Width: | Height: | Size: 385 B |
|
@ -5,15 +5,12 @@ export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
|
||||||
// Llamar a la función loginUser del controlador
|
|
||||||
const { token, user, error, status } = await loginUser(body);
|
const { token, user, error, status } = await loginUser(body);
|
||||||
|
|
||||||
// Si hay un error, devolverlo con el status correspondiente
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return NextResponse.json({ error }, { status: status || 500 });
|
return NextResponse.json({ error }, { status: status || 500 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devolver la respuesta con el token y el usuario
|
|
||||||
return NextResponse.json({ token, user }, { status: 200 });
|
return NextResponse.json({ token, user }, { status: 200 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error en el login:", error);
|
console.error("Error en el login:", error);
|
||||||
|
|
|
@ -5,15 +5,12 @@ export async function POST(request: NextRequest) {
|
||||||
try {
|
try {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
|
|
||||||
// Llamar a la función register del controlador
|
|
||||||
const { token, user, error, status } = await register(body);
|
const { token, user, error, status } = await register(body);
|
||||||
|
|
||||||
// Si hay un error, devolverlo con el status correspondiente
|
|
||||||
if (error) {
|
if (error) {
|
||||||
return NextResponse.json({ error }, { status: status || 500 });
|
return NextResponse.json({ error }, { status: status || 500 });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devolver la respuesta con el token y el usuario
|
|
||||||
return NextResponse.json({ token, user }, { status: 201 });
|
return NextResponse.json({ token, user }, { status: 201 });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error en el registro:", error);
|
console.error("Error en el registro:", error);
|
||||||
|
|
|
@ -3,9 +3,12 @@
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import { useI18n } from '@/lib/i18n/useI18n';
|
||||||
|
import { login } from '@/lib/api';
|
||||||
|
|
||||||
export default function Login() {
|
export default function Login() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { t, isLoading } = useI18n();
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
email: '',
|
email: '',
|
||||||
password: ''
|
password: ''
|
||||||
|
@ -24,44 +27,40 @@ export default function Login() {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const response = await fetch('/api/auth/login', {
|
const result = await login({
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
email: formData.email,
|
email: formData.email,
|
||||||
password: formData.password,
|
password: formData.password,
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
if (result.error) {
|
||||||
|
throw new Error(result.error || t('auth.errors.loginError'));
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(data.error || 'Error al iniciar sesión');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
localStorage.setItem('token', data.token);
|
if (result.data?.token) {
|
||||||
|
localStorage.setItem('token', result.data.token);
|
||||||
router.push('/dashboard');
|
router.push('/dashboard');
|
||||||
|
}
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
if (err instanceof Error) {
|
if (err instanceof Error) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
} else {
|
} else {
|
||||||
setError('Ha ocurrido un error desconocido');
|
setError(t('auth.errors.unknownError') || '');
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (isLoading) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-100 flex items-center justify-center p-6">
|
<div className="min-h-screen bg-gray-100 flex items-center justify-center p-6">
|
||||||
<div className="max-w-md w-full mx-auto">
|
<div className="max-w-md w-full mx-auto">
|
||||||
<div className="bg-white shadow-sm rounded-lg overflow-hidden">
|
<div className="bg-white shadow-sm rounded-lg overflow-hidden">
|
||||||
<div className="px-8 pt-8 pb-6 border-b border-gray-200">
|
<div className="px-8 pt-8 pb-6 border-b border-gray-200">
|
||||||
<h2 className="text-2xl font-normal text-gray-800 mb-2">Iniciar sesión</h2>
|
<h2 className="text-2xl font-normal text-gray-800 mb-2">{t('auth.login.title')}</h2>
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-gray-500">
|
||||||
Accede a tu cuenta para comenzar a dibujar
|
{t('auth.login.subtitle')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -75,7 +74,7 @@ export default function Login() {
|
||||||
<form onSubmit={handleSubmit} className="space-y-5">
|
<form onSubmit={handleSubmit} className="space-y-5">
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
Correo electrónico
|
{t('auth.login.email')}
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
id="email"
|
id="email"
|
||||||
|
@ -93,11 +92,11 @@ export default function Login() {
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
Contraseña
|
{t('auth.login.password')}
|
||||||
</label>
|
</label>
|
||||||
<div className="text-xs">
|
<div className="text-xs">
|
||||||
<a href="#" className="text-gray-500 hover:text-gray-700">
|
<a href="#" className="text-gray-500 hover:text-gray-700">
|
||||||
¿Olvidaste tu contraseña?
|
{t('auth.login.forgotPassword')}
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -122,7 +121,7 @@ export default function Login() {
|
||||||
className="h-4 w-4 text-blue-600 focus:ring-0 border-gray-300 rounded"
|
className="h-4 w-4 text-blue-600 focus:ring-0 border-gray-300 rounded"
|
||||||
/>
|
/>
|
||||||
<label htmlFor="remember-me" className="ml-2 block text-sm text-gray-600">
|
<label htmlFor="remember-me" className="ml-2 block text-sm text-gray-600">
|
||||||
Recordarme
|
{t('auth.login.rememberMe')}
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -138,9 +137,9 @@ export default function Login() {
|
||||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
</svg>
|
</svg>
|
||||||
Iniciando sesión...
|
{t('auth.login.buttonLoading')}
|
||||||
</>
|
</>
|
||||||
) : 'Iniciar sesión'}
|
) : t('auth.login.button')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
@ -148,9 +147,9 @@ export default function Login() {
|
||||||
|
|
||||||
<div className="px-8 py-4 bg-gray-50 border-t border-gray-200">
|
<div className="px-8 py-4 bg-gray-50 border-t border-gray-200">
|
||||||
<p className="text-sm text-center text-gray-600">
|
<p className="text-sm text-center text-gray-600">
|
||||||
¿No tienes una cuenta?{' '}
|
{t('auth.login.noAccount')}{' '}
|
||||||
<Link href="/auth/register" className="text-blue-600 hover:text-blue-500 font-medium">
|
<Link href="/auth/register" className="text-blue-600 hover:text-blue-500 font-medium">
|
||||||
Regístrate
|
{t('auth.login.signUp')}
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -3,9 +3,12 @@
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import { useI18n } from '@/lib/i18n/useI18n';
|
||||||
|
import { register } from '@/lib/api';
|
||||||
|
|
||||||
export default function Register() {
|
export default function Register() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const { t, isLoading } = useI18n();
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
username: '',
|
username: '',
|
||||||
email: '',
|
email: '',
|
||||||
|
@ -25,56 +28,52 @@ export default function Register() {
|
||||||
setError('');
|
setError('');
|
||||||
|
|
||||||
if (formData.password !== formData.confirmPassword) {
|
if (formData.password !== formData.confirmPassword) {
|
||||||
setError('Las contraseñas no coinciden');
|
setError(t('auth.errors.passwordMatch') || '');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (formData.password.length < 6) {
|
if (formData.password.length < 6) {
|
||||||
setError('La contraseña debe tener al menos 6 caracteres');
|
setError(t('auth.errors.passwordLength') || '');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const response = await fetch('/api/auth/register', {
|
const result = await register({
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
username: formData.username,
|
username: formData.username,
|
||||||
email: formData.email,
|
email: formData.email,
|
||||||
password: formData.password,
|
password: formData.password,
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
if (result.error) {
|
||||||
|
throw new Error(result.error || t('auth.errors.registerError'));
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(data.error || 'Error al registrar usuario');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
localStorage.setItem('token', data.token);
|
if (result.data?.token) {
|
||||||
|
localStorage.setItem('token', result.data.token);
|
||||||
router.push('/dashboard');
|
router.push('/dashboard');
|
||||||
|
}
|
||||||
} catch (err: unknown) {
|
} catch (err: unknown) {
|
||||||
if (err instanceof Error) {
|
if (err instanceof Error) {
|
||||||
setError(err.message);
|
setError(err.message);
|
||||||
} else {
|
} else {
|
||||||
setError('Ha ocurrido un error desconocido');
|
setError(t('auth.errors.unknownError') || '');
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (isLoading) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-100 flex items-center justify-center p-6">
|
<div className="min-h-screen bg-gray-100 flex items-center justify-center p-6">
|
||||||
<div className="max-w-md w-full mx-auto">
|
<div className="max-w-md w-full mx-auto">
|
||||||
<div className="bg-white shadow-sm rounded-lg overflow-hidden">
|
<div className="bg-white shadow-sm rounded-lg overflow-hidden">
|
||||||
<div className="px-8 pt-8 pb-6 border-b border-gray-200">
|
<div className="px-8 pt-8 pb-6 border-b border-gray-200">
|
||||||
<h2 className="text-2xl font-normal text-gray-800 mb-2">Crear cuenta</h2>
|
<h2 className="text-2xl font-normal text-gray-800 mb-2">{t('auth.register.title')}</h2>
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-gray-500">
|
||||||
Regístrate para comenzar a dibujar
|
{t('auth.register.subtitle')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -88,7 +87,7 @@ export default function Register() {
|
||||||
<form onSubmit={handleSubmit} className="space-y-4">
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
|
<label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
Nombre de usuario
|
{t('auth.register.username')}
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
id="username"
|
id="username"
|
||||||
|
@ -105,7 +104,7 @@ export default function Register() {
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
Correo electrónico
|
{t('auth.register.email')}
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
id="email"
|
id="email"
|
||||||
|
@ -122,7 +121,7 @@ export default function Register() {
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
Contraseña
|
{t('auth.register.password')}
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
id="password"
|
id="password"
|
||||||
|
@ -135,12 +134,12 @@ export default function Register() {
|
||||||
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-gray-400 focus:border-gray-400 text-sm"
|
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-gray-400 focus:border-gray-400 text-sm"
|
||||||
placeholder="••••••••"
|
placeholder="••••••••"
|
||||||
/>
|
/>
|
||||||
<p className="mt-1 text-xs text-gray-500">Mínimo 6 caracteres</p>
|
<p className="mt-1 text-xs text-gray-500">{t('auth.register.minChars')}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-1">
|
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
Confirmar contraseña
|
{t('auth.register.confirmPassword')}
|
||||||
</label>
|
</label>
|
||||||
<input
|
<input
|
||||||
id="confirmPassword"
|
id="confirmPassword"
|
||||||
|
@ -167,9 +166,9 @@ export default function Register() {
|
||||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
</svg>
|
</svg>
|
||||||
Creando cuenta...
|
{t('auth.register.buttonLoading')}
|
||||||
</>
|
</>
|
||||||
) : 'Crear cuenta'}
|
) : t('auth.register.button')}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
@ -177,9 +176,9 @@ export default function Register() {
|
||||||
|
|
||||||
<div className="px-8 py-4 bg-gray-50 border-t border-gray-200">
|
<div className="px-8 py-4 bg-gray-50 border-t border-gray-200">
|
||||||
<p className="text-sm text-center text-gray-600">
|
<p className="text-sm text-center text-gray-600">
|
||||||
¿Ya tienes una cuenta?{' '}
|
{t('auth.register.haveAccount')}{' '}
|
||||||
<Link href="/auth/login" className="text-blue-600 hover:text-blue-500 font-medium">
|
<Link href="/auth/login" className="text-blue-600 hover:text-blue-500 font-medium">
|
||||||
Inicia sesión
|
{t('auth.register.login')}
|
||||||
</Link>
|
</Link>
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
|
@ -1,6 +1,9 @@
|
||||||
import type { Metadata } from "next";
|
'use client';
|
||||||
|
|
||||||
import { Geist, Geist_Mono } from "next/font/google";
|
import { Geist, Geist_Mono } from "next/font/google";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
import { LanguageProvider } from "@/lib/i18n/language-context";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
const geistSans = Geist({
|
const geistSans = Geist({
|
||||||
variable: "--font-geist-sans",
|
variable: "--font-geist-sans",
|
||||||
|
@ -12,20 +15,29 @@ const geistMono = Geist_Mono({
|
||||||
subsets: ["latin"],
|
subsets: ["latin"],
|
||||||
});
|
});
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
|
||||||
title: "Excalidraw App",
|
|
||||||
description: "Una aplicación de dibujo con Excalidraw",
|
|
||||||
};
|
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
children,
|
children,
|
||||||
}: Readonly<{
|
}: Readonly<{
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}>) {
|
}>) {
|
||||||
|
const [language, setLanguage] = useState<string>('es');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const storedLanguage = localStorage.getItem('locale');
|
||||||
|
if (storedLanguage) {
|
||||||
|
setLanguage(storedLanguage);
|
||||||
|
} else {
|
||||||
|
const browserLang = navigator.language.split('-')[0];
|
||||||
|
setLanguage(['es', 'en'].includes(browserLang) ? browserLang : 'en');
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang={language}>
|
||||||
<body className={`${geistSans.variable} ${geistMono.variable}`}>
|
<body className={`${geistSans.variable} ${geistMono.variable}`}>
|
||||||
|
<LanguageProvider>
|
||||||
{children}
|
{children}
|
||||||
|
</LanguageProvider>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
|
|
@ -1,23 +1,32 @@
|
||||||
|
'use client';
|
||||||
|
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import LanguageSwitcher from '@/components/LanguageSwitcher';
|
||||||
|
import { useI18n } from '@/lib/i18n/useI18n';
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
|
const { t, isLoading } = useI18n();
|
||||||
|
|
||||||
|
if (isLoading) return null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-100 flex flex-col">
|
<div className="min-h-screen bg-gray-100 flex flex-col">
|
||||||
<header className="py-6 bg-white shadow-sm">
|
<header className="py-6 bg-white shadow-sm">
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex justify-between items-center">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex justify-between items-center">
|
||||||
<div className="font-medium text-lg text-gray-900">DrawApp</div>
|
<div className="font-medium text-lg text-gray-900">Draw</div>
|
||||||
<nav>
|
<nav className="flex items-center space-x-4">
|
||||||
|
<LanguageSwitcher />
|
||||||
<Link
|
<Link
|
||||||
href="/auth/login"
|
href="/auth/login"
|
||||||
className="text-sm text-gray-700 hover:text-gray-900 mr-4"
|
className="text-sm text-gray-700 hover:text-gray-900"
|
||||||
>
|
>
|
||||||
Iniciar sesión
|
{t('header.login')}
|
||||||
</Link>
|
</Link>
|
||||||
<Link
|
<Link
|
||||||
href="/auth/register"
|
href="/auth/register"
|
||||||
className="text-sm bg-blue-600 text-white py-2 px-3 rounded-md hover:bg-blue-700"
|
className="text-sm bg-blue-600 text-white py-2 px-3 rounded-md hover:bg-blue-700"
|
||||||
>
|
>
|
||||||
Registrarse
|
{t('header.register')}
|
||||||
</Link>
|
</Link>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
|
@ -27,23 +36,23 @@ export default function Home() {
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 flex flex-col lg:flex-row items-center">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 flex flex-col lg:flex-row items-center">
|
||||||
<div className="lg:w-1/2 lg:pr-12 mb-10 lg:mb-0">
|
<div className="lg:w-1/2 lg:pr-12 mb-10 lg:mb-0">
|
||||||
<h1 className="text-4xl font-bold text-gray-900 mb-6">
|
<h1 className="text-4xl font-bold text-gray-900 mb-6">
|
||||||
Dibuja lo que imagines
|
{t('home.title')}
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-xl text-gray-600 mb-8">
|
<p className="text-xl text-gray-600 mb-8">
|
||||||
Una aplicación simple y poderosa para expresar tu creatividad mediante dibujos digitales.
|
{t('home.description')}
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-col sm:flex-row space-y-3 sm:space-y-0 sm:space-x-4">
|
<div className="flex flex-col sm:flex-row space-y-3 sm:space-y-0 sm:space-x-4">
|
||||||
<Link
|
<Link
|
||||||
href="/auth/register"
|
href="/auth/register"
|
||||||
className="inline-flex justify-center items-center px-6 py-3 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
|
className="inline-flex justify-center items-center px-6 py-3 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
|
||||||
>
|
>
|
||||||
Comenzar gratis
|
{t('home.startFree')}
|
||||||
</Link>
|
</Link>
|
||||||
<Link
|
<Link
|
||||||
href="/about"
|
href="/about"
|
||||||
className="inline-flex justify-center items-center px-6 py-3 border border-gray-300 rounded-md shadow-sm text-base font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
|
className="inline-flex justify-center items-center px-6 py-3 border border-gray-300 rounded-md shadow-sm text-base font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
|
||||||
>
|
>
|
||||||
Conocer más
|
{t('home.learnMore')}
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -60,7 +69,7 @@ export default function Home() {
|
||||||
<footer className="bg-white border-t border-gray-200 py-8">
|
<footer className="bg-white border-t border-gray-200 py-8">
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
<p className="text-sm text-gray-500 text-center">
|
<p className="text-sm text-gray-500 text-center">
|
||||||
© 2023 DrawApp. Todos los derechos reservados.
|
{t('footer.copyright')}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
|
@ -0,0 +1,64 @@
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useLanguage } from '@/lib/i18n/language-context';
|
||||||
|
import { locales } from '@/lib/i18n/i18n-config';
|
||||||
|
import { useState, useRef, useEffect } from 'react';
|
||||||
|
import { useI18n } from '@/lib/i18n/useI18n';
|
||||||
|
|
||||||
|
export default function LanguageSwitcher() {
|
||||||
|
const { locale, setLocale } = useLanguage();
|
||||||
|
const { t, isLoading } = useI18n();
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
|
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener('mousedown', handleClickOutside);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (isLoading) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative" ref={dropdownRef}>
|
||||||
|
<button
|
||||||
|
onClick={() => setIsOpen(!isOpen)}
|
||||||
|
className="flex items-center gap-1.5 text-sm text-gray-600 hover:text-gray-900"
|
||||||
|
>
|
||||||
|
<span className="uppercase">{locale}</span>
|
||||||
|
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||||
|
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{isOpen && (
|
||||||
|
<div className="absolute right-0 mt-2 w-40 bg-white rounded-md shadow-lg py-1 z-10">
|
||||||
|
<div className="px-3 py-2 text-xs font-medium text-gray-500">
|
||||||
|
{t('language.select')}
|
||||||
|
</div>
|
||||||
|
{locales.map((lang) => (
|
||||||
|
<button
|
||||||
|
key={lang}
|
||||||
|
onClick={() => {
|
||||||
|
setLocale(lang);
|
||||||
|
setIsOpen(false);
|
||||||
|
}}
|
||||||
|
className={`block w-full text-left px-4 py-2 text-sm hover:bg-gray-100 ${
|
||||||
|
locale === lang ? 'text-blue-600 font-medium' : 'text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{t(`language.${lang}`)}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
|
@ -1,4 +1,3 @@
|
||||||
import { NextApiRequest, NextApiResponse } from "next";
|
|
||||||
import bcrypt from "bcryptjs";
|
import bcrypt from "bcryptjs";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
import User from "../models/User";
|
import User from "../models/User";
|
||||||
|
@ -46,38 +45,6 @@ export async function register(data: {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function login(req: NextApiRequest, res: NextApiResponse) {
|
|
||||||
try {
|
|
||||||
await dbConnect();
|
|
||||||
const { email, password } = req.body;
|
|
||||||
|
|
||||||
const user = await User.findOne({ email });
|
|
||||||
if (!user) {
|
|
||||||
return res.status(401).json({ error: "Invalid credentials" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const isValidPassword = await bcrypt.compare(password, user.password);
|
|
||||||
if (!isValidPassword) {
|
|
||||||
return res.status(401).json({ error: "Invalid credentials" });
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = jwt.sign({ userId: user._id }, JWT_SECRET, {
|
|
||||||
expiresIn: "7d",
|
|
||||||
});
|
|
||||||
|
|
||||||
return res.status(200).json({
|
|
||||||
token,
|
|
||||||
user: {
|
|
||||||
id: user._id,
|
|
||||||
username: user.username,
|
|
||||||
email: user.email,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch {
|
|
||||||
return res.status(500).json({ error: "Internal server error" });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loginUser(data: { email: string; password: string }) {
|
export async function loginUser(data: { email: string; password: string }) {
|
||||||
try {
|
try {
|
||||||
await dbConnect();
|
await dbConnect();
|
||||||
|
|
|
@ -0,0 +1,101 @@
|
||||||
|
interface LoginRequest {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RegisterRequest {
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ApiResponse<T> {
|
||||||
|
data?: T;
|
||||||
|
error?: string;
|
||||||
|
status: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UserProfile {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
email: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthResponse {
|
||||||
|
token: string;
|
||||||
|
user: UserProfile;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchApi<T, R>(
|
||||||
|
endpoint: string,
|
||||||
|
method: string = "GET",
|
||||||
|
body?: T,
|
||||||
|
headers?: Record<string, string>
|
||||||
|
): Promise<ApiResponse<R>> {
|
||||||
|
try {
|
||||||
|
const requestHeaders = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
...headers,
|
||||||
|
};
|
||||||
|
|
||||||
|
const config: RequestInit = {
|
||||||
|
method,
|
||||||
|
headers: requestHeaders,
|
||||||
|
body: body ? JSON.stringify(body) : undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await fetch(`/api${endpoint}`, config);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
return {
|
||||||
|
data: response.ok ? data : undefined,
|
||||||
|
error: !response.ok ? data.error || "Error en la petición" : undefined,
|
||||||
|
status: response.status,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error("API request error:", error);
|
||||||
|
return {
|
||||||
|
error: error instanceof Error ? error.message : "Error desconocido",
|
||||||
|
status: 500,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function login(
|
||||||
|
credentials: LoginRequest
|
||||||
|
): Promise<ApiResponse<AuthResponse>> {
|
||||||
|
return fetchApi<LoginRequest, AuthResponse>(
|
||||||
|
"/auth/login",
|
||||||
|
"POST",
|
||||||
|
credentials
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function register(
|
||||||
|
userData: RegisterRequest
|
||||||
|
): Promise<ApiResponse<AuthResponse>> {
|
||||||
|
return fetchApi<RegisterRequest, AuthResponse>(
|
||||||
|
"/auth/register",
|
||||||
|
"POST",
|
||||||
|
userData
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getProfile(): Promise<ApiResponse<UserProfile>> {
|
||||||
|
const token = localStorage.getItem("token");
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return {
|
||||||
|
error: "No hay token de autenticación",
|
||||||
|
status: 401,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetchApi<undefined, UserProfile>("/user/profile", "GET", undefined, {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function logout(): Promise<void> {
|
||||||
|
localStorage.removeItem("token");
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
export const defaultLocale = "en";
|
||||||
|
export const locales = ["en", "es"];
|
||||||
|
|
||||||
|
export function getOptions(lng = defaultLocale, ns = "common") {
|
||||||
|
return {
|
||||||
|
supportedLngs: locales,
|
||||||
|
fallbackLng: defaultLocale,
|
||||||
|
lng,
|
||||||
|
ns,
|
||||||
|
defaultNS: "common",
|
||||||
|
fallbackNS: "common",
|
||||||
|
};
|
||||||
|
}
|
|
@ -0,0 +1,67 @@
|
||||||
|
import { createInstance, i18n } from "i18next";
|
||||||
|
import { initReactI18next } from "react-i18next";
|
||||||
|
import resourcesToBackend from "i18next-resources-to-backend";
|
||||||
|
import { getOptions } from "./i18n-config";
|
||||||
|
|
||||||
|
// Caché para las instancias de i18next por idioma y namespace
|
||||||
|
const i18nInstancesCache: Record<string, i18n> = {};
|
||||||
|
|
||||||
|
const initI18next = async (lng: string, ns: string) => {
|
||||||
|
const cacheKey = `${lng}:${ns}`;
|
||||||
|
|
||||||
|
// Si ya existe en caché, devolver la instancia existente
|
||||||
|
if (i18nInstancesCache[cacheKey]) {
|
||||||
|
return i18nInstancesCache[cacheKey];
|
||||||
|
}
|
||||||
|
|
||||||
|
const i18nInstance = createInstance();
|
||||||
|
await i18nInstance
|
||||||
|
.use(initReactI18next)
|
||||||
|
.use(
|
||||||
|
resourcesToBackend(
|
||||||
|
(language: string, namespace: string) =>
|
||||||
|
import(`../../public/locales/${language}/${namespace}.json`)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.init(getOptions(lng, ns));
|
||||||
|
|
||||||
|
// Guardar en caché
|
||||||
|
i18nInstancesCache[cacheKey] = i18nInstance;
|
||||||
|
|
||||||
|
return i18nInstance;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Tipo para la función de traducción
|
||||||
|
export type TranslationFunction = (key: string) => string | undefined;
|
||||||
|
|
||||||
|
// Tipo para el objeto de traducción cacheado
|
||||||
|
interface CachedTranslation {
|
||||||
|
t: TranslationFunction;
|
||||||
|
i18n: i18n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Caché para las funciones de traducción
|
||||||
|
const translationCache: Record<string, CachedTranslation> = {};
|
||||||
|
|
||||||
|
export async function getTranslation(
|
||||||
|
lng: string,
|
||||||
|
ns: string = "common"
|
||||||
|
): Promise<CachedTranslation> {
|
||||||
|
const cacheKey = `${lng}:${ns}`;
|
||||||
|
|
||||||
|
// Si ya existe en caché, devolver la función de traducción existente
|
||||||
|
if (translationCache[cacheKey]) {
|
||||||
|
return translationCache[cacheKey];
|
||||||
|
}
|
||||||
|
|
||||||
|
const i18nextInstance = await initI18next(lng, ns);
|
||||||
|
const translation: CachedTranslation = {
|
||||||
|
t: i18nextInstance.getFixedT(lng, ns),
|
||||||
|
i18n: i18nextInstance,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Guardar en caché
|
||||||
|
translationCache[cacheKey] = translation;
|
||||||
|
|
||||||
|
return translation;
|
||||||
|
}
|
|
@ -0,0 +1,50 @@
|
||||||
|
'use client';
|
||||||
|
|
||||||
|
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||||
|
import { locales, defaultLocale } from './i18n-config';
|
||||||
|
|
||||||
|
type LanguageContextType = {
|
||||||
|
locale: string;
|
||||||
|
setLocale: (locale: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LanguageContext = createContext<LanguageContextType | null>(null);
|
||||||
|
|
||||||
|
export function LanguageProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [locale, setLocale] = useState<string>(defaultLocale);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const storedLocale = localStorage.getItem('locale');
|
||||||
|
|
||||||
|
if (storedLocale && locales.includes(storedLocale)) {
|
||||||
|
setLocale(storedLocale);
|
||||||
|
} else {
|
||||||
|
const browserLocale = navigator.language.split('-')[0];
|
||||||
|
const newLocale = locales.includes(browserLocale) ? browserLocale : defaultLocale;
|
||||||
|
setLocale(newLocale);
|
||||||
|
localStorage.setItem('locale', newLocale);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleSetLocale = (newLocale: string) => {
|
||||||
|
if (locales.includes(newLocale)) {
|
||||||
|
setLocale(newLocale);
|
||||||
|
localStorage.setItem('locale', newLocale);
|
||||||
|
window.location.reload();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<LanguageContext.Provider value={{ locale, setLocale: handleSetLocale }}>
|
||||||
|
{children}
|
||||||
|
</LanguageContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useLanguage() {
|
||||||
|
const context = useContext(LanguageContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useLanguage must be used within a LanguageProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { useLanguage } from "./language-context";
|
||||||
|
import { getTranslation } from "./i18n";
|
||||||
|
|
||||||
|
export function useI18n() {
|
||||||
|
const { locale } = useLanguage();
|
||||||
|
const [t, setT] = useState<(key: string) => string | undefined>(null!);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let isMounted = true;
|
||||||
|
|
||||||
|
const loadTranslations = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const translation = await getTranslation(locale);
|
||||||
|
if (isMounted) {
|
||||||
|
setT(() => translation.t);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error loading translations:", error);
|
||||||
|
} finally {
|
||||||
|
if (isMounted) {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadTranslations();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isMounted = false;
|
||||||
|
};
|
||||||
|
}, [locale]);
|
||||||
|
|
||||||
|
return { t, isLoading, locale };
|
||||||
|
}
|
36
yarn.lock
36
yarn.lock
|
@ -15,7 +15,7 @@
|
||||||
"@jridgewell/gen-mapping" "^0.3.5"
|
"@jridgewell/gen-mapping" "^0.3.5"
|
||||||
"@jridgewell/trace-mapping" "^0.3.24"
|
"@jridgewell/trace-mapping" "^0.3.24"
|
||||||
|
|
||||||
"@babel/runtime@^7.13.10":
|
"@babel/runtime@^7.13.10", "@babel/runtime@^7.23.2", "@babel/runtime@^7.25.0", "@babel/runtime@^7.26.10":
|
||||||
version "7.27.1"
|
version "7.27.1"
|
||||||
resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.1.tgz"
|
resolved "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.1.tgz"
|
||||||
integrity sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog==
|
integrity sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog==
|
||||||
|
@ -2931,6 +2931,13 @@ hasown@^2.0.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
function-bind "^1.1.2"
|
function-bind "^1.1.2"
|
||||||
|
|
||||||
|
html-parse-stringify@^3.0.1:
|
||||||
|
version "3.0.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz#dfc1017347ce9f77c8141a507f233040c59c55d2"
|
||||||
|
integrity sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==
|
||||||
|
dependencies:
|
||||||
|
void-elements "3.1.0"
|
||||||
|
|
||||||
http-errors@2.0.0, http-errors@^2.0.0:
|
http-errors@2.0.0, http-errors@^2.0.0:
|
||||||
version "2.0.0"
|
version "2.0.0"
|
||||||
resolved "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz"
|
resolved "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz"
|
||||||
|
@ -2942,6 +2949,20 @@ http-errors@2.0.0, http-errors@^2.0.0:
|
||||||
statuses "2.0.1"
|
statuses "2.0.1"
|
||||||
toidentifier "1.0.1"
|
toidentifier "1.0.1"
|
||||||
|
|
||||||
|
i18next-resources-to-backend@^1.2.1:
|
||||||
|
version "1.2.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/i18next-resources-to-backend/-/i18next-resources-to-backend-1.2.1.tgz#fded121e63e3139ce839c9901b9449dbbea7351d"
|
||||||
|
integrity sha512-okHbVA+HZ7n1/76MsfhPqDou0fptl2dAlhRDu2ideXloRRduzHsqDOznJBef+R3DFZnbvWoBW+KxJ7fnFjd6Yw==
|
||||||
|
dependencies:
|
||||||
|
"@babel/runtime" "^7.23.2"
|
||||||
|
|
||||||
|
i18next@^25.1.2:
|
||||||
|
version "25.1.2"
|
||||||
|
resolved "https://registry.yarnpkg.com/i18next/-/i18next-25.1.2.tgz#c667b814ed1b4dbea76976a4c746a87922ac6ceb"
|
||||||
|
integrity sha512-SP63m8LzdjkrAjruH7SCI3ndPSgjt4/wX7ouUUOzCW/eY+HzlIo19IQSfYA9X3qRiRP1SYtaTsg/Oz/PGsfD8w==
|
||||||
|
dependencies:
|
||||||
|
"@babel/runtime" "^7.26.10"
|
||||||
|
|
||||||
iconv-lite@0.6, iconv-lite@0.6.3, iconv-lite@^0.6.3:
|
iconv-lite@0.6, iconv-lite@0.6.3, iconv-lite@^0.6.3:
|
||||||
version "0.6.3"
|
version "0.6.3"
|
||||||
resolved "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz"
|
resolved "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz"
|
||||||
|
@ -4425,6 +4446,14 @@ react-dom@^19.0.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
scheduler "^0.26.0"
|
scheduler "^0.26.0"
|
||||||
|
|
||||||
|
react-i18next@^15.5.1:
|
||||||
|
version "15.5.1"
|
||||||
|
resolved "https://registry.yarnpkg.com/react-i18next/-/react-i18next-15.5.1.tgz#ceada755a0b6691432b6b6dc5dad454fd3d158e3"
|
||||||
|
integrity sha512-C8RZ7N7H0L+flitiX6ASjq9p5puVJU1Z8VyL3OgM/QOMRf40BMZX+5TkpxzZVcTmOLPX5zlti4InEX5pFyiVeA==
|
||||||
|
dependencies:
|
||||||
|
"@babel/runtime" "^7.25.0"
|
||||||
|
html-parse-stringify "^3.0.1"
|
||||||
|
|
||||||
react-is@^16.13.1:
|
react-is@^16.13.1:
|
||||||
version "16.13.1"
|
version "16.13.1"
|
||||||
resolved "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz"
|
resolved "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz"
|
||||||
|
@ -5305,6 +5334,11 @@ vary@^1, vary@^1.1.2:
|
||||||
resolved "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz"
|
resolved "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz"
|
||||||
integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==
|
integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==
|
||||||
|
|
||||||
|
void-elements@3.1.0:
|
||||||
|
version "3.1.0"
|
||||||
|
resolved "https://registry.yarnpkg.com/void-elements/-/void-elements-3.1.0.tgz#614f7fbf8d801f0bb5f0661f5b2f5785750e4f09"
|
||||||
|
integrity sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==
|
||||||
|
|
||||||
web-worker@^1.2.0:
|
web-worker@^1.2.0:
|
||||||
version "1.5.0"
|
version "1.5.0"
|
||||||
resolved "https://registry.npmjs.org/web-worker/-/web-worker-1.5.0.tgz"
|
resolved "https://registry.npmjs.org/web-worker/-/web-worker-1.5.0.tgz"
|
||||||
|
|
Loading…
Reference in New Issue
Block a user