add work SMS auth

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

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