I18n: strony logowania i rejestracji w tlumaczeniach PL/EN (ApiError.code, helper apiErrorMessage z mapowaniem bledow API po kodzie, testy)
This commit is contained in:
@@ -8,6 +8,11 @@ export class ApiError extends Error {
|
||||
) {
|
||||
super(body?.error?.message || `HTTP ${status}`);
|
||||
}
|
||||
|
||||
/** Kod błędu z ciała odpowiedzi (`{ error: { code } }`) albo null. */
|
||||
get code(): string | null {
|
||||
return this.body?.error?.code ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
let accessToken: string | null = localStorage.getItem('fitos_access');
|
||||
|
||||
38
app/src/lib/errors.ts
Normal file
38
app/src/lib/errors.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { ApiError } from '../api/client';
|
||||
import { resolveLocaleTag } from '../i18n/language';
|
||||
import { i18n } from '../i18n';
|
||||
|
||||
type TFn = (key: string, options?: Record<string, unknown>) => string;
|
||||
|
||||
/**
|
||||
* Etykieta błędu API dla użytkownika: kod → `errors:<code>`, z obsługą
|
||||
* `details.until` (`errors:<code>_until`) i `details.reason` (sufiks).
|
||||
* Bez mapowania — surowy message; bez message — fallback.
|
||||
*/
|
||||
export function apiErrorMessage(err: unknown, t: TFn, fallback?: string): string {
|
||||
if (err instanceof ApiError) {
|
||||
const code = err.body?.error?.code;
|
||||
if (code) {
|
||||
const details = (err.body?.error?.details ?? {}) as {
|
||||
until?: string;
|
||||
reason?: string | null;
|
||||
};
|
||||
let base = '';
|
||||
if (details.until) {
|
||||
const date = new Intl.DateTimeFormat(resolveLocaleTag(i18n.language), {
|
||||
dateStyle: 'long',
|
||||
timeStyle: 'short',
|
||||
}).format(new Date(details.until));
|
||||
base = t(`errors:${code}_until`, { date, defaultValue: '' });
|
||||
}
|
||||
if (!base) base = t(`errors:${code}`, { defaultValue: '' });
|
||||
if (base) {
|
||||
if (details.reason) base += t('errors:reasonSuffix', { reason: details.reason });
|
||||
return base;
|
||||
}
|
||||
}
|
||||
return err.message || fallback || '';
|
||||
}
|
||||
if (err instanceof Error) return err.message || fallback || '';
|
||||
return String(err);
|
||||
}
|
||||
@@ -1,41 +1,15 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../store/auth';
|
||||
import { ApiError } from '../api/client';
|
||||
import AuthShell from '../components/AuthShell';
|
||||
import { Button, ErrorText, Field, Input } from '../components/ui';
|
||||
import { apiErrorMessage } from '../lib/errors';
|
||||
|
||||
const REMEMBER_KEY = 'fitos-remembered-email';
|
||||
|
||||
interface RestrictionDetails {
|
||||
until?: string;
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
/** Kara na koncie (403 z API) ma własny komunikat z terminem/powodem. */
|
||||
function loginErrorMessage(err: unknown): string {
|
||||
if (err instanceof ApiError) {
|
||||
const code = err.body?.error?.code;
|
||||
const details = err.body?.error?.details as RestrictionDetails | undefined;
|
||||
if (code === 'ACCOUNT_SUSPENDED') {
|
||||
const base = details?.until
|
||||
? `Konto zawieszone do ${new Intl.DateTimeFormat('pl-PL', {
|
||||
dateStyle: 'long',
|
||||
timeStyle: 'short',
|
||||
}).format(new Date(details.until))}.`
|
||||
: 'Konto zawieszone.';
|
||||
return details?.reason ? `${base} Powód: ${details.reason}` : base;
|
||||
}
|
||||
if (code === 'ACCOUNT_BANNED') {
|
||||
return details?.reason
|
||||
? `Konto zablokowane przez administratora. Powód: ${details.reason}`
|
||||
: 'Konto zablokowane przez administratora.';
|
||||
}
|
||||
}
|
||||
return err instanceof Error ? err.message : 'Błąd logowania';
|
||||
}
|
||||
|
||||
export default function Login() {
|
||||
const { t } = useTranslation();
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState(() => localStorage.getItem(REMEMBER_KEY) ?? '');
|
||||
@@ -54,7 +28,7 @@ export default function Login() {
|
||||
else localStorage.removeItem(REMEMBER_KEY);
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
setError(loginErrorMessage(err));
|
||||
setError(apiErrorMessage(err, t, t('errors:loginFailed')));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -63,7 +37,7 @@ export default function Login() {
|
||||
return (
|
||||
<AuthShell>
|
||||
<form onSubmit={submit}>
|
||||
<Field label="E-mail">
|
||||
<Field label={t('auth:email')}>
|
||||
<Input
|
||||
type="email"
|
||||
value={email}
|
||||
@@ -72,7 +46,7 @@ export default function Login() {
|
||||
autoComplete="email"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Hasło">
|
||||
<Field label={t('auth:password')}>
|
||||
<Input
|
||||
type="password"
|
||||
value={password}
|
||||
@@ -88,15 +62,15 @@ export default function Login() {
|
||||
onChange={(e) => setRemember(e.target.checked)}
|
||||
className="[--checkbox-size:1.25rem]"
|
||||
/>
|
||||
Zapamiętaj mnie
|
||||
{t('auth:rememberMe')}
|
||||
</label>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
<Button type="submit" disabled={loading} className="w-full">
|
||||
{loading ? 'Logowanie…' : 'Zaloguj'}
|
||||
{loading ? t('auth:loginLoading') : t('auth:login')}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-[0.875rem] text-dim">
|
||||
Nie masz konta? <Link to="/register">Zarejestruj się</Link>
|
||||
{t('auth:noAccount')} <Link to="/register">{t('auth:registerLink')}</Link>
|
||||
</p>
|
||||
</AuthShell>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useAuth } from '../store/auth';
|
||||
import AuthShell from '../components/AuthShell';
|
||||
import { Button, ErrorText, Field, Input } from '../components/ui';
|
||||
import { apiErrorMessage } from '../lib/errors';
|
||||
|
||||
export default function Register() {
|
||||
const { t } = useTranslation();
|
||||
const { register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [form, setForm] = useState({ email: '', password: '', firstName: '', lastName: '' });
|
||||
@@ -26,7 +29,7 @@ export default function Register() {
|
||||
});
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Błąd rejestracji');
|
||||
setError(apiErrorMessage(err, t, t('errors:registerFailed')));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -35,7 +38,7 @@ export default function Register() {
|
||||
return (
|
||||
<AuthShell>
|
||||
<form onSubmit={submit}>
|
||||
<Field label="E-mail">
|
||||
<Field label={t('auth:email')}>
|
||||
<Input
|
||||
type="email"
|
||||
value={form.email}
|
||||
@@ -44,7 +47,7 @@ export default function Register() {
|
||||
autoComplete="email"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Hasło (min. 8 znaków)">
|
||||
<Field label={t('auth:passwordMin')}>
|
||||
<Input
|
||||
type="password"
|
||||
value={form.password}
|
||||
@@ -55,14 +58,14 @@ export default function Register() {
|
||||
/>
|
||||
</Field>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<Field label="Imię">
|
||||
<Field label={t('auth:firstName')}>
|
||||
<Input
|
||||
value={form.firstName}
|
||||
onChange={(e) => set('firstName', e.target.value)}
|
||||
autoComplete="given-name"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="Nazwisko">
|
||||
<Field label={t('auth:lastName')}>
|
||||
<Input
|
||||
value={form.lastName}
|
||||
onChange={(e) => set('lastName', e.target.value)}
|
||||
@@ -72,11 +75,11 @@ export default function Register() {
|
||||
</div>
|
||||
{error && <ErrorText>{error}</ErrorText>}
|
||||
<Button type="submit" disabled={loading} className="w-full mt-2">
|
||||
{loading ? 'Rejestracja…' : 'Zarejestruj'}
|
||||
{loading ? t('auth:registerLoading') : t('auth:register')}
|
||||
</Button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-[0.875rem] text-dim">
|
||||
Masz konto? <Link to="/login">Zaloguj się</Link>
|
||||
{t('auth:haveAccount')} <Link to="/login">{t('auth:loginLink')}</Link>
|
||||
</p>
|
||||
</AuthShell>
|
||||
);
|
||||
|
||||
@@ -128,7 +128,9 @@ describe('Login page', () => {
|
||||
await user.type(email, 'jan@test.local');
|
||||
await user.type(password, 'wrong');
|
||||
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
|
||||
expect(await screen.findByText('Invalid credentials')).toBeInTheDocument();
|
||||
expect(
|
||||
await screen.findByText('Sesja wygasła — zaloguj się ponownie.'),
|
||||
).toBeInTheDocument();
|
||||
expect(useAuth.getState().user).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -93,7 +93,7 @@ describe('Register page', () => {
|
||||
await user.type(email, 'jan@test.local');
|
||||
await user.type(password, 'Password123!');
|
||||
await user.click(screen.getByRole('button', { name: 'Zarejestruj' }));
|
||||
expect(await screen.findByText('Email already in use')).toBeInTheDocument();
|
||||
expect(await screen.findByText('Zmiana koliduje z istniejącymi danymi.')).toBeInTheDocument();
|
||||
expect(useAuth.getState().user).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user