(mode: AuthenticationMode = 'cookie', config: Partial<AuthenticationConfig> = {})
| 37 | * @returns A Directus authentication client. |
| 38 | */ |
| 39 | export const authentication = (mode: AuthenticationMode = 'cookie', config: Partial<AuthenticationConfig> = {}) => { |
| 40 | return <Schema>(client: DirectusClient<Schema>): AuthenticationClient<Schema> => { |
| 41 | const authConfig = { ...defaultConfigValues, ...config }; |
| 42 | let refreshPromise: Promise<AuthenticationData> | null = null; |
| 43 | let refreshTimeout: ReturnType<typeof setTimeout> | null = null; |
| 44 | const storage = authConfig.storage ?? memoryStorage(); |
| 45 | |
| 46 | const resetStorage = async () => |
| 47 | storage.set({ access_token: null, refresh_token: null, expires: null, expires_at: null }); |
| 48 | |
| 49 | const activeRefresh = async () => { |
| 50 | try { |
| 51 | await refreshPromise; |
| 52 | } finally { |
| 53 | refreshPromise = null; |
| 54 | } |
| 55 | }; |
| 56 | |
| 57 | const refreshIfExpired = async () => { |
| 58 | const authData = await storage.get(); |
| 59 | |
| 60 | if (refreshPromise || !authData?.expires_at) { |
| 61 | return activeRefresh(); |
| 62 | } |
| 63 | |
| 64 | if (authData.expires_at < new Date().getTime() + authConfig.msRefreshBeforeExpires) { |
| 65 | refresh().catch((_err) => { |
| 66 | /* throw err; */ |
| 67 | }); |
| 68 | } |
| 69 | |
| 70 | return activeRefresh(); |
| 71 | }; |
| 72 | |
| 73 | const setCredentials = async (data: AuthenticationData) => { |
| 74 | const expires = data.expires ?? 0; |
| 75 | data.expires_at = new Date().getTime() + expires; |
| 76 | await storage.set(data); |
| 77 | |
| 78 | if (authConfig.autoRefresh && expires > authConfig.msRefreshBeforeExpires && expires < MAX_INT32) { |
| 79 | if (refreshTimeout) clearTimeout(refreshTimeout); |
| 80 | |
| 81 | refreshTimeout = setTimeout(() => { |
| 82 | refreshTimeout = null; |
| 83 | |
| 84 | refresh().catch((_err) => { |
| 85 | /* throw err; */ |
| 86 | }); |
| 87 | }, expires - authConfig.msRefreshBeforeExpires); |
| 88 | } |
| 89 | }; |
| 90 | |
| 91 | const refresh = async (options: Omit<RefreshOptions, 'refresh_token'> = {}) => { |
| 92 | const awaitRefresh = async () => { |
| 93 | const authData = await storage.get(); |
| 94 | |
| 95 | const fetchOptions: RequestInit = { |
| 96 | method: 'POST', |
no test coverage detected