mirror of
https://github.com/azaion/ui.git
synced 2026-06-24 19:01:11 +00:00
chore: update API configuration and enhance authentication handling
- Updated Vite configuration to use the production API endpoint. - Modified TypeScript build info to include new config file. - Refactored API client to support authenticated URLs. - Updated various components to utilize the new authenticated API URL for media fetching. - Removed obsolete CSS and JS files from the distribution directory.
This commit is contained in:
+12
-3
@@ -1,3 +1,5 @@
|
||||
import { apiUrl } from '../config'
|
||||
|
||||
let accessToken: string | null = null
|
||||
|
||||
export function setToken(token: string | null) {
|
||||
@@ -8,6 +10,13 @@ export function getToken() {
|
||||
return accessToken
|
||||
}
|
||||
|
||||
export function authenticatedApiUrl(path: string): string {
|
||||
const url = apiUrl(path)
|
||||
if (!accessToken) return url
|
||||
const separator = url.includes('?') ? '&' : '?'
|
||||
return `${url}${separator}access_token=${encodeURIComponent(accessToken)}`
|
||||
}
|
||||
|
||||
async function handleResponse<T>(res: Response): Promise<T> {
|
||||
if (res.status === 204) return undefined as T
|
||||
if (!res.ok) {
|
||||
@@ -22,13 +31,13 @@ async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
if (accessToken) headers.set('Authorization', `Bearer ${accessToken}`)
|
||||
if (options.body && typeof options.body === 'string') headers.set('Content-Type', 'application/json')
|
||||
|
||||
let res = await fetch(url, { ...options, headers })
|
||||
let res = await fetch(apiUrl(url), { ...options, headers, credentials: 'include' })
|
||||
|
||||
if (res.status === 401 && accessToken) {
|
||||
const refreshed = await refreshToken()
|
||||
if (refreshed) {
|
||||
headers.set('Authorization', `Bearer ${accessToken}`)
|
||||
res = await fetch(url, { ...options, headers })
|
||||
res = await fetch(apiUrl(url), { ...options, headers, credentials: 'include' })
|
||||
} else {
|
||||
setToken(null)
|
||||
window.location.href = '/login'
|
||||
@@ -41,7 +50,7 @@ async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
|
||||
async function refreshToken(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch('/api/admin/auth/refresh', { method: 'POST', credentials: 'include' })
|
||||
const res = await fetch(apiUrl('/api/admin/auth/refresh'), { method: 'POST', credentials: 'include' })
|
||||
if (!res.ok) return false
|
||||
const data = await res.json()
|
||||
setToken(data.token)
|
||||
|
||||
Reference in New Issue
Block a user