Skip to content

Commit 6d28f1f

Browse files
committed
feat: add bearer token mechanism
1 parent 67d3b0e commit 6d28f1f

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/core/infra/repositories/ApiConfig.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,19 +2,23 @@ export class ApiConfig {
22
static dataverseApiUrl: string
33
static dataverseApiAuthMechanism: DataverseApiAuthMechanism
44
static dataverseApiKey?: string
5+
static bearerTokenLocalStorageKey?: string
56

67
static init(
78
dataverseApiUrl: string,
89
dataverseApiAuthMechanism: DataverseApiAuthMechanism,
9-
dataverseApiKey?: string
10+
dataverseApiKey?: string,
11+
bearerTokenLocalStorageKey?: string
1012
) {
1113
this.dataverseApiUrl = dataverseApiUrl
1214
this.dataverseApiAuthMechanism = dataverseApiAuthMechanism
1315
this.dataverseApiKey = dataverseApiKey
16+
this.bearerTokenLocalStorageKey = bearerTokenLocalStorageKey
1417
}
1518
}
1619

1720
export enum DataverseApiAuthMechanism {
1821
API_KEY = 'api-key',
19-
SESSION_COOKIE = 'session-cookie' // Temporal and only for dev purposes
22+
SESSION_COOKIE = 'session-cookie', // Temporal and only for dev purposes
23+
BEARER_TOKEN = 'bearer-token'
2024
}

src/core/infra/repositories/apiConfigBuilders.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,14 @@ export const buildRequestConfig = (
1313
headers: {
1414
'Content-Type': contentType
1515
},
16+
withCredentials: false,
1617
...(abortSignal && { signal: abortSignal })
1718
}
19+
1820
if (!authRequired) {
1921
return requestConfig
2022
}
23+
2124
switch (ApiConfig.dataverseApiAuthMechanism) {
2225
case DataverseApiAuthMechanism.SESSION_COOKIE:
2326
/*
@@ -32,10 +35,36 @@ export const buildRequestConfig = (
3235
requestConfig.headers['X-Dataverse-Key'] = ApiConfig.dataverseApiKey
3336
}
3437
break
38+
39+
case DataverseApiAuthMechanism.BEARER_TOKEN: {
40+
if (!ApiConfig.bearerTokenLocalStorageKey) {
41+
throw new Error(
42+
'Bearer token local storage key is not set in the ApiConfig, when using bearer token auth mechanism you must set the bearerTokenLocalStorageKey'
43+
)
44+
}
45+
46+
const token = getLocalStorageItem<string>(ApiConfig.bearerTokenLocalStorageKey)
47+
48+
if (token) {
49+
requestConfig.headers.Authorization = `Bearer ${token}`
50+
}
51+
requestConfig.withCredentials = false
52+
break
53+
}
3554
}
3655
return requestConfig
3756
}
3857

3958
export const buildRequestUrl = (apiEndpoint: string): string => {
4059
return `${ApiConfig.dataverseApiUrl}${apiEndpoint}`
4160
}
61+
62+
export const getLocalStorageItem = <T>(key: string): T | null => {
63+
try {
64+
const item = localStorage.getItem(key)
65+
return item ? (JSON.parse(item) as T) : null
66+
} catch (error) {
67+
console.error(`Error parsing localStorage key "${key}":`, error)
68+
return null
69+
}
70+
}

0 commit comments

Comments
 (0)