feat: add forgot password and username recovery flow
Run Tests on Branches / Detect Changes (push) Successful in 14s
Run Tests on Branches / Backend Tests (push) Successful in 2m24s
Run Tests on Branches / Frontend Tests (push) Successful in 1m57s
Run Tests on Branches / Frontend Mobile Tests (push) Has been skipped
Run Tests on Branches / Parapharmacy API Tests (push) Has been skipped
Run Tests on Branches / PIP Platform Tests (push) Has been skipped

- Add Mailpit SMTP container to docker-compose for dev email capture
- Add nodemailer dependency for email sending
- Add password_reset_tokens table (PG + SQLite)
- Add POST /api/auth/forgot-username endpoint
- Add POST /api/auth/forgot-password endpoint (token-based, 1h expiry)
- Add POST /api/auth/reset-password endpoint
- Create ForgotPasswordModal component (choose mode → email → sent)
- Create ResetPasswordView (token-based new password form)
- Add forgot/recovery links to LoginModal
- Add i18n translations (ES/CA) for the full flow
This commit is contained in:
Antoni Nuñez Romeu
2026-07-27 15:57:54 +02:00
parent 271d23b072
commit 87df61ab15
15 changed files with 839 additions and 1 deletions
+44
View File
@@ -8,6 +8,8 @@ import AlertsView from './views/AlertsView';
import ProfileView from './views/ProfileView';
import AdminView from './views/AdminView';
import LoginModal from './components/LoginModal';
import ForgotPasswordModal from './components/ForgotPasswordModal';
import ResetPasswordView from './views/ResetPasswordView';
import SavedNotifications from './components/SavedNotifications';
import BottomNav from './components/BottomNav';
import { getFaro } from './utils/faro';
@@ -17,6 +19,9 @@ function App() {
const [currentUser, setCurrentUser] = useState(null);
const [authChecked, setAuthChecked] = useState(false);
const [showLogin, setShowLogin] = useState(false);
const [showForgot, setShowForgot] = useState(false);
const [forgotMode, setForgotMode] = useState('password');
const [resetToken, setResetToken] = useState(null);
const [showSaved, setShowSaved] = useState(false);
const [badgeCount, setBadgeCount] = useState(0);
const [prescriptionSearch, setPrescriptionSearch] = useState('');
@@ -67,6 +72,13 @@ function App() {
});
};
const params = new URLSearchParams(window.location.search);
const token = params.get('token');
if (token) {
setResetToken(token);
setScreen('reset-password');
}
fetch('/api/auth/check')
.then(r => r.json())
.then(data => { if (data.authenticated) setCurrentUser(data.user); })
@@ -126,6 +138,18 @@ function App() {
setCurrentUser(prev => ({ ...prev, ...updated }));
}
function handleForgotPassword(mode) {
setForgotMode(mode);
setShowLogin(false);
setShowForgot(true);
}
function handleResetComplete() {
setResetToken(null);
setShowLogin(true);
window.history.replaceState({}, '', '/');
}
function handleAdminClick() {
setScreen('admin');
}
@@ -211,6 +235,14 @@ function App() {
/>
);
break;
case 'reset-password':
activeView = (
<ResetPasswordView
token={resetToken}
onReset={handleResetComplete}
/>
);
break;
case 'admin':
activeView = <AdminView />;
break;
@@ -243,6 +275,18 @@ function App() {
<LoginModal
onLogin={handleLogin}
onClose={() => setShowLogin(false)}
onForgotPassword={handleForgotPassword}
/>
)}
{showForgot && (
<ForgotPasswordModal
initialMode={forgotMode}
onClose={() => setShowForgot(false)}
onBackToLogin={() => {
setShowForgot(false);
setShowLogin(true);
}}
/>
)}
@@ -0,0 +1,77 @@
.forgot-box {
max-width: 380px;
}
.forgot-back {
background: none;
border: none;
color: var(--primary);
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
padding: 0;
margin-bottom: 1rem;
display: inline-block;
}
.forgot-back:hover {
opacity: 0.8;
}
.forgot-options {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 0.5rem;
}
.forgot-option {
display: flex;
align-items: center;
gap: 0.85rem;
background: var(--surface-muted);
border: 1px solid var(--border);
border-radius: calc(var(--radius) - 4px);
padding: 1rem;
cursor: pointer;
text-align: left;
transition: border-color 0.15s, background 0.15s;
font-size: 0.9rem;
color: var(--text-main);
}
.forgot-option:hover {
border-color: var(--primary);
background: var(--surface);
}
.forgot-option-icon {
font-size: 1.5rem;
flex-shrink: 0;
}
.forgot-option-text {
display: flex;
flex-direction: column;
gap: 0.15rem;
}
.forgot-option-desc {
font-size: 0.8rem;
color: var(--text-muted);
font-weight: 400;
}
.forgot-sent-icon {
text-align: center;
font-size: 2.5rem;
margin-bottom: 0.75rem;
}
.forgot-sent-text {
font-size: 0.9rem;
color: var(--text-muted);
line-height: 1.5;
text-align: center;
margin: 0 0 0.5rem;
}
@@ -0,0 +1,159 @@
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from '../i18n';
import './LoginModal.css';
import './ForgotPasswordModal.css';
function ForgotPasswordModal({ onClose, onBackToLogin, initialMode }) {
const { t } = useTranslation();
const [step, setStep] = useState(initialMode ? 'email' : 'choose'); // choose | email | sent
const [mode, setMode] = useState(initialMode || ''); // username | password
const [email, setEmail] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const emailRef = useRef(null);
useEffect(() => {
emailRef.current?.focus();
function handleKey(e) { if (e.key === 'Escape') onClose(); }
document.addEventListener('keydown', handleKey);
return () => document.removeEventListener('keydown', handleKey);
}, [onClose]);
function handleChoose(m) {
setMode(m);
setStep('email');
setError('');
}
async function handleSubmit(e) {
e.preventDefault();
const em = email.trim();
if (!em) return;
setLoading(true);
setError('');
try {
const endpoint = mode === 'password'
? '/api/auth/forgot-password'
: '/api/auth/forgot-username';
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: em }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data.error || t('forgot.error'));
return;
}
setStep('sent');
} catch {
setError(t('login.networkError'));
} finally {
setLoading(false);
}
}
function handleBack() {
if (step === 'email') setStep('choose');
else onBackToLogin();
}
return (
<div className="modal-overlay" onClick={onClose}>
<div
className="modal-box forgot-box"
onClick={e => e.stopPropagation()}
role="dialog"
aria-modal="true"
aria-labelledby="forgot-title"
>
{step === 'choose' && (
<>
<button type="button" className="forgot-back" onClick={onBackToLogin} aria-label={t('forgot.back')}>
← {t('forgot.backToLogin')}
</button>
<h2 id="forgot-title">{t('forgot.title')}</h2>
<p className="modal-sub">{t('forgot.subtitle')}</p>
<div className="forgot-options">
<button
type="button"
className="forgot-option"
onClick={() => handleChoose('password')}
>
<span className="forgot-option-icon">🔑</span>
<span className="forgot-option-text">
<strong>{t('forgot.password')}</strong>
<span className="forgot-option-desc">{t('forgot.passwordDesc')}</span>
</span>
</button>
<button
type="button"
className="forgot-option"
onClick={() => handleChoose('username')}
>
<span className="forgot-option-icon">👤</span>
<span className="forgot-option-text">
<strong>{t('forgot.username')}</strong>
<span className="forgot-option-desc">{t('forgot.usernameDesc')}</span>
</span>
</button>
</div>
</>
)}
{step === 'email' && (
<>
<button type="button" className="forgot-back" onClick={handleBack} aria-label={t('forgot.back')}>
← {t('forgot.back')}
</button>
<h2 id="forgot-title">
{mode === 'password' ? t('forgot.resetTitle') : t('forgot.usernameTitle')}
</h2>
<p className="modal-sub">
{mode === 'password' ? t('forgot.resetDesc') : t('forgot.usernameDesc2')}
</p>
<form onSubmit={handleSubmit} noValidate>
<div className="modal-field">
<label htmlFor="forgot-email">{t('forgot.email')}</label>
<input
id="forgot-email"
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
autoComplete="email"
ref={emailRef}
disabled={loading}
placeholder={t('forgot.emailPlaceholder')}
/>
</div>
{error && <p className="modal-error">{error}</p>}
<div className="modal-actions">
<button type="button" className="modal-cancel" onClick={handleBack} disabled={loading}>
{t('forgot.cancel')}
</button>
<button type="submit" className="modal-submit" disabled={loading || !email.trim()}>
{loading ? t('forgot.sending') : t('forgot.send')}
</button>
</div>
</form>
</>
)}
{step === 'sent' && (
<>
<div className="forgot-sent-icon">✅</div>
<h2 id="forgot-title">{t('forgot.sentTitle')}</h2>
<p className="forgot-sent-text">{t('forgot.sentText')}</p>
<div className="modal-actions" style={{ justifyContent: 'center' }}>
<button type="button" className="modal-submit" onClick={onClose}>
{t('forgot.close')}
</button>
</div>
</>
)}
</div>
</div>
);
}
export default ForgotPasswordModal;
@@ -171,3 +171,27 @@
opacity: 0.5;
cursor: not-allowed;
}
.forgot-links {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.35rem;
margin-top: 1rem;
}
.forgot-link {
background: none;
border: none;
color: var(--text-muted);
font-size: 0.8rem;
cursor: pointer;
padding: 0.2rem 0;
text-decoration: underline;
text-underline-offset: 2px;
transition: color 0.15s;
}
.forgot-link:hover {
color: var(--primary);
}
+19 -1
View File
@@ -2,7 +2,7 @@ import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from '../i18n';
import './LoginModal.css';
function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
function LoginModal({ onLogin, onClose, initialMode = 'login', onForgotPassword }) {
const { t } = useTranslation();
const [mode, setMode] = useState(initialMode === 'register' ? 'register' : 'login');
const [username, setUsername] = useState('');
@@ -148,6 +148,24 @@ function LoginModal({ onLogin, onClose, initialMode = 'login' }) {
</button>
</div>
</form>
{!isRegister && (
<div className="forgot-links">
<button
type="button"
className="forgot-link"
onClick={() => onForgotPassword('password')}
>
{t('forgot.forgotPassword')}
</button>
<button
type="button"
className="forgot-link"
onClick={() => onForgotPassword('username')}
>
{t('forgot.forgotUsername')}
</button>
</div>
)}
</div>
</div>
);
+39
View File
@@ -251,6 +251,45 @@ const ca = {
'profile.languageCatalan': 'Català',
'profile.languageSpanish': 'Castellà',
// ForgotPasswordModal
'forgot.title': 'Problemes per accedir?',
'forgot.subtitle': 'Tria què necessites recuperar',
'forgot.password': 'He oblidat la meva contrasenya',
'forgot.passwordDesc': 'T\'enviarem un enllaç per crear-ne una de nova',
'forgot.username': 'He oblidat el meu usuari',
'forgot.usernameDesc': 'T\'enviarem el teu nom d\'usuari',
'forgot.resetTitle': 'Restablir contrasenya',
'forgot.resetDesc': 'Introdueix el teu correu electrònic i t\'enviarem un enllaç per crear una nova contrasenya.',
'forgot.usernameTitle': 'Recuperar usuari',
'forgot.usernameDesc2': 'Introdueix el teu correu electrònic i t\'enviarem el teu nom d\'usuari.',
'forgot.email': 'Correu electrònic',
'forgot.emailPlaceholder': 'el_teu@email.com',
'forgot.send': 'Enviar',
'forgot.sending': 'Enviant...',
'forgot.cancel': 'Cancel·lar',
'forgot.back': 'Tornar',
'forgot.backToLogin': 'Tornar a iniciar sessió',
'forgot.sentTitle': 'Correu enviat',
'forgot.sentText': 'Si l\'adreça de correu existeix a la nostra base de dades, rebràs un missatge en uns minuts. Revisa la teva safata d\'entrada.',
'forgot.close': 'Tancar',
'forgot.error': 'Error en processar la sol·licitud',
'forgot.forgotPassword': 'Has oblidat la contrasenya?',
'forgot.forgotUsername': 'Has oblidat l\'usuari?',
// ResetPasswordView
'reset.title': 'Crear nova contrasenya',
'reset.subtitle': 'Introdueix la teva nova contrasenya',
'reset.newPassword': 'Nova contrasenya',
'reset.confirmPassword': 'Confirmar contrasenya',
'reset.saveBtn': 'Canviar contrasenya',
'reset.saving': 'Desant...',
'reset.passwordsDontMatch': 'Les contrasenyes no coincideixen',
'reset.successTitle': 'Contrasenya actualitzada',
'reset.successText': 'La teva contrasenya s\'ha actualitzat correctament. Ja pots iniciar sessió amb la teva nova contrasenya.',
'reset.goToLogin': 'Anar a iniciar sessió',
'reset.error': 'Error en restablir la contrasenya',
'reset.invalidToken': 'Enllaç invàlid o caducat. Sol·licita un nou restabliment de contrasenya.',
// SavedNotifications
'savedNotifications.title': '🔔 Notificacions Desades',
'savedNotifications.close': 'Tancar',
+39
View File
@@ -251,6 +251,45 @@ const es = {
'profile.languageCatalan': 'Català',
'profile.languageSpanish': 'Castellano',
// ForgotPasswordModal
'forgot.title': '¿Problemas para acceder?',
'forgot.subtitle': 'Elige qué necesitas recuperar',
'forgot.password': 'He olvidado mi contraseña',
'forgot.passwordDesc': 'Te enviaremos un enlace para crear una nueva',
'forgot.username': 'He olvidado mi usuario',
'forgot.usernameDesc': 'Te enviaremos tu nombre de usuario',
'forgot.resetTitle': 'Restablecer contraseña',
'forgot.resetDesc': 'Introduce tu correo electrónico y te enviaremos un enlace para crear una nueva contraseña.',
'forgot.usernameTitle': 'Recuperar usuario',
'forgot.usernameDesc2': 'Introduce tu correo electrónico y te enviaremos tu nombre de usuario.',
'forgot.email': 'Correo electrónico',
'forgot.emailPlaceholder': 'tu@email.com',
'forgot.send': 'Enviar',
'forgot.sending': 'Enviando...',
'forgot.cancel': 'Cancelar',
'forgot.back': 'Volver',
'forgot.backToLogin': 'Volver a iniciar sesión',
'forgot.sentTitle': 'Correo enviado',
'forgot.sentText': 'Si la dirección de correo existe en nuestra base de datos, recibirás un mensaje en unos minutos. Revisa tu bandeja de entrada.',
'forgot.close': 'Cerrar',
'forgot.error': 'Error al procesar la solicitud',
'forgot.forgotPassword': '¿Olvidaste tu contraseña?',
'forgot.forgotUsername': '¿Olvidaste tu usuario?',
// ResetPasswordView
'reset.title': 'Crear nueva contraseña',
'reset.subtitle': 'Introduce tu nueva contraseña',
'reset.newPassword': 'Nueva contraseña',
'reset.confirmPassword': 'Confirmar contraseña',
'reset.saveBtn': 'Cambiar contraseña',
'reset.saving': 'Guardando...',
'reset.passwordsDontMatch': 'Las contraseñas no coinciden',
'reset.successTitle': 'Contraseña actualizada',
'reset.successText': 'Tu contraseña se ha actualizado correctamente. Ya puedes iniciar sesión con tu nueva contraseña.',
'reset.goToLogin': 'Ir a iniciar sesión',
'reset.error': 'Error al restablecer la contraseña',
'reset.invalidToken': 'Enlace inválido o expirado. Solicita un nuevo restablecimiento de contraseña.',
// SavedNotifications
'savedNotifications.title': '🔔 Notificaciones Guardadas',
'savedNotifications.close': 'Cerrar',
@@ -0,0 +1,100 @@
.reset-container {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 1.5rem;
}
.reset-card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 2rem 2.25rem 1.75rem;
width: 100%;
max-width: 360px;
box-shadow: 0 20px 60px rgba(28, 25, 23, 0.12);
}
.reset-card h2 {
margin: 0 0 0.25rem;
font-size: 1.35rem;
font-weight: 700;
color: var(--text-main);
text-align: center;
}
.reset-sub {
margin: 0 0 1.5rem;
font-size: 0.875rem;
color: var(--text-muted);
text-align: center;
}
.reset-field {
display: flex;
flex-direction: column;
gap: 0.35rem;
margin-bottom: 1rem;
}
.reset-field label {
font-size: 0.82rem;
font-weight: 600;
color: var(--text-muted);
}
.reset-field input {
padding: 0.6rem 0.85rem;
border: 1px solid var(--border);
border-radius: calc(var(--radius) - 4px);
background: var(--surface-muted);
color: var(--text-main);
font-size: 0.95rem;
outline: none;
transition: border-color 0.15s;
}
.reset-field input:focus {
border-color: var(--primary);
}
.reset-field input:disabled {
opacity: 0.6;
}
.reset-error {
font-size: 0.82rem;
color: var(--error);
margin: 0.25rem 0 0.75rem;
text-align: center;
}
.reset-btn {
width: 100%;
background: var(--primary);
border: none;
color: var(--on-primary);
padding: 0.65rem 1.35rem;
border-radius: 999px;
cursor: pointer;
font-size: 0.95rem;
font-weight: 600;
transition: opacity 0.15s;
margin-top: 0.5rem;
}
.reset-btn:hover:not(:disabled) {
opacity: 0.88;
}
.reset-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.reset-icon {
text-align: center;
font-size: 2.5rem;
margin-bottom: 0.75rem;
}
@@ -0,0 +1,109 @@
import React, { useState, useEffect } from 'react';
import { useTranslation } from '../i18n';
import './ResetPasswordView.css';
function ResetPasswordView({ token, onReset }) {
const { t } = useTranslation();
const [password, setPassword] = useState('');
const [confirm, setConfirm] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [success, setSuccess] = useState(false);
useEffect(() => {
if (!token) setError(t('reset.invalidToken'));
}, [token, t]);
async function handleSubmit(e) {
e.preventDefault();
if (password.length < 8) {
setError(t('login.passwordError'));
return;
}
if (password !== confirm) {
setError(t('reset.passwordsDontMatch'));
return;
}
setLoading(true);
setError('');
try {
const res = await fetch('/api/auth/reset-password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, password }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data.error || t('reset.error'));
return;
}
setSuccess(true);
} catch {
setError(t('login.networkError'));
} finally {
setLoading(false);
}
}
if (success) {
return (
<div className="reset-container">
<div className="reset-card">
<div className="reset-icon">✅</div>
<h2>{t('reset.successTitle')}</h2>
<p>{t('reset.successText')}</p>
<button type="button" className="reset-btn" onClick={onReset}>
{t('reset.goToLogin')}
</button>
</div>
</div>
);
}
return (
<div className="reset-container">
<div className="reset-card">
<h2>{t('reset.title')}</h2>
<p className="reset-sub">{t('reset.subtitle')}</p>
<form onSubmit={handleSubmit} noValidate>
<div className="reset-field">
<label htmlFor="reset-password">{t('reset.newPassword')}</label>
<input
id="reset-password"
type="password"
value={password}
onChange={e => setPassword(e.target.value)}
autoComplete="new-password"
disabled={loading}
minLength={8}
placeholder="········"
/>
</div>
<div className="reset-field">
<label htmlFor="reset-confirm">{t('reset.confirmPassword')}</label>
<input
id="reset-confirm"
type="password"
value={confirm}
onChange={e => setConfirm(e.target.value)}
autoComplete="new-password"
disabled={loading}
minLength={8}
placeholder="········"
/>
</div>
{error && <p className="reset-error">{error}</p>}
<button
type="submit"
className="reset-btn"
disabled={loading || !password || !confirm}
>
{loading ? t('reset.saving') : t('reset.saveBtn')}
</button>
</form>
</div>
</div>
);
}
export default ResetPasswordView;