fix(api): send bearer tokens for authenticated requests
This commit is contained in:
1 parent
b7886589cb
commit
251eb6deb9
1 file changed
+15
-1
+15
-1
@@ -1,4 +1,5 @@
|
|||||||
import { API_BASE_URL, getAuthUserId } from '../config';
|
import { API_BASE_URL, getAuthUserId } from '../config';
|
||||||
|
import { acquireAccessToken } from './auth/token-provider';
|
||||||
|
|
||||||
export class ApiError extends Error {
|
export class ApiError extends Error {
|
||||||
readonly data: unknown;
|
readonly data: unknown;
|
||||||
@@ -42,6 +43,14 @@ async function readResponseBody(response: Response): Promise<unknown> {
|
|||||||
return text ? text : null;
|
return text ? text : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function resolveAccessToken(): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
return await acquireAccessToken();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function apiFetch<T>(
|
export async function apiFetch<T>(
|
||||||
path: string,
|
path: string,
|
||||||
options: ApiFetchOptions = {},
|
options: ApiFetchOptions = {},
|
||||||
@@ -54,8 +63,13 @@ export async function apiFetch<T>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (auth !== 'none' && !requestHeaders.has('Authorization')) {
|
if (auth !== 'none' && !requestHeaders.has('Authorization')) {
|
||||||
|
const accessToken = auth === 'dev' ? null : await resolveAccessToken();
|
||||||
|
if (accessToken) {
|
||||||
|
requestHeaders.set('Authorization', `Bearer ${accessToken}`);
|
||||||
|
}
|
||||||
|
|
||||||
const authUserId = getAuthUserId();
|
const authUserId = getAuthUserId();
|
||||||
if (authUserId) {
|
if (!accessToken && authUserId) {
|
||||||
requestHeaders.set('x-auth-user-id', authUserId);
|
requestHeaders.set('x-auth-user-id', authUserId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user