pin_forgot.html 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. <!DOCTYPE html>
  2. <html lang="es">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Recuperar PIN - Biergarten Klein</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <!-- Meta tags para evitar cache -->
  8. <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
  9. <meta http-equiv="Pragma" content="no-cache">
  10. <meta http-equiv="Expires" content="0">
  11. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  12. <link rel="stylesheet" as="style" onload="this.rel='stylesheet'"
  13. href="https://fonts.googleapis.com/css2?display=swap&family=Noto+Sans:wght@400;500;700;900&family=Spline+Sans:wght@400;500;700">
  14. <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
  15. <script>
  16. tailwind.config = {
  17. theme: {
  18. extend: {
  19. colors: {
  20. 'custom-dark': '#101419',
  21. 'custom-dark-hover': '#37404a',
  22. 'gray-50': '#f9fafb',
  23. 'gray-100': '#f3f4f6',
  24. }
  25. }
  26. }
  27. }
  28. </script>
  29. </head>
  30. <body class="min-h-screen bg-gray-50 flex items-center justify-center p-4" style='font-family:"Spline Sans","Noto Sans",sans-serif;'>
  31. <div class="w-full max-w-md">
  32. <!-- Header -->
  33. <div class="text-center mb-8">
  34. <div class="inline-flex items-center justify-center w-16 h-16 bg-[#101419] rounded-full mb-4">
  35. <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  36. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
  37. </svg>
  38. </div>
  39. <h1 class="text-[26px] font-bold text-[#101419] tracking-tight mb-2">
  40. ¿Olvidaste tu PIN?
  41. </h1>
  42. <p class="text-[#58728d] text-sm leading-relaxed">
  43. No te preocupes, te ayudamos a recuperar el acceso a tu cuenta
  44. </p>
  45. </div>
  46. <!-- Indicador de pasos -->
  47. <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-6">
  48. <div class="space-y-4">
  49. <div class="flex items-start space-x-3" id="step1Indicator">
  50. <div class="flex-shrink-0 w-6 h-6 bg-[#101419] text-white rounded-full flex items-center justify-center text-xs font-medium">1</div>
  51. <div class="text-sm">
  52. <p class="font-medium text-[#101419]">Ingresa tu correo</p>
  53. <p class="text-[#58728d] mt-1">Te enviaremos un código de verificación</p>
  54. </div>
  55. </div>
  56. <div class="flex items-start space-x-3" id="step2Indicator">
  57. <div class="flex-shrink-0 w-6 h-6 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-xs font-medium">2</div>
  58. <div class="text-sm">
  59. <p class="font-medium text-gray-400">Código de verificación</p>
  60. <p class="text-gray-400 mt-1">Ingresa el código de 6 dígitos</p>
  61. </div>
  62. </div>
  63. <div class="flex items-start space-x-3" id="step3Indicator">
  64. <div class="flex-shrink-0 w-6 h-6 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-xs font-medium">3</div>
  65. <div class="text-sm">
  66. <p class="font-medium text-gray-400">Nuevo PIN</p>
  67. <p class="text-gray-400 mt-1">Crea tu nuevo PIN de 4 dígitos</p>
  68. </div>
  69. </div>
  70. </div>
  71. </div>
  72. <!-- FASE 1: Ingreso de correo -->
  73. <form id="emailForm" class="bg-white rounded-xl shadow-sm border border-gray-200 p-8 space-y-6">
  74. <div class="text-center">
  75. <h2 class="text-[19px] font-bold text-[#101419] mb-2">Ingresa tu correo electrónico</h2>
  76. <p class="text-sm text-[#58728d]">
  77. Te enviaremos un código de verificación a tu correo
  78. </p>
  79. </div>
  80. <div class="space-y-4">
  81. <div>
  82. <label for="emailInput" class="block text-sm font-medium text-[#101419] mb-2">
  83. Correo electrónico
  84. </label>
  85. <input
  86. id="emailInput"
  87. name="email"
  88. type="email"
  89. class="w-full border border-gray-300 px-4 py-3 rounded-lg focus:ring-2 focus:ring-[#101419] focus:border-transparent outline-none transition-all"
  90. placeholder="tu@email.com"
  91. required
  92. />
  93. </div>
  94. </div>
  95. <div class="space-y-3">
  96. <button
  97. id="emailSubmitBtn"
  98. type="submit"
  99. class="w-full bg-[#101419] hover:bg-[#37404a] disabled:opacity-50 disabled:cursor-not-allowed text-white py-3 rounded-lg font-medium transition-colors duration-200 focus:ring-2 focus:ring-offset-2 focus:ring-[#101419]"
  100. >
  101. Enviar código
  102. </button>
  103. <a
  104. href="/"
  105. class="block w-full text-center border border-gray-300 hover:border-[#101419] text-[#101419] py-3 rounded-lg font-medium transition-colors duration-200"
  106. >
  107. Volver al inicio
  108. </a>
  109. </div>
  110. </form>
  111. <!-- FASE 2: Verificación de código -->
  112. <form id="codeForm" class="bg-white rounded-xl shadow-sm border border-gray-200 p-8 space-y-6 hidden">
  113. <div class="text-center">
  114. <h2 class="text-[19px] font-bold text-[#101419] mb-2">Código de verificación</h2>
  115. <p class="text-sm text-[#58728d]">
  116. Ingresa el código de 6 dígitos que enviamos a <span id="emailDisplay" class="font-medium"></span>
  117. </p>
  118. </div>
  119. <div class="space-y-4">
  120. <div>
  121. <label for="codeInput" class="block text-sm font-medium text-[#101419] mb-2">
  122. Código de verificación
  123. </label>
  124. <input
  125. id="codeInput"
  126. name="code"
  127. type="text"
  128. maxlength="6"
  129. class="w-full border border-gray-300 px-4 py-3 rounded-lg focus:ring-2 focus:ring-[#101419] focus:border-transparent outline-none transition-all text-center text-2xl tracking-widest"
  130. placeholder="000000"
  131. required
  132. />
  133. </div>
  134. <div class="text-center">
  135. <button
  136. type="button"
  137. id="resendCodeBtn"
  138. class="text-sm text-[#58728d] hover:text-[#101419] transition-colors disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:text-[#58728d]"
  139. >
  140. ¿No recibiste el código? <span class="font-medium" id="resendText">Reenviar</span>
  141. </button>
  142. </div>
  143. </div>
  144. <div class="space-y-3">
  145. <button
  146. id="codeSubmitBtn"
  147. type="submit"
  148. class="w-full bg-[#101419] hover:bg-[#37404a] disabled:opacity-50 disabled:cursor-not-allowed text-white py-3 rounded-lg font-medium transition-colors duration-200 focus:ring-2 focus:ring-offset-2 focus:ring-[#101419]"
  149. >
  150. Verificar código
  151. </button>
  152. <button
  153. type="button"
  154. id="backToEmailBtn"
  155. class="block w-full text-center border border-gray-300 hover:border-[#101419] text-[#101419] py-3 rounded-lg font-medium transition-colors duration-200"
  156. >
  157. Cambiar correo
  158. </button>
  159. </div>
  160. </form>
  161. <!-- FASE 3: Crear nuevo PIN -->
  162. <form id="pinForm" class="bg-white rounded-xl shadow-sm border border-gray-200 p-8 space-y-6 hidden">
  163. <div class="text-center">
  164. <h2 class="text-[19px] font-bold text-[#101419] mb-2">Crea tu nuevo PIN</h2>
  165. <p class="text-sm text-[#58728d]">
  166. Ingresa un PIN de 4 dígitos que sea fácil de recordar para ti
  167. </p>
  168. </div>
  169. <div class="space-y-4">
  170. <div>
  171. <label for="newPinInput" class="block text-sm font-medium text-[#101419] mb-2">
  172. Nuevo PIN
  173. </label>
  174. <input
  175. id="newPinInput"
  176. name="newPin"
  177. type="password"
  178. maxlength="4"
  179. class="w-full border border-gray-300 px-4 py-3 rounded-lg focus:ring-2 focus:ring-[#101419] focus:border-transparent outline-none transition-all text-center text-2xl tracking-widest"
  180. placeholder="••••"
  181. required
  182. />
  183. </div>
  184. <div>
  185. <label for="confirmPinInput" class="block text-sm font-medium text-[#101419] mb-2">
  186. Confirmar PIN
  187. </label>
  188. <input
  189. id="confirmPinInput"
  190. name="confirmPin"
  191. type="password"
  192. maxlength="4"
  193. class="w-full border border-gray-300 px-4 py-3 rounded-lg focus:ring-2 focus:ring-[#101419] focus:border-transparent outline-none transition-all text-center text-2xl tracking-widest"
  194. placeholder="••••"
  195. required
  196. />
  197. </div>
  198. <div class="bg-blue-50 border border-blue-200 text-blue-800 px-4 py-3 rounded-lg text-sm">
  199. <div class="flex items-start space-x-2">
  200. <svg class="w-4 h-4 mt-0.5 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
  201. <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"/>
  202. </svg>
  203. <p>Recuerda elegir un PIN que sea seguro pero fácil de recordar. Evita fechas obvias como tu cumpleaños.</p>
  204. </div>
  205. </div>
  206. </div>
  207. <div class="space-y-3">
  208. <button
  209. id="pinSubmitBtn"
  210. type="submit"
  211. class="w-full bg-[#101419] hover:bg-[#37404a] disabled:opacity-50 disabled:cursor-not-allowed text-white py-3 rounded-lg font-medium transition-colors duration-200 focus:ring-2 focus:ring-offset-2 focus:ring-[#101419]"
  212. >
  213. Establecer nuevo PIN
  214. </button>
  215. </div>
  216. </form>
  217. <!-- Mensaje de error global -->
  218. <div id="errorMessage" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg text-sm mt-4">
  219. </div>
  220. <!-- Mensaje de éxito -->
  221. <div id="successMessage" class="hidden bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg text-sm mt-4">
  222. </div>
  223. </div>
  224. <script>
  225. // Variables globales
  226. let currentStep = 1;
  227. let userEmail = '';
  228. let verificationCode = '';
  229. let resendTimer = null;
  230. let resendCountdown = 0;
  231. let changeToken = '';
  232. // Referencias a elementos del DOM
  233. const emailForm = document.getElementById('emailForm');
  234. const codeForm = document.getElementById('codeForm');
  235. const pinForm = document.getElementById('pinForm');
  236. const emailInput = document.getElementById('emailInput');
  237. const codeInput = document.getElementById('codeInput');
  238. const newPinInput = document.getElementById('newPinInput');
  239. const confirmPinInput = document.getElementById('confirmPinInput');
  240. const emailSubmitBtn = document.getElementById('emailSubmitBtn');
  241. const codeSubmitBtn = document.getElementById('codeSubmitBtn');
  242. const pinSubmitBtn = document.getElementById('pinSubmitBtn');
  243. const backToEmailBtn = document.getElementById('backToEmailBtn');
  244. const resendCodeBtn = document.getElementById('resendCodeBtn');
  245. const resendText = document.getElementById('resendText');
  246. const errorMessage = document.getElementById('errorMessage');
  247. const successMessage = document.getElementById('successMessage');
  248. const emailDisplay = document.getElementById('emailDisplay');
  249. // Indicadores de pasos
  250. const step1Indicator = document.getElementById('step1Indicator');
  251. const step2Indicator = document.getElementById('step2Indicator');
  252. const step3Indicator = document.getElementById('step3Indicator');
  253. // Inicialización
  254. emailInput.focus();
  255. // Funciones de utilidad
  256. function showError(message) {
  257. errorMessage.textContent = message;
  258. errorMessage.classList.remove('hidden');
  259. successMessage.classList.add('hidden');
  260. }
  261. function showSuccess(message) {
  262. successMessage.textContent = message;
  263. successMessage.classList.remove('hidden');
  264. errorMessage.classList.add('hidden');
  265. }
  266. function hideMessages() {
  267. errorMessage.classList.add('hidden');
  268. successMessage.classList.add('hidden');
  269. }
  270. function updateStepIndicators() {
  271. // Resetear todos los indicadores
  272. [step1Indicator, step2Indicator, step3Indicator].forEach((step, index) => {
  273. const circle = step.querySelector('.w-6');
  274. const texts = step.querySelectorAll('p');
  275. if (index + 1 < currentStep) {
  276. // Paso completado
  277. circle.className = 'flex-shrink-0 w-6 h-6 bg-green-500 text-white rounded-full flex items-center justify-center text-xs font-medium';
  278. circle.innerHTML = '✓';
  279. texts.forEach(text => {
  280. text.className = text.className.replace('text-gray-400', 'text-green-600');
  281. text.className = text.className.replace('text-[#58728d]', 'text-green-600');
  282. });
  283. } else if (index + 1 === currentStep) {
  284. // Paso actual
  285. circle.className = 'flex-shrink-0 w-6 h-6 bg-[#101419] text-white rounded-full flex items-center justify-center text-xs font-medium';
  286. circle.textContent = index + 1;
  287. texts.forEach(text => {
  288. text.className = text.className.replace('text-gray-400', 'text-[#101419]');
  289. if (text.className.includes('font-medium')) {
  290. text.className = text.className.replace('text-gray-400', 'text-[#101419]');
  291. } else {
  292. text.className = text.className.replace('text-gray-400', 'text-[#58728d]');
  293. }
  294. });
  295. } else {
  296. // Paso pendiente
  297. circle.className = 'flex-shrink-0 w-6 h-6 bg-gray-300 text-gray-600 rounded-full flex items-center justify-center text-xs font-medium';
  298. circle.textContent = index + 1;
  299. texts.forEach(text => {
  300. text.className = text.className.replace('text-[#101419]', 'text-gray-400');
  301. text.className = text.className.replace('text-[#58728d]', 'text-gray-400');
  302. text.className = text.className.replace('text-green-600', 'text-gray-400');
  303. });
  304. }
  305. });
  306. }
  307. function showStep(step) {
  308. // Ocultar todos los formularios
  309. emailForm.classList.add('hidden');
  310. codeForm.classList.add('hidden');
  311. pinForm.classList.add('hidden');
  312. // Detener timer si cambia de paso
  313. if (step !== 2) {
  314. stopResendTimer();
  315. }
  316. // Mostrar el formulario correspondiente
  317. switch(step) {
  318. case 1:
  319. emailForm.classList.remove('hidden');
  320. emailInput.focus();
  321. break;
  322. case 2:
  323. codeForm.classList.remove('hidden');
  324. codeInput.focus();
  325. break;
  326. case 3:
  327. pinForm.classList.remove('hidden');
  328. newPinInput.focus();
  329. break;
  330. }
  331. currentStep = step;
  332. updateStepIndicators();
  333. hideMessages();
  334. }
  335. function generateVerificationCode() {
  336. return Math.floor(100000 + Math.random() * 900000).toString();
  337. }
  338. function startResendTimer() {
  339. resendCountdown = 60; // 1 minuto
  340. resendCodeBtn.disabled = true;
  341. resendTimer = setInterval(() => {
  342. if (resendCountdown > 0) {
  343. resendText.textContent = `Reenviar (${resendCountdown}s)`;
  344. resendCountdown--;
  345. } else {
  346. clearInterval(resendTimer);
  347. resendCodeBtn.disabled = false;
  348. resendText.textContent = 'Reenviar';
  349. }
  350. }, 1000);
  351. }
  352. async function sendMail(){
  353. const codeVerify = await fetch('/recovery/validate', {
  354. method: 'POST',
  355. headers: {
  356. 'Content-Type': 'application/json'
  357. },
  358. body: JSON.stringify({ email: userEmail, code })
  359. });
  360. switch (codeVerify.status) {
  361. case 200:
  362. showSuccess('Código verificado correctamente');
  363. setTimeout(async () => {
  364. data = await codeVerify.json();
  365. changeToken = data.token;
  366. showStep(3);
  367. }, 1000);
  368. break;
  369. case 404:
  370. showError('Usuario no encontrado. Por favor verifica e intenta nuevamente.');
  371. codeInput.focus();
  372. codeInput.select();
  373. return;
  374. case 400:
  375. showError('Código incorrecto. Por favor verifica e intenta nuevamente.');
  376. codeInput.focus();
  377. codeInput.select();
  378. return;
  379. default:
  380. return;
  381. }
  382. codeSubmitBtn.disabled = false;
  383. codeSubmitBtn.textContent = 'Verificar código';
  384. }
  385. function stopResendTimer() {
  386. if (resendTimer) {
  387. clearInterval(resendTimer);
  388. resendTimer = null;
  389. }
  390. resendCountdown = 0;
  391. resendCodeBtn.disabled = false;
  392. resendText.textContent = 'Reenviar';
  393. }
  394. // FASE 1: Envío de correo
  395. emailForm.addEventListener('submit', async function(e) {
  396. e.preventDefault();
  397. const email = emailInput.value.trim();
  398. if (!email) {
  399. showError('Por favor ingresa tu correo electrónico');
  400. emailInput.focus();
  401. return;
  402. }
  403. if (!isValidEmail(email)) {
  404. showError('Por favor ingresa un correo electrónico válido');
  405. emailInput.focus();
  406. return;
  407. }
  408. emailSubmitBtn.disabled = true;
  409. emailSubmitBtn.textContent = 'Enviando código...';
  410. userEmail = email;
  411. emailDisplay.textContent = email;
  412. const body = JSON.stringify({ email })
  413. // En una aplicación real, aquí enviarías el código por email
  414. const emailResponse = await fetch('/recovery', {
  415. method: 'POST',
  416. headers: {
  417. 'Content-Type': 'application/json'
  418. },
  419. body: body
  420. });
  421. if (!emailResponse.ok) {
  422. showError(emailResponse.message || 'Error al enviar el código. Por favor intenta nuevamente.');
  423. emailInput.focus();
  424. return;
  425. }
  426. showSuccess(`Código enviado a ${email}`);
  427. setTimeout(() => {
  428. showStep(2);
  429. startResendTimer(); // Iniciar el timer cuando se muestra la fase 2
  430. }, 400);
  431. emailSubmitBtn.disabled = false;
  432. emailSubmitBtn.textContent = 'Enviar código';
  433. });
  434. // FASE 2: Verificación de código
  435. codeForm.addEventListener('submit',async function(e) {
  436. e.preventDefault();
  437. const code = codeInput.value.trim();
  438. if (!code || code.length !== 6) {
  439. showError('Por favor ingresa el código de 6 dígitos');
  440. codeInput.focus();
  441. return;
  442. }
  443. if (!/^\d{6}$/.test(code)) {
  444. showError('El código debe contener solo números');
  445. codeInput.focus();
  446. return;
  447. }
  448. codeSubmitBtn.disabled = true;
  449. codeSubmitBtn.textContent = 'Verificando...';
  450. const codeVerify = await fetch('/recovery/validate', {
  451. method: 'POST',
  452. headers: {
  453. 'Content-Type': 'application/json'
  454. },
  455. body: JSON.stringify({ email: userEmail, code })
  456. });
  457. switch (codeVerify.status) {
  458. case 200:
  459. showSuccess('Código verificado correctamente');
  460. setTimeout(async () => {
  461. data = await codeVerify.json();
  462. changeToken = data.token;
  463. showStep(3);
  464. }, 1000);
  465. break;
  466. case 404:
  467. showError('Usuario no encontrado. Por favor verifica e intenta nuevamente.');
  468. codeInput.focus();
  469. codeInput.select();
  470. return;
  471. case 400:
  472. showError('Código incorrecto. Por favor verifica e intenta nuevamente.');
  473. codeSubmitBtn.disabled = false;
  474. codeSubmitBtn.textContent = 'Verificar código';
  475. codeInput.focus();
  476. codeInput.select();
  477. return;
  478. default:
  479. return;
  480. }
  481. codeSubmitBtn.disabled = false;
  482. codeSubmitBtn.textContent = 'Verificar código';
  483. });
  484. // FASE 3: Crear nuevo PIN
  485. pinForm.addEventListener('submit', async function(e) {
  486. e.preventDefault();
  487. const newPin = newPinInput.value.trim();
  488. const confirmPin = confirmPinInput.value.trim();
  489. if (!newPin || newPin.length !== 4) {
  490. showError('El PIN debe tener 4 dígitos');
  491. newPinInput.focus();
  492. return;
  493. }
  494. if (!/^\d{4}$/.test(newPin)) {
  495. showError('El PIN debe contener solo números');
  496. newPinInput.focus();
  497. return;
  498. }
  499. if (!confirmPin || confirmPin.length !== 4) {
  500. showError('Por favor confirma tu PIN');
  501. confirmPinInput.focus();
  502. return;
  503. }
  504. if (newPin !== confirmPin) {
  505. showError('Los PINs no coinciden. Por favor verifica e intenta nuevamente.');
  506. confirmPinInput.focus();
  507. confirmPinInput.select();
  508. return;
  509. }
  510. // Validar que no sea un PIN muy obvio
  511. if (newPin === '1234' || newPin === '0000' || newPin === '1111' || newPin === '2222' ||
  512. newPin === '3333' || newPin === '4444' || newPin === '5555' || newPin === '6666' ||
  513. newPin === '7777' || newPin === '8888' || newPin === '9999') {
  514. showError('Por favor elige un PIN más seguro. Evita secuencias obvias.');
  515. newPinInput.focus();
  516. newPinInput.select();
  517. return;
  518. }
  519. pinSubmitBtn.disabled = true;
  520. pinSubmitBtn.textContent = 'Estableciendo PIN...';
  521. const changePinResponse = await fetch('/api/users/pin-recovery', {
  522. method: 'POST',
  523. headers: {
  524. 'Content-Type': 'application/json',
  525. 'Authorization': 'Bearer ' + changeToken
  526. },
  527. body: JSON.stringify({email:userEmail, token: changeToken, new_pin: newPin})
  528. });
  529. if (changePinResponse.ok) {
  530. showSuccess('¡PIN establecido correctamente! Ya puedes acceder a tu cuenta.');
  531. setTimeout(() => {
  532. // Redirigir al login o página principal
  533. alert('PIN establecido correctamente. Serás redirigido al inicio de sesión.');
  534. window.location.href = '/';
  535. }, 500);
  536. } else {
  537. showError('Error al establecer el PIN. Por favor intenta nuevamente.');
  538. }
  539. });
  540. // Eventos adicionales
  541. backToEmailBtn.addEventListener('click', function() {
  542. stopResendTimer(); // Detener el timer si regresa al paso 1
  543. showStep(1);
  544. });
  545. resendCodeBtn.addEventListener('click', function() {
  546. if (resendCodeBtn.disabled) return; // Prevenir clics múltiples
  547. sendMail();
  548. startResendTimer(); // Reiniciar el timer
  549. });
  550. // Formatear inputs de PIN para que solo acepten números
  551. [newPinInput, confirmPinInput].forEach(input => {
  552. input.addEventListener('input', function(e) {
  553. e.target.value = e.target.value.replace(/\D/g, '').slice(0, 4);
  554. hideMessages();
  555. });
  556. });
  557. // Formatear input de código para que solo acepte números
  558. codeInput.addEventListener('input', function(e) {
  559. e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
  560. hideMessages();
  561. });
  562. // Ocultar mensajes cuando el usuario escriba
  563. [emailInput, codeInput, newPinInput, confirmPinInput].forEach(input => {
  564. input.addEventListener('input', hideMessages);
  565. });
  566. // Validar email
  567. function isValidEmail(email) {
  568. const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  569. return emailRegex.test(email);
  570. }
  571. // Navegación con Enter entre campos de PIN
  572. newPinInput.addEventListener('keypress', function(e) {
  573. if (e.key === 'Enter' && this.value.length === 4) {
  574. confirmPinInput.focus();
  575. }
  576. });
  577. confirmPinInput.addEventListener('keypress', function(e) {
  578. if (e.key === 'Enter' && this.value.length === 4) {
  579. pinForm.dispatchEvent(new Event('submit'));
  580. }
  581. });
  582. </script>
  583. </body>
  584. </html>