fix: authorization / registration

This commit is contained in:
2026-05-10 19:24:32 +03:00
parent 574e27a379
commit 8b0e787fc6
11 changed files with 140 additions and 39 deletions

View File

@@ -1,28 +1,37 @@
import { API_URL } from '@shared/config/env'
import { getCsrfToken } from './csrf'
import { tokenStore, refreshAccessToken } from './tokenStore'
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = await getCsrfToken()
async function doRequest<T>(path: string, options: RequestInit, allowRetry: boolean): Promise<T> {
const csrf = await getCsrfToken()
const bearer = tokenStore.get()
const res = await fetch(`${API_URL}${path}`, {
...options,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': token,
...options.headers,
},
})
const headers: HeadersInit = {
'Content-Type': 'application/json',
'X-CSRF-Token': csrf,
...(bearer ? { Authorization: `Bearer ${bearer}` } : {}),
...options.headers,
}
const res = await fetch(`${API_URL}${path}`, { ...options, credentials: 'include', headers })
if (res.status === 401 && allowRetry) {
try {
await refreshAccessToken()
return doRequest<T>(path, options, false)
} catch {
tokenStore.clear()
throw new Error('Unauthorized')
}
}
const data = await res.json()
if (!res.ok) throw data
return data as T
}
export const api = {
get: <T>(path: string) => request<T>(path),
get: <T>(path: string) => doRequest<T>(path, {}, true),
post: <T>(path: string, body: unknown) =>
request<T>(path, { method: 'POST', body: JSON.stringify(body) }),
doRequest<T>(path, { method: 'POST', body: JSON.stringify(body) }, true),
}

View File

@@ -0,0 +1,17 @@
let accessToken: string | null = null
export const tokenStore = {
get: () => accessToken,
set: (token: string) => { accessToken = token },
clear: () => { accessToken = null },
}
const REFRESH_URL = 'https://app.auth.elcsa.ru/v1/jwt/refresh'
export async function refreshAccessToken(): Promise<string> {
const res = await fetch(REFRESH_URL, { method: 'POST', credentials: 'include' })
if (!res.ok) throw new Error('Unauthorized')
const data = await res.json()
tokenStore.set(data.access_token)
return data.access_token as string
}