diff --git a/src/App.svelte b/src/App.svelte index bc51af8..011a6a2 100644 --- a/src/App.svelte +++ b/src/App.svelte @@ -1,72 +1,111 @@ - - {#if needRefresh} - + {/if} -
- {#if page === 'main'} - - {:else if page === 'print'} - - {:else if page === 'scan'} - - {/if} -
+{#if !auth.authReady} + +
+
+
+ +{:else if !auth.isAuthenticated} + + + +{:else} + +
+ {#if page === 'main'} + + {:else if page === 'print'} + + {:else if page === 'scan'} + + {/if} +
+{/if} + + diff --git a/src/lib/common/hooks/useAuth.svelte.js b/src/lib/common/hooks/useAuth.svelte.js new file mode 100644 index 0000000..fb2abc9 --- /dev/null +++ b/src/lib/common/hooks/useAuth.svelte.js @@ -0,0 +1,42 @@ +// src/lib/common/hooks/useAuth.svelte.js +import { + getToken, saveToken, clearToken, isTokenValid, +} from '$lib/common/services/auth.service.js'; + +let token = $state(getToken()); +let authReady = $state(false); // завершена ли начальная проверка + +/** Начальная проверка при загрузке приложения */ +function checkAuth() { + const t = getToken(); + if (t && isTokenValid(t)) { + token = t; + } else { + clearToken(); + token = null; + } + authReady = true; +} + +/** Вызывается после успешной верификации OTP */ +function setToken(newToken) { + saveToken(newToken); + token = newToken; +} + +/** Выход */ +function logout() { + clearToken(); + token = null; +} + +export function useAuth() { + return { + get token() { return token; }, + get isAuthenticated() { return !!token && isTokenValid(token); }, + get authReady() { return authReady; }, + checkAuth, + setToken, + logout, + }; +} diff --git a/src/lib/common/services/auth.service.js b/src/lib/common/services/auth.service.js new file mode 100644 index 0000000..1b7f38e --- /dev/null +++ b/src/lib/common/services/auth.service.js @@ -0,0 +1,86 @@ +// src/lib/common/services/auth.service.js + +const TOKEN_KEY = 'up_token'; + +/** Сохранить токен в localStorage */ +export function saveToken(token) { + localStorage.setItem(TOKEN_KEY, token); +} + +/** Получить токен из localStorage */ +export function getToken() { + return localStorage.getItem(TOKEN_KEY) || null; +} + +/** Удалить токен */ +export function clearToken() { + localStorage.removeItem(TOKEN_KEY); +} + +/** Декодировать payload JWT без верификации (для проверки срока) */ +export function decodeJwtPayload(token) { + try { + const payload = token.split('.')[1]; + return JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/'))); + } catch { + return null; + } +} + +/** Проверить, не истёк ли токен (локально, без сервера) */ +export function isTokenValid(token) { + if (!token) return false; + const payload = decodeJwtPayload(token); + if (!payload || !payload.exp) return false; + return payload.exp * 1000 > Date.now(); +} + +/** + * POST /api/auth/send-otp + * @param {string} phone + */ +export async function sendOtp(phone) { + const res = await fetch('/api/auth/send-otp', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ phone }), + }); + const data = await res.json().catch(() => null); + if (!res.ok) { + const msg = typeof data === 'string' ? data : data?.message || `Ошибка ${res.status}`; + throw new Error(msg); + } + return data; +} + +/** + * POST /api/auth/verify-otp + * @param {string} phone + * @param {string} code + * @returns {Promise<{token: string, phone: string}>} + */ +export async function verifyOtp(phone, code) { + const res = await fetch('/api/auth/verify-otp', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ phone, code }), + }); + const data = await res.json().catch(() => null); + if (!res.ok) { + const msg = typeof data === 'string' ? data : data?.message || `Ошибка ${res.status}`; + throw new Error(msg); + } + return data; +} + +/** + * GET /api/auth/me + * @param {string} token + */ +export async function getMe(token) { + const res = await fetch('/api/auth/me', { + headers: { Authorization: `Bearer ${token}` }, + }); + if (!res.ok) throw new Error('Токен недействителен'); + return res.json(); +} diff --git a/src/lib/common/ui/AuthPage.svelte b/src/lib/common/ui/AuthPage.svelte new file mode 100644 index 0000000..9e2c7d1 --- /dev/null +++ b/src/lib/common/ui/AuthPage.svelte @@ -0,0 +1,393 @@ + + + +
+
+ + + {#if step === 'phone'} + +

Вход в UnitPrint

+

Введите номер телефона — мы отправим код подтверждения

+ +
+ +7 + e.key === 'Enter' && handleSendOtp()} + maxlength="11" + autocomplete="tel" + inputmode="numeric" + /> +
+ + {#if error} +

{error}

+ {/if} + + + + {:else} + +

Введите код

+

Код отправлен на {maskedPhone}

+ +
+ {#each otp as digit, i} + handleOtpInput(i, e)} + onkeydown={(e) => handleOtpKeydown(i, e)} + /> + {/each} +
+ + {#if error} +

{error}

+ {/if} + + + + + {/if} +
+
+ +