Fix relogin
Deploy Frontend / build-and-deploy (push) Successful in 26s
Details
Deploy Frontend / build-and-deploy (push) Successful in 26s
Details
This commit is contained in:
parent
999c23c144
commit
c1cdb95557
|
|
@ -1,5 +1,11 @@
|
|||
import axios from 'axios'
|
||||
import CryptoJS from 'crypto-js'
|
||||
import { timeApi } from './time'
|
||||
|
||||
// 🔄 Offset между клиентом и сервером (в секундах)
|
||||
let serverTimeOffset = 0
|
||||
let isSyncing = false
|
||||
let syncPromise: Promise<void> | null = null
|
||||
|
||||
// Функция генерации HMAC подписи
|
||||
function generateHmacSignature(publicKey: string, timestamp: string, privateKey: string): string {
|
||||
|
|
@ -12,27 +18,51 @@ function generateHmacSignature(publicKey: string, timestamp: string, privateKey:
|
|||
function getOrCreateDeviceId(): string {
|
||||
let deviceId = localStorage.getItem('device_id')
|
||||
|
||||
console.log('[DeviceID] Checking localStorage:', {
|
||||
exists: !!deviceId,
|
||||
value: deviceId || 'null'
|
||||
})
|
||||
|
||||
if (!deviceId) {
|
||||
deviceId = crypto.randomUUID()
|
||||
localStorage.setItem('device_id', deviceId)
|
||||
|
||||
console.log('[DeviceID] 🆕 Created and saved new device_id:', deviceId)
|
||||
|
||||
// Проверяем, что действительно сохранилось
|
||||
const saved = localStorage.getItem('device_id')
|
||||
console.log('[DeviceID] ✅ Verification - saved value:', saved)
|
||||
} else {
|
||||
console.log('[DeviceID] ✅ Using existing device_id:', deviceId)
|
||||
}
|
||||
|
||||
return deviceId
|
||||
}
|
||||
|
||||
// 🆕 Синхронизация времени с сервером
|
||||
async function syncTimeWithServer(): Promise<void> {
|
||||
if (isSyncing && syncPromise) {
|
||||
return syncPromise
|
||||
}
|
||||
|
||||
isSyncing = true
|
||||
syncPromise = (async () => {
|
||||
try {
|
||||
const serverTime = await timeApi.getServerTime()
|
||||
const clientTimestamp = Math.floor(Date.now() / 1000)
|
||||
serverTimeOffset = serverTime.timestamp - clientTimestamp
|
||||
|
||||
console.log('[Time] ✅ Synced with server', {
|
||||
serverTime: serverTime.iso,
|
||||
serverTimestamp: serverTime.timestamp,
|
||||
clientTimestamp,
|
||||
offset: serverTimeOffset,
|
||||
})
|
||||
} catch (error) {
|
||||
console.warn('[Time] ⚠️ Failed to sync with server:', error)
|
||||
// При ошибке сбрасываем offset
|
||||
serverTimeOffset = 0
|
||||
} finally {
|
||||
isSyncing = false
|
||||
syncPromise = null
|
||||
}
|
||||
})()
|
||||
|
||||
return syncPromise
|
||||
}
|
||||
|
||||
// 🆕 Получение timestamp с учётом offset
|
||||
function getCorrectedTimestamp(): string {
|
||||
return Math.floor(Date.now() / 1000 + serverTimeOffset).toString()
|
||||
}
|
||||
|
||||
const apiClient = axios.create({
|
||||
baseURL: '/api',
|
||||
headers: {
|
||||
|
|
@ -41,7 +71,7 @@ const apiClient = axios.create({
|
|||
})
|
||||
|
||||
// Interceptor для добавления токена и HMAC подписи
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
apiClient.interceptors.request.use(async (config) => {
|
||||
console.log('[API] === Request interceptor started ===')
|
||||
|
||||
// Добавляем JWT токен, если есть
|
||||
|
|
@ -51,10 +81,10 @@ apiClient.interceptors.request.use((config) => {
|
|||
console.log('[API] ✅ Added JWT token')
|
||||
}
|
||||
|
||||
// Генерируем HMAC подпись
|
||||
// Генерируем HMAC подпись с скорректированным timestamp
|
||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
||||
const timestamp = Math.floor(Date.now() / 1000).toString()
|
||||
const timestamp = getCorrectedTimestamp()
|
||||
|
||||
if (!publicKey || !privateKey) {
|
||||
console.error('[API] ❌ Missing API keys in .env!')
|
||||
|
|
@ -66,11 +96,12 @@ apiClient.interceptors.request.use((config) => {
|
|||
|
||||
config.headers['X-Timestamp'] = timestamp
|
||||
|
||||
// 🆕 Получаем или создаём device_id
|
||||
// Получаем или создаём device_id
|
||||
const deviceId = getOrCreateDeviceId()
|
||||
config.headers['x-device-id'] = deviceId
|
||||
|
||||
console.log('[API] ✅ Added device_id:', deviceId)
|
||||
console.log('[API] 🕐 Using timestamp:', timestamp, 'offset:', serverTimeOffset)
|
||||
console.log('[API] === Request interceptor finished ===')
|
||||
|
||||
return config
|
||||
|
|
@ -82,7 +113,7 @@ apiClient.interceptors.response.use(
|
|||
console.log('[API] ✅ Response success:', response.config.url)
|
||||
return response
|
||||
},
|
||||
(error) => {
|
||||
async (error) => {
|
||||
console.error('[API] ❌ Response error:', {
|
||||
status: error.response?.status,
|
||||
statusText: error.response?.statusText,
|
||||
|
|
@ -90,14 +121,47 @@ apiClient.interceptors.response.use(
|
|||
url: error.config?.url,
|
||||
})
|
||||
|
||||
// 🆕 При ошибке "Timestamp expired" — синхронизируем время и повторяем запрос
|
||||
if (
|
||||
error.response?.status === 401 &&
|
||||
error.response?.data === 'Timestamp expired\n' &&
|
||||
!error.config._retry
|
||||
) {
|
||||
console.warn('[API] ⚠️ Timestamp expired, syncing with server...')
|
||||
error.config._retry = true
|
||||
|
||||
await syncTimeWithServer()
|
||||
|
||||
// Пересоздаём подпись с новым timestamp
|
||||
const publicKey = import.meta.env.VITE_API_PUBLIC_KEY
|
||||
const privateKey = import.meta.env.VITE_API_PRIVATE_KEY
|
||||
const newTimestamp = getCorrectedTimestamp()
|
||||
|
||||
error.config.headers['X-Timestamp'] = newTimestamp
|
||||
error.config.headers['ApiKey'] = generateHmacSignature(
|
||||
publicKey,
|
||||
newTimestamp,
|
||||
privateKey
|
||||
)
|
||||
|
||||
return apiClient(error.config)
|
||||
}
|
||||
|
||||
if (error.response?.status === 401) {
|
||||
console.warn('[API] ⚠️ Unauthorized, redirecting to login')
|
||||
localStorage.removeItem('token')
|
||||
// НЕ удаляем device_id!
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// 🆕 Синхронизируем время при загрузке модуля
|
||||
syncTimeWithServer()
|
||||
|
||||
// 🆕 Периодическая синхронизация каждые 5 минут
|
||||
setInterval(() => {
|
||||
syncTimeWithServer()
|
||||
}, 5 * 60 * 1000)
|
||||
|
||||
export default apiClient
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
import axios from 'axios'
|
||||
|
||||
const publicApiClient = axios.create({
|
||||
baseURL: '/api',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
export interface ServerTimeResponse {
|
||||
timestamp: number
|
||||
iso: string
|
||||
}
|
||||
|
||||
export const timeApi = {
|
||||
getServerTime: async (): Promise<ServerTimeResponse> => {
|
||||
const response = await publicApiClient.get<ServerTimeResponse>('/time')
|
||||
return response.data
|
||||
},
|
||||
}
|
||||
Loading…
Reference in New Issue