This commit is contained in:
2026-10-29 12:48:24 +03:00
parent 0bc60622f1
commit 7bda9bbc10
4 changed files with 621 additions and 61 deletions

View File

@ -1,72 +1,111 @@
<script>
import MainMenu from '$lib/pages/main/MainMenu.svelte';
import PrintMenu from '$lib/pages/print/PrintMenu.svelte';
import ScanPage from '$lib/pages/scan/ScanPage.svelte';
import UpdateBanner from '$lib/common/ui/UpdateBanner.svelte';
import { useUpdateCheck } from '$lib/common/hooks/useUpdateCheck.svelte.js';
import MainMenu from '$lib/pages/main/MainMenu.svelte';
import PrintMenu from '$lib/pages/print/PrintMenu.svelte';
import ScanPage from '$lib/pages/scan/ScanPage.svelte';
import UpdateBanner from '$lib/common/ui/UpdateBanner.svelte';
import AuthPage from '$lib/common/ui/AuthPage.svelte';
import { useUpdateCheck } from '$lib/common/hooks/useUpdateCheck.svelte.js';
import { useAuth } from '$lib/common/hooks/useAuth.svelte.js';
/** @type {'main' | 'print' | 'scan'} */
let page = $state('main');
const { needRefresh, doUpdate } = useUpdateCheck();
const auth = useAuth();
const { needRefresh, doUpdate } = useUpdateCheck();
// Проверяем токен при загрузке
auth.checkAuth();
/** @param {'print' | 'scan' | 'photo' | 'access'} id */
function handleAction(id) {
if (id === 'print') {
page = 'print';
} else if (id === 'scan') {
page = 'scan';
} else {
console.log('Выбрано действие:', id);
}
}
/** @type {'main' | 'print' | 'scan'} */
let page = $state('main');
function handleBack() {
page = 'main';
}
function handleAction(id) {
if (id === 'print') {
page = 'print';
} else if (id === 'scan') {
page = 'scan';
} else {
console.log('Выбрано действие:', id);
}
}
function handleDismiss() {
// Пользователь нажал "Позже", баннер скроется
}
function handleBack() {
page = 'main';
}
function handleDismiss() {}
function handleAuthenticated(token) {
auth.setToken(token);
}
</script>
<style>
:global(html),
:global(body) {
margin: 0;
padding: 0;
background: #0b0d11;
}
:global(body) {
display: block;
place-items: initial;
min-width: 0;
color: #f5f7fa;
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
}
.app-wrapper {
display: flex;
justify-content: center;
}
@media (max-width: 480px) {
.app-wrapper {
justify-content: center;
}
}
</style>
{#if needRefresh}
<UpdateBanner onUpdate={doUpdate} onDismiss={handleDismiss} />
<UpdateBanner onUpdate={doUpdate} onDismiss={handleDismiss} />
{/if}
<main class="app-wrapper">
{#if page === 'main'}
<MainMenu onAction={handleAction} />
{:else if page === 'print'}
<PrintMenu onBack={handleBack} />
{:else if page === 'scan'}
<ScanPage onBack={handleBack} />
{/if}
</main>
{#if !auth.authReady}
<!-- Начальная проверка токена -->
<div class="loading-screen">
<div class="loading-spinner"></div>
</div>
{:else if !auth.isAuthenticated}
<!-- ═══ Экран авторизации ═══ -->
<AuthPage onAuthenticated={handleAuthenticated} />
{:else}
<!-- ═══ Основное приложение ═══ -->
<main class="app-wrapper">
{#if page === 'main'}
<MainMenu onAction={handleAction} />
{:else if page === 'print'}
<PrintMenu onBack={handleBack} />
{:else if page === 'scan'}
<ScanPage onBack={handleBack} />
{/if}
</main>
{/if}
<style>
:global(html),
:global(body) {
margin: 0;
padding: 0;
background: #0b0d11;
}
:global(body) {
display: block;
place-items: initial;
min-width: 0;
color: #f5f7fa;
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
-webkit-font-smoothing: antialiased;
}
.app-wrapper {
display: flex;
justify-content: center;
}
@media (max-width: 480px) {
.app-wrapper {
justify-content: center;
}
}
.loading-screen {
width: 100%;
min-height: 100dvh;
display: flex;
align-items: center;
justify-content: center;
background: #0b0d11;
}
.loading-spinner {
width: 36px;
height: 36px;
border: 3px solid rgba(255, 255, 255, 0.1);
border-top-color: #6366f1;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>

View File

@ -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,
};
}

View File

@ -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();
}

View File

@ -0,0 +1,393 @@
<!-- src/lib/common/ui/AuthPage.svelte -->
<script>
import { sendOtp, verifyOtp } from '$lib/common/services/auth.service.js';
let { onAuthenticated = () => {} } = $props();
/** 'phone' | 'otp' */
let step = $state('phone');
let phone = $state('');
let otp = $state(['', '', '', '', '', '']);
let loading = $state(false);
let error = $state('');
let resendTimer = $state(0);
let timerInterval = null;
/** Маска для отображения номера */
const maskedPhone = $derived(
phone.length >= 12
? `${phone.slice(0, 2)} (${phone.slice(2, 5)}) ${phone.slice(5, 8)}-${phone.slice(8, 10)}-${phone.slice(10, 12)}`
: phone
);
/** OTP введён полностью? */
const otpComplete = $derived(otp.every((d) => d !== ''));
const otpCode = $derived(otp.join(''));
function onPhoneInput(e) {
// Оставляем только цифры, максимум 11 (без +7)
phone = e.target.value.replace(/\D/g, '').slice(0, 11);
error = '';
}
function fullPhone() {
const digits = phone.replace(/\D/g, '');
if (digits.length === 11 && (digits[0] === '7' || digits[0] === '8')) {
return `+7${digits.slice(1)}`;
}
if (digits.length === 10) {
return `+7${digits}`;
}
return null;
}
async function handleSendOtp() {
const p = fullPhone();
if (!p) {
error = 'Введите корректный номер телефона';
return;
}
loading = true;
error = '';
try {
await sendOtp(p);
step = 'otp';
otp = ['', '', '', '', '', ''];
startResendTimer(60);
} catch (e) {
error = e.message || 'Не удалось отправить код';
} finally {
loading = false;
}
}
function handleOtpInput(index, e) {
const val = e.target.value.replace(/\D/g, '').slice(-1);
otp[index] = val;
otp = [...otp];
// Автопереход к следующему полю
if (val && index < 5) {
const next = e.target.parentElement?.querySelector(`input[data-idx="${index + 1}"]`);
next?.focus();
}
}
function handleOtpKeydown(index, e) {
// Backspace → назад
if (e.key === 'Backspace' && !otp[index] && index > 0) {
const prev = e.target.parentElement?.querySelector(`input[data-idx="${index - 1}"]`);
prev?.focus();
}
}
function handleOtpPaste(e) {
e.preventDefault();
const text = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '');
if (text.length >= 6) {
otp = text.slice(0, 6).split('');
}
}
async function handleVerify() {
if (!otpComplete) return;
const p = fullPhone();
loading = true;
error = '';
try {
const data = await verifyOtp(p, otpCode);
onAuthenticated(data.token);
} catch (e) {
error = e.message || 'Неверный код';
otp = ['', '', '', '', '', ''];
} finally {
loading = false;
}
}
function backToPhone() {
step = 'phone';
error = '';
otp = ['', '', '', '', '', ''];
stopResendTimer();
}
function startResendTimer(secs) {
stopResendTimer();
resendTimer = secs;
timerInterval = setInterval(() => {
resendTimer -= 1;
if (resendTimer <= 0) stopResendTimer();
}, 1000);
}
function stopResendTimer() {
if (timerInterval) clearInterval(timerInterval);
timerInterval = null;
resendTimer = 0;
}
</script>
<div class="auth-container">
<main class="auth-card">
<div class="auth-logo">
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 6 2 18 2 18 9"></polyline>
<path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path>
<rect x="6" y="14" width="12" height="8"></rect>
</svg>
</div>
{#if step === 'phone'}
<!-- ═══ Шаг 1: ввод телефона ═══ -->
<h1 class="auth-title">Вход в UnitPrint</h1>
<p class="auth-sub">Введите номер телефона — мы отправим код подтверждения</p>
<div class="phone-input-wrap">
<span class="phone-prefix">+7</span>
<input
type="tel"
class="phone-input"
placeholder="999 900-50-80"
value={phone}
oninput={onPhoneInput}
onkeydown={(e) => e.key === 'Enter' && handleSendOtp()}
maxlength="11"
autocomplete="tel"
inputmode="numeric"
/>
</div>
{#if error}
<p class="auth-error">{error}</p>
{/if}
<button
class="auth-btn"
disabled={loading || phone.length < 10}
onclick={handleSendOtp}
>
{loading ? 'Отправка…' : 'Получить код'}
</button>
{:else}
<!-- ═══ Шаг 2: ввод OTP ═══ -->
<h1 class="auth-title">Введите код</h1>
<p class="auth-sub">Код отправлен на <strong>{maskedPhone}</strong></p>
<div class="otp-row" onpaste={handleOtpPaste}>
{#each otp as digit, i}
<input
type="text"
class="otp-cell"
data-idx={i}
value={digit}
maxlength="1"
inputmode="numeric"
autocomplete="one-time-code"
oninput={(e) => handleOtpInput(i, e)}
onkeydown={(e) => handleOtpKeydown(i, e)}
/>
{/each}
</div>
{#if error}
<p class="auth-error">{error}</p>
{/if}
<button
class="auth-btn"
disabled={loading || !otpComplete}
onclick={handleVerify}
>
{loading ? 'Проверка…' : 'Подтвердить'}
</button>
<div class="auth-links">
<button class="link-btn" onclick={backToPhone}>← Изменить номер</button>
{#if resendTimer > 0}
<span class="resend-hint">Повторно через {resendTimer} с</span>
{:else}
<button class="link-btn" onclick={handleSendOtp}>Отправить код ещё раз</button>
{/if}
</div>
{/if}
</main>
</div>
<style>
.auth-container {
width: 100%;
min-height: 100dvh;
display: flex;
align-items: center;
justify-content: center;
background: radial-gradient(120% 60% at 50% -10%, rgba(99, 102, 241, 0.18) 0%, transparent 60%);
font-family: system-ui, -apple-system, sans-serif;
color: #f5f7fa;
padding: 20px;
}
.auth-card {
width: 100%;
max-width: 380px;
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
text-align: center;
}
.auth-logo {
width: 72px;
height: 72px;
border-radius: 20px;
display: grid;
place-items: center;
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
box-shadow: 0 12px 32px -8px rgba(99, 102, 241, 0.5);
color: #fff;
margin-bottom: 8px;
}
.auth-title {
margin: 0;
font-size: 24px;
font-weight: 700;
letter-spacing: -0.02em;
}
.auth-sub {
margin: 0;
font-size: 14px;
color: #8b93a1;
line-height: 1.5;
}
.auth-sub strong { color: #c7cdd8; }
/* ── Телефон ── */
.phone-input-wrap {
width: 100%;
display: flex;
align-items: center;
gap: 0;
border-radius: 14px;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(255, 255, 255, 0.05);
overflow: hidden;
}
.phone-prefix {
padding: 14px 4px 14px 16px;
font-size: 16px;
font-weight: 600;
color: #a5b4fc;
user-select: none;
}
.phone-input {
flex: 1;
border: none;
background: transparent;
color: #f5f7fa;
font-size: 16px;
font-weight: 500;
padding: 14px 16px 14px 4px;
outline: none;
letter-spacing: 0.04em;
}
.phone-input::placeholder { color: rgba(139, 147, 161, 0.5); }
/* ── OTP ── */
.otp-row {
display: flex;
gap: 8px;
justify-content: center;
}
.otp-cell {
width: 46px;
height: 54px;
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.12);
background: rgba(255, 255, 255, 0.05);
color: #f5f7fa;
font-size: 22px;
font-weight: 700;
text-align: center;
outline: none;
transition: border-color 0.2s;
caret-color: #6366f1;
}
.otp-cell:focus {
border-color: #6366f1;
box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.3);
}
/* ── Кнопка ── */
.auth-btn {
width: 100%;
padding: 16px 24px;
border-radius: 14px;
border: none;
font-size: 16px;
font-weight: 700;
color: #fff;
cursor: pointer;
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
box-shadow: 0 8px 24px -6px rgba(99, 102, 241, 0.45);
transition: all 0.2s;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
.auth-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.auth-btn:not(:disabled):active {
transform: scale(0.97);
}
/* ── Ошибка ── */
.auth-error {
margin: 0;
font-size: 13px;
font-weight: 600;
color: #f87171;
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.25);
border-radius: 10px;
padding: 10px 14px;
width: 100%;
box-sizing: border-box;
}
/* ── Ссылки ── */
.auth-links {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
.link-btn {
background: none;
border: none;
color: #6366f1;
font-size: 14px;
font-weight: 600;
cursor: pointer;
padding: 4px 0;
}
.resend-hint {
font-size: 13px;
color: #8b93a1;
}
</style>